<template>
  <div class="m-container">
    <h2>
      <div class="squrt"></div>
      分部管理
    </h2>

    <div class="m-core">
      <save-form
        :inline="true"
        class="searchForm"
        saveKey="contentFlashPage"
        @submit="search"
        :model="searchForm"
      >
        <el-form-item prop="search">
          <el-input
            v-model.trim="searchForm.search"
            clearable
            @keyup.enter.native="search"
            placeholder="分部名称、编号"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button native-type="submit" type="danger">搜索</el-button>
           <el-button @click="onReSet" type="primary">重置</el-button>
        </el-form-item>
      </save-form>
      <el-button
        @click="onBranchOperation('create')"
        v-permission="'organization/add'"
        type="primary"
        style="margin-bottom: 20px"
      >
        新建
      </el-button>
      <!-- 列表 -->
      <div class="tableWrap">
        <el-table
          :data="tableList"
          :header-cell-style="{ background: '#EDEEF0', color: '#444' }"
        >
          <el-table-column align="center" prop="id" label="分部编号">
          </el-table-column>
          <el-table-column align="center" prop="name" label="分部名称">
          </el-table-column>
          <el-table-column align="center" prop="areaName" label="城市">
          </el-table-column>
          <el-table-column align="center" prop="address" label="分部地址">
          </el-table-column>
          <el-table-column align="center" label="学年制">
            <template slot-scope="scope">
              {{ scope.row.gradeType | gradeTypeFormat }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="成立时间">
            <template slot-scope="scope">
              {{ scope.row.registerDate | formatTimer }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-button
                @click="onBranchOperation('update', scope.row)"
                v-permission="'organization/update'"
                type="text"
                >修改</el-button
              >
              <el-button
                @click="showCode(scope.row)"
                v-permission="'organization/update'"
                type="text"
                >注册二维码</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <pagination
          sync
          :total.sync="pageInfo.total"
          :page.sync="pageInfo.page"
          :limit.sync="pageInfo.limit"
          :page-sizes="pageInfo.page_size"
          @pagination="getList"
        />
      </div>
    </div>

    <el-dialog
      :title="formTitle[formActionTitle]"
      :visible.sync="branchStatus"
      @close="onFormClose('ruleForm')"
      width="600px"
    >
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <!-- <el-alert
          style="margin: 20px 0"
          title="分部信息"
          :closable="false"
          type="info"
        >
        </el-alert> -->
        <el-form-item
          label="分部名称"
          prop="name"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model.trim="form.name"
            placeholder="请输入分部名称"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="城市" required :label-width="formLabelWidth">
          <el-col :span="12">
            <el-form-item prop="province">
              <el-select
                v-model.trim="form.province"
                filterable
                placeholder="请选择省"
                clearable
                @change="onChangeProvince"
              >
                <el-option
                  v-for="item in provinceList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="city">
              <el-select
                v-model.trim="form.city"
                filterable
                placeholder="请选择市"
                clearable
              >
                <el-option
                  v-for="item in cityList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item
          label="学年制"
          prop="gradeType"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model.trim="form.gradeType"
            filterable
            placeholder="请选择学年制"
            clearable
          >
            <el-option label="6+3" value="SIX_PLUS"></el-option>
            <el-option label="5+4" value="FIVE_PLUS"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="分部地址"
          prop="address"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model.trim="form.address"
            placeholder="请输入分部地址"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="成立时间"
          prop="registerDate"
          :label-width="formLabelWidth"
        >
          <el-date-picker
            v-model.trim="form.registerDate"
            type="date"
            value-format="yyyy-MM-dd"
            :picker-options="{
              firstDayOfWeek: 1,
            }"
            placeholder="选择成立时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item
          label="公司名称"
          prop="corporateName"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model.trim="form.corporateName"
            placeholder="请输入公司名称"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="营业执照编号"
          prop="corporateCode"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model.trim="form.corporateCode"
            placeholder="请输入营业执照编号"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="企业公章"
          prop="corporateSeal"
          :label-width="formLabelWidth"
        >
          <div style="width: 300px !important" class="ant-upload-preview">
            <!-- <el-upload
              class="avatar-uploader"
              action="/api-web/uploadFile"
              accept=".png"
              :headers="headers"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <i v-if="form.corporateSeal" @click.stop="form.corporateSeal = null" class="el-icon-error" style="position: absolute;right: -14px;font-size: 28px;top: -14px;color: #787878;background: #fff;"></i>
              <img
                v-if="form.corporateSeal"
                :src="form.corporateSeal"
                class="avatar"
              />
              <span v-else>
                <i class="el-icon-plus avatar-uploader-icon"></i>
                <span class="upload-desc">添加上传图片</span>
              </span>
            </el-upload> -->
            <image-cropper
              :options="{
                autoCrop: true, //是否默认生成截图框
                autoCropWidth: 300, //默认生成截图框宽度
                autoCropHeight: 300, //默认生成截图框高度
                fixedBox: true, //是否固定截图框大小 不允许改变
                previewsCircle: false, //预览图是否是圆形
                title: '上传企业公章', //模态框上显示的标题
              }"
              isDelete
              :imgSize="5"
              accept=".png"
              :acceptArray="['image/png']"
              :imageUrl.sync="form.corporateSeal"
              @crop-upload-success="cropSuccess1"
            />
            <div class="tips" style="line-height: 1.3; color: red">
              请上传透明背景PNG格式公章图片；<br />
              仅支持图片格式：png，大小：5MB；
            </div>
          </div>
        </el-form-item>
        <el-form-item
          label="企业财务公章"
          prop="corporateFinancialSeal"
          :label-width="formLabelWidth"
        >
          <div style="width: 300px !important" class="ant-upload-preview">
            <!-- <el-upload
              class="avatar-uploader"
              action="/api-web/uploadFile"
              accept=".png"
              :headers="headers"
              :show-file-list="false"
              :on-success="handleAvatarSuccess2"
              :before-upload="beforeAvatarUpload"
            >
              <i v-if="form.corporateFinancialSeal" @click.stop="form.corporateFinancialSeal = null" class="el-icon-error" style="position: absolute;right: -14px;font-size: 28px;top: -14px;color: #787878;background: #fff;"></i>
              <img
                v-if="form.corporateFinancialSeal"
                :src="form.corporateFinancialSeal"
                class="avatar"
              />
              <span v-else>
                <i class="el-icon-plus avatar-uploader-icon"></i>
                <span class="upload-desc">添加上传图片</span>
              </span>
            </el-upload> -->
            <image-cropper
              :options="{
                autoCrop: true, //是否默认生成截图框
                autoCropWidth: 300, //默认生成截图框宽度
                autoCropHeight: 300, //默认生成截图框高度
                fixedBox: true, //是否固定截图框大小 不允许改变
                previewsCircle: false, //预览图是否是圆形
                title: '上传企业财务公章', //模态框上显示的标题
              }"
              isDelete
              :imgSize="5"
              accept=".png"
              :acceptArray="['image/png']"
              :imageUrl.sync="form.corporateFinancialSeal"
              @crop-upload-success="cropSuccess2"
            />
            <div class="tips" style="line-height: 1.3; color: red">
              请上传透明背景PNG格式公章图片；<br />
              仅支持图片格式：png，大小：5MB；
            </div>
          </div>
        </el-form-item>
        <!-- <el-alert
          style="margin: 20px 0"
          title="分部人员配置"
          :closable="false"
          type="info"
        >
        </el-alert>
        <el-form-item label="分部经理" prop="organManager" :label-width="formLabelWidth">
          <el-select
            v-model.trim="form.organManager"
            filterable
            clearable
            multiple
          >
            <el-option
              v-for="item in employeeList"
              :key="item.id"
              :label="item.realName"
              :value="item.id+''"
            >
              <span style="float: left">{{ item.realName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                String(item.id)
              }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="乐团主管" prop="educationId" :label-width="formLabelWidth">
          <el-select
            v-model.trim="form.educationId"
            filterable
            clearable
            multiple
          >
            <el-option
              v-for="item in employeeList"
              :key="item.id"
              :label="item.realName"
              :value="item.id+''"
            >
              <span style="float: left">{{ item.realName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                String(item.id)
              }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="维修技师" prop="repairId" :label-width="formLabelWidth">
          <el-select v-model.trim="form.repairId" filterable clearable multiple>
            <el-option
              v-for="item in employeeList"
              :key="item.id"
              :label="item.realName"
              :value="item.id+''"
            >
              <span style="float: left">{{ item.realName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                String(item.id)
              }}</span>
            </el-option>
          </el-select>
        </el-form-item>
               <el-form-item label="衔接老师" prop="joinTeacherId" :label-width="formLabelWidth">
          <el-select v-model.trim="form.joinTeacherId" filterable clearable multiple>
            <el-option
              v-for="item in employeeList"
              :key="item.id"
              :label="item.realName"
              :value="item.id+''"
            >
              <span style="float: left">{{ item.realName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                String(item.id)
              }}</span>
            </el-option>
          </el-select>
        </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="branchStatus = false">取 消</el-button>
        <el-button @click="onBranchSubmit('ruleForm')" type="primary"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <qr-code v-model="codeStatus" :title="codeTitle" :codeUrl="qrCodeUrl" />
  </div>
</template>
<script>
import { getToken } from "@/utils/auth";
import pagination from "@/components/Pagination/index";
import qrCode from "@/components/QrCode/index";
import {
  branchQueryPage,
  areaQueryChild,
  branchAdd,
  branchUpdate,
  getParentArea,
} from "@/api/specialSetting";
import { vaildStudentUrl } from "@/utils/validate";
import { queryEmployByOrganId } from "@/api/systemManage";
import ImageCropper from "@/components/ImageCropper";
export default {
  name: "branchSetting",
  components: { pagination, qrCode, ImageCropper },
  data() {
    return {
      headers: {
        Authorization: getToken(),
      },
      tableList: [],
      pageInfo: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50], // 选择限制显示条数
      },
      organId: null,
      formActionTitle: "create",
      formTitle: {
        create: "添加分部",
        update: "修改分部",
      },
      formLabelWidth: "100px",
      branchStatus: false,
      provinceList: [], // 省列表
      cityList: [], // 市列表
      employeeList: [], // 分部下的员工集合
      form: {
        name: null,
        province: null,
        city: null,
        address: null,
        registerDate: null,
        gradeType: "SIX_PLUS",
        organManager: [],
        educationId: [],
        repairId: [],
        joinTeacherId: [],
        corporateName: null,
        corporateCode: null,
        corporateSeal: null,
        corporateFinancialSeal: null,
      },
      rules: {
        name: [{ required: true, message: "请输入分部名称", trigger: "blur" }],
        province: [{ required: true, message: "请选择省", trigger: "change" }],
        city: [{ required: true, message: "请选择市", trigger: "change" }],
        address: [
          { required: true, message: "请输入分部地址", trigger: "blur" },
        ],
        registerDate: [
          { required: true, message: "请选择成立时间", trigger: "change" },
        ],
        gradeType: [
          { required: true, message: "请选择学年制", trigger: "change" },
        ],
      },
      codeStatus: false,
      qrCodeUrl: null,
      codeTitle: "注册二维码",
      searchForm: {
        search: "",
      },
    };
  },
  mounted() {
    this.getList();
    this.getAreaList();
  },
  methods: {
    cropSuccess1(data) {
      this.form.corporateSeal = data.data.url;
    },
    cropSuccess2(data) {
      this.form.corporateFinancialSeal = data.data.url;
    },
    onReSet(){
      this.searchForm.search = ''
      this.search();
    },
    search() {
      this.rules.page = 1;
      this.getList();
    },
    beforeAvatarUpload(file) {
      const imageType = {
        "image/png": true,
      };
      const isImage = imageType[file.type];
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isImage) {
        this.$message.error("只能上传图片格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 5MB!");
        return false;
      }
      return isImage && isLt2M;
    },
    handleAvatarSuccess(res) {
      this.form.corporateSeal = res.data.url;
    },
    handleAvatarSuccess2(res) {
      this.form.corporateFinancialSeal = res.data.url;
    },
    onBranchSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) return;
        this.form.areaId = this.form.city;
        let obj = {
          ...this.form,
          organManager: this.form.organManager.join(","),
          educationId: this.form.educationId.join(","),
          repairId: this.form.repairId.join(","),
          joinTeacherId: this.form.joinTeacherId.join(","),
        };

        if (this.formActionTitle == "create") {
          if (obj.id) {
            // 判断有没有Id，如果有则删除
            delete obj.id;
          }
          branchAdd(obj).then((res) => {
            this.messageTips("添加", res);
          });
        } else if (this.formActionTitle == "update") {
          branchUpdate(obj).then((res) => {
            this.messageTips("修改", res);
          });
        }
      });
    },
    messageTips(title, res) {
      if (res.code == 200) {
        this.$message.success(title + "成功");
        this.branchStatus = false;
        this.getList();
      } else {
        this.$message.error(res.msg);
      }
    },
    getList() {
      branchQueryPage({
        rows: this.pageInfo.limit,
        page: this.pageInfo.page,
        ...this.searchForm,
      }).then((res) => {
        if (res.code == 200 && res.data) {
          this.tableList = res.data.rows;
          this.pageInfo.total = res.data.total;
        }
      });
    },
    onFormClose(formName) {
      // 关闭弹窗重置验证
      this.$refs[formName].resetFields();
      this.form.gradeType = "SIX_PLUS";
    },
    getAreaList(parentId, callback) {
      parentId = parentId ? parentId : 0;
      areaQueryChild({ parentId: parentId }).then((res) => {
        if (res.code == 200 && res.data) {
          let tempData = [];
          res.data.forEach((item) => {
            tempData.push({
              label: item.name,
              value: item.id,
            });
          });
          if (parentId) {
            this.cityList = tempData;
          } else {
            this.provinceList = tempData;
          }

          if (callback && typeof callback == "function") {
            callback();
          }
        }
      });
    },
    onChangeProvince(val) {
      this.form.city = null;
      this.getAreaList(val);
    },
    async onBranchOperation(type, row) {
      // 修改分部信息
      // employeeFindEmployeeByRole
      if (row) {
        try {
          const res = await queryEmployByOrganId({
            organId: row.id,
            rows: 9999,
            demissionflag: false,
            lockFlag: false,
          });
          this.$set(this, "employeeList", res.data.rows);
        } catch (e) {
          console.log(e);
        }
      }
      this.formActionTitle = type;

      if (type == "update") {
        getParentArea({ id: row.areaId }).then((res) => {
          if (res.code == 200 && res.data) {
            this.getAreaList(res.data.id, () => {
              this.form = {
                id: row.id,
                name: row.name,
                province: res.data.id,
                city: row.areaId,
                address: row.address,
                registerDate: row.registerDate,
                gradeType: row.gradeType == 1 ? "FIVE_PLUS" : "SIX_PLUS",
                organManager: row.organManager
                  ? row.organManager.split(",")
                  : [],
                repairId: row.repairId ? row.repairId.split(",") : [],
                joinTeacherId: row.joinTeacherId
                  ? row.joinTeacherId.split(",")
                  : [],
                educationId: row.educationId ? row.educationId.split(",") : [],
                corporateName: row.corporateName,
                corporateCode: row.corporateCode,
                corporateSeal: row.corporateSeal,
                corporateFinancialSeal: row.corporateFinancialSeal,
              };
            });
            this.branchStatus = true;
          }
        });
      } else {
        this.branchStatus = true;
      }
    },
    showCode(row) {
      this.qrCodeUrl =
        vaildStudentUrl() + "/project/register/index.html?organId=" + row.id;
      this.codeStatus = true;
      // qrCodeUrl:null,
    },
  },
};
</script>
<style lang="scss" scoped>
.ant-upload-preview {
  background-color: #fff;
  .avatar-uploader {
    .upload-desc {
      position: absolute;
      bottom: 0;
      left: 0;
      color: #ccc;
      font-size: 8px;
      right: 0;
    }
  }
}
::v-deep .avatar-uploader .el-upload--text {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  margin-right: 20px;
  cursor: pointer;
  position: relative;
  // overflow: hidden;
}
::v-deep .avatar-uploader.uploadDisabled {
  .el-upload--text {
    cursor: not-allowed;
    background-color: #f7f7f7;
  }
  .el-upload:hover {
    border-color: #d9d9d9;
  }
}
::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
::v-deep .avatar-uploader-icon {
  font-size: 22px;
  color: #ccc;
  width: 108px;
  height: 108px;
  line-height: 108px;
  text-align: center;
}
::v-deep.avatar {
  width: 108px;
  height: 108px;
  display: block;
}
/deep/.el-date-editor.el-input {
  width: 100% !important;
}
/deep/.el-select {
  width: 98% !important;
}
</style>
