<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="skuIds">
          <el-select v-model="form.skuIds" multiple placeholder="请选择" class="w100">
            <el-option v-for="item in drugtableList" :key="item.drug_id" :label="item.drug_name" :value="item.drug_id"> </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="服务截止日期" prop="serviceDeadline">
          <el-date-picker
            class="w100"
            v-model="form.serviceDeadline"
            :picker-options="pickerOptions"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          >
          </el-date-picker>
        </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="yyzz">
          <uploadCom v-if="uploadComShow" @updateInfo="list => updateInfo(list, 'yyzz')" :info="form.yyzz" key="yyzz" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="社保缴纳证明" prop="sbjnzm">
          <uploadCom v-if="uploadComShow" @updateInfo="list => updateInfo(list, 'sbjnzm')" :info="form.sbjnzm" key="sbjnzm" />
        </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-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="法人手持身份证明" prop="frsfzzmSc">
          <uploadCom v-if="uploadComShow" @updateInfo="list => updateInfo(list, 'frsfzzmSc')" :info="form.frsfzzmSc" key="frsfzzmSc" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="近12个月依法缴纳税收的记录" prop="taxRecordIn12m">
          <uploadCom v-if="uploadComShow" @updateInfo="list => updateInfo(list, 'taxRecordIn12m')" :info="form.taxRecordIn12m" key="taxRecordIn12m" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="国家企业信用信息公示系统查询报告" prop="publicitySystemQueryResults">
          <uploadCom
            v-if="uploadComShow"
            @updateInfo="list => updateInfo(list, 'publicitySystemQueryResults')"
            :info="form.publicitySystemQueryResults"
            key="publicitySystemQueryResults"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="市场服务协议" prop="marketServicesAgreement">
          <uploadCom
            v-if="uploadComShow"
            listType="file"
            @updateInfo="list => updateInfo(list, 'marketServicesAgreement')"
            :info="form.marketServicesAgreement"
            key="marketServicesAgreement"
          />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="服务包合同" prop="serviceContract">
          <uploadCom v-if="uploadComShow" listType="file" @updateInfo="list => updateInfo(list, 'serviceContract')" :info="form.serviceContract" key="serviceContract" />
        </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 abbreviationsProvinces from '@/const/abbreviationsProvinces.js';

import {mapGetters} from 'vuex';
import {getObjDept} from '@/api/admin/dept';
import {addObj, createAeApi, putObj, getWmdadrugentdrugtableList} from '@/api/wmdaagent';
import {filterCodes, extractPaths} from '@/util/treeUtils.js';
export default {
  components: {uploadCom},
  data() {
    return {
      type: 'add',
      uploadComShow: false,
      cascaderKey: 0,
      enableDisabledList: [],
      treeList: [],
      entLevel: 0,
      type: '',
      abbreviationsProvincesList: abbreviationsProvinces,
      searchCascaderProps: {
        multiple: true,
        label: 'name',
        value: 'id'
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      drugtableList: [],
      form: {
        gsmc: '',
        skuIds: [],
        zjNumber: '',
        enableFlag: '',
        areaCodesData: [],
        yyzz: '',
        sbjnzm: '',
        abbr: '',
        provAbbr: '',
        provAbbrList: [],
        frsfzzmZm: '',
        frsfzzmBm: '',
        frsfzzmSc: '',
        taxRecordIn12m: '',
        publicitySystemQueryResults: '',
        marketServicesAgreement: '',
        serviceContract: '',
        serviceDeadline: ''
      },
      rules: {
        gsmc: [{required: true, message: '请输入企业名称'}, {min: 1, max: 60, message: '长度在 1-60 个字符', trigger: 'blur'}],
        skuIds: [{required: true, message: '请输入服务产品'}],
        abbr: [{required: true, message: '请输入简称', trigger: 'blur'}],
        provAbbrList: [{required: true, message: '请选择省份简称', trigger: 'change'}],
        zjNumber: [{required: true, message: '请输入统一社会信用代码'}],
        serviceDeadline: [{required: true, message: '请输入统一社会信用代码'}],
        enableFlag: [{required: true, message: '请选择启停状态', trigger: 'change'}],
        areaCodesData: [{required: true, message: '请选择区域', trigger: 'change'}],
        yyzz: [{required: true, message: '请上传营业执照'}],
        sbjnzm: [{required: true, message: '请上传社保缴纳证明'}],
        frsfzzmZm: [{required: true, message: '请上传身份证照片（人像面）'}],
        frsfzzmBm: [{required: true, message: '请上传身份证照片（国徽面）'}],
        frsfzzmSc: [{required: true, message: '请上传法人手持身份证明'}],
        taxRecordIn12m: [{required: true, message: '请上传近12个月依法缴纳税收的记录'}],
        publicitySystemQueryResults: [{required: true, message: '请上传近12个月依法缴纳税收的记录'}],
        marketServicesAgreement: [{required: true, message: '请上传市场服务协议'}],
        serviceContract: [{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;
      }
      console.log('row', row);
      this.form = row;
      this.form.skuIds = row.skuIds.split(',');
    },
    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;
      });
      getWmdadrugentdrugtableList().then(res => {
        this.drugtableList = res.data.data;
        console.log('drugtableList', this.drugtableList);
      });
    },
    updateInfo(list, type) {
      this.form[type] = list[0].url;
      this.$refs.formRef.validateField(type);
      this.$emit('setLoading', true);
    },
    submitFn(extDrugEntId, type) {
      this.type = type;
      this.$refs.formRef.validate(valid => {
        if (valid) {
          this.submitInfo(extDrugEntId);
        } 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: 'AE',
        extDrugEnt: extDrugEntId
      });
      obj.provAbbr = obj.provAbbrList.join(',');
      try {
        if (this.type === 'add') {
          const res = await createAeApi(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');
      } catch (err) {
        this.$emit('setLoading', false);
      }
    }
  }
};
</script>

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