<template>
  <el-form :model="form" :rules="rules" ref="formRef" label-position="top">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="区域名称" prop="gsmc">
          <el-input v-model="form.gsmc"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="区域代码（负责人身份证号）" prop="zjNumber">
          <el-input v-model="form.zjNumber"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="启停状态" prop="enableFlag">
          <el-select v-model="form.enableFlag" placeholder="请选择活动区域">
            <el-option v-for="item in enableDisabledList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="所属区域" prop="areaCodesData">
          <el-cascader class="w100" v-model="form.areaCodesData" :options="treeList" :key="cascaderKey" collapse-tags :props="searchCascaderProps" clearable />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="简称" prop="abbr">
          <el-input v-model="form.abbr"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="服务省份简称" prop="provAbbr">
          <el-select v-model="form.provAbbrList" multiple placeholder="请选择省份">
            <el-option v-for="province in abbreviationsProvincesList" :key="province" :label="province" :value="province" />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="身份证照片（人像面）" prop="frsfzzmZm">
          <uploadCom v-if="uploadComShow" @updateInfo="list => updateInfo(list, 'frsfzzmZm')" :info="form.frsfzzmZm" key="frsfzzmZm" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="身份证照片（国徽面）" prop="frsfzzmBm">
          <uploadCom v-if="uploadComShow" @updateInfo="list => updateInfo(list, 'frsfzzmBm')" :info="form.frsfzzmBm" key="frsfzzmBm" />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script>
import {getDictType} from '@/api/common';
import {getAreaTreeApi} from '@/api/areaTree';
import uploadCom from './uploadCom.vue';
import {mapGetters} from 'vuex';
import {getObjDept} from '@/api/admin/dept';
import {addObj, putObj} from '@/api/wmdaagent';
import {filterCodes, extractPaths} from '@/util/treeUtils.js';
import abbreviationsProvinces from '@/const/abbreviationsProvinces.js';
export default {
  components: {uploadCom},
  data() {
    return {
      uploadComShow: false,
      cascaderKey: 0,
      enableDisabledList: [],
      treeList: [],
      entLevel: 0,
      searchCascaderProps: {
        multiple: true,
        label: 'name',
        value: 'id'
      },
      type: '',
      abbreviationsProvincesList: abbreviationsProvinces,
      form: {
        gsmc: '',
        zjNumber: '',
        enableFlag: '',
        abbr: '',
        provAbbr: '',
        provAbbrList: [],
        areaCodesData: [],
        frsfzzmZm: '',
        frsfzzmBm: ''
      },
      rules: {
        gsmc: [{required: true, message: '请输入团队名称'}, {min: 1, max: 60, message: '长度在 1-60 个字符', trigger: 'blur'}],
        abbr: [{required: true, message: '请输入简称', trigger: 'blur'}],
        provAbbrList: [{required: true, message: '请选择省份简称', trigger: 'change'}],
        zjNumber: [{required: true, message: '请输入负责人身份证号码'}],
        enableFlag: [{required: true, message: '请选择启停状态', trigger: 'change'}],
        areaCodesData: [{required: true, message: '请选择区域', trigger: 'change'}],
        frsfzzmZm: [{required: true, message: '请上传身份证照片（人像面）'}],
        frsfzzmBm: [{required: true, message: '请上传身份证照片（国徽面）'}]
      }
    };
  },
  computed: {
    ...mapGetters(['userInfo'])
  },

  mounted() {
    this.getDict();
  },
  methods: {
    async editShow(row) {
      await this.getDict();
      await getAreaTreeApi().then(res => (this.treeList = res.data.data));
      const areaCodes = row.areaCodes;
      const treeList = JSON.parse(JSON.stringify(this.treeList));
      const currTree = filterCodes(areaCodes, treeList);
      if (currTree) {
        const ids = extractPaths(currTree);
        row.areaCodesData = ids;
      }
      this.form = row;
    },
    uploadComShowFn() {
      this.uploadComShow = true;
    },
    getDict() {
      getDictType({type: 'enable_disabled'}).then(res => (this.enableDisabledList = res.data.data));
      getAreaTreeApi().then(res => (this.treeList = res.data.data));
      const deptId = this.userInfo.deptId;
      getObjDept(deptId).then(data => {
        var deptInfo = data.data.data;
        this.entLevel = deptInfo.level;
      });
    },

    updateInfo(list, type) {
      this.form[type] = list[0].url;
      this.$refs.formRef.validateField(type);
    },
    submitFn(extDrugEntId, type) {
      this.type = type;
      this.$refs.formRef.validate(valid => {
        if (valid) {
          this.submitInfo(extDrugEntId);
          this.$emit('setLoading', true);
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    restForm() {
      this.$refs.formRef.resetFields();
      this.uploadComShow = false;
    },
    async submitInfo(extDrugEntId) {
      if (this.entLevel > 3) {
        this.$message.error('二级代理商不能添加代理商');
        this.$emit('setLoading', false);
        return false;
      }
      const flattenedArray = this.form.areaCodesData.flat();
      const areaCodes = Array.from(new Set(flattenedArray));
      const obj = Object.assign(this.form, {
        areaCodes: areaCodes,
        updateUser: 0,
        agentType: 'AT',
        extDrugEnt: extDrugEntId
      });
      obj.provAbbr = obj.provAbbrList.join(',');
      if (this.type === 'add') {
        const res = await addObj(obj);
        if (res.data.code === 0) {
          this.$message.success('添加成功');
        }
      } else if (this.type === 'edit') {
        const res = await putObj(obj);
        if (res.data.code === 0) {
          this.$message.success('更新成功');
        }
      }
      this.$emit('setLoading', false);
      this.$emit('success');
    }
  }
};
</script>

<style lang="scss" scoped></style>
