<template>
  <div id="deal">
    <el-row :gutter="50">
      <el-col :span="24">
        <data-form :fields="fields" v-model="form" @save="toSubmit">
          <template #status>
            <el-radio v-for="(i, index) in statusList" :key="`status-${index}`" :label="i.value">{{ i.label }}</el-radio>
          </template>
          <template #status_two>
            <el-radio v-for="(i, index) in status_twoList" :key="`status-${index}`" :label="i.value" @change="changeS">{{ i.label }}</el-radio>
          </template>
        </data-form>
      </el-col>
      <!-- <el-col :span="6">right</el-col> -->
    </el-row>
  </div>
</template>

<script>
/*
  本组件为处理企业审核与受理而使用,需要引入受理/审核两个接口.
  只使用query,create,分左右两个区域.左侧意见,右侧时间轴及之前评价的内容
*/
const _ = require('lodash');
const moment = require('moment');
import { mapState, mapGetters, createNamespacedHelpers } from 'vuex';
const { mapActions: accept } = createNamespacedHelpers('company_accept');
const { mapActions: examine } = createNamespacedHelpers('company_examine');
const { mapActions: company_base } = createNamespacedHelpers('company_base');
const { mapActions: company_licence } = createNamespacedHelpers('company_licence');
const { mapActions: company_keep } = createNamespacedHelpers('company_keep');

export default {
  name: 'deal',
  props: {},
  components: {},
  data: function () {
    return {
      list: [],
      form: {},
      fields: [
        { label: '审核结果', model: 'status', type: 'radio', required: true },
        {
          label: '备案状态',
          model: 'status_two',
          type: 'radio',
          required: true,
          is_show: 'purpose_four',
          display: (i) => i.is_show == this.info.purpose_id,
        },
        { label: '审核意见', model: 'resaon', type: 'textarea', options: { maxlength: 50, 'show-word-limit': true } },
      ],
      rules: {
        status: [{ required: true, message: `请选择本次${this.type === 'accept' ? '受理' : '审核'}结果`, trigger: 'change' }],
      },
      statusList: [],
      status_twoList: [
        { label: '建档并补充资料', value: '0' },
        { label: '通过', value: '1' },
      ],
      info: {},
    };
  },
  created() {},
  mounted() {
    this.init();
  },
  methods: {
    ...accept({ acceptQuery: 'query', acceptCreate: 'create' }),
    ...examine({ examineQuery: 'query', examineCreate: 'create' }),
    ...company_base(['update', 'fetch']),
    ...company_licence({ licenceQuery: 'query', licenceCreate: 'create' }),
    ...company_keep({ keepQuery: 'query', keepCreate: 'create' }),
    async init() {
      const res = await this[`${this.type}Query`]({ company_id: this.id });
      if (this.$checkRes(res)) {
        this.$set(this, `list`, res.data);
      }
      // 查询详情
      const arr = await this.fetch({ id: this.id });
      if (this.$checkRes(res)) {
        this.$set(this, `info`, arr.data);
      }
      const list = [];
      if (this.type === 'accept') list.push({ label: '受理', value: '2' }, { label: '拒受', value: '0' });
      else list.push({ label: '通过', value: '3' }, { label: '拒绝', value: '0' });
      this.$set(this, `statusList`, list);
    },
    async toSubmit({ data }) {
      const company_id = this.id;
      const examine_prsonal = this.user.name;
      const examine_date = moment().format('YYYY-MM-DD HH:mm:ss');
      let dup = _.cloneDeep(data);
      let status_two = dup.status_two;
      dup = { ...dup, company_id, examine_prsonal, examine_date };
      dup.status_two = undefined;
      const res = await this[`${this.type}Create`](dup);
      let word = this.type === 'accept' ? '受理' : '审核';
      if (this.$checkRes(res)) {
        let p1 = await this.update({ id: this.id, status: dup.status, status_two: status_two });
        if (this.$checkRes(p1, `${word}成功`, `${word}失败`)) {
          if (dup.status == '3') this.createCert(dup.company_id);
          this.$emit('close');
        }
      }
    },
    // 查询企业详情，当企业为保安服务公司时，创建许可证表
    async createCert(company_id) {
      let res = await this.fetch({ id: company_id });
      if (this.$checkRes(res)) {
        let data = res.data;
        if (data.purpose_id == 'purpose_one' || data.purpose_id == 'purpose_six') {
          // 查询证编号到了多少，以次往下加，并创建发放表
          this.searchLicence(company_id, data);
        } else if (data.purpose_id == 'purpose_four') {
          // 查询证件编号到了多少，以次往下加数。并创建发放表
          this.searchKeep(company_id, data);
        }
      }
    },
    // 查询证件编号，以次往下加，并创建发放表
    async searchLicence(company_id, data) {
      let p1 = await this.licenceQuery();
      if (this.$checkRes(p1)) {
        let p2 = {
          company_id: company_id,
          company: data.company,
          purpose: data.purpose,
          legal_personal: data.legal_personal,
          legal_card: data.legal_card,
          addres: data.addres,
          baoan_sevicetype: data.baoan_sevicetype.replace(/[^\u4e00-\u9fa5]/gi, ''),
          register_money: data.register_money,
          tube_company: data.tube_company,
          approve_date: moment(new Date()).format('YYYY-MM-DD'),
          cert_date: moment(new Date()).format('YYYY-MM-DD'),
          effective_date: moment(moment().add(1, 'Y')).format('YYYY年MM月DD日'),
        };
        // 判断是否有证书，未有第一个证书为00001，有的话，以次往下加
        if (p1.total > 0) {
          // 查找是否已经发过证，已发证者编号不变，未发证查找编号，以次往下加
          let oneData = p1.data.find((i) => i.company_id == company_id);
          if (oneData) {
            p2.licence_num = oneData.licence_num;
            p2.approval_num = '吉林省公保服' + oneData.licence_num + '号';
          } else {
            let num = p1.total + 1;
            if (num.toString().length == 1) num = '000' + num;
            else if (num.toString().length == 2) num = '00' + num;
            else if (num.toString().length == 3) num = '0' + num;
            else num;
            p2.licence_num = moment(new Date()).format('YYYY') + num;
            p2.approval_num = '吉林省公保服' + moment(new Date()).format('YYYY') + num + '号';
          }
        } else {
          p2.licence_num = moment(new Date()).format('YYYY') + '0001';
          p2.approval_num = '吉林省公保服' + moment(new Date()).format('YYYY') + '0001' + '号';
        }
        // 取当前颁证用户机构代码的前4位
        p2.licence_num = `${_.padEnd(this.user.department_code, 4, '0') || '2201'}${p2.licence_num}`;
        let p3 = await this.licenceCreate(p2);
        if (this.$checkRes(p3)) {
          this.$message({ type: `success`, message: `服务许可证创建成功` });
        } else {
          this.$message({ type: `error`, message: `${p3.errmsg}` });
        }
      }
    },
    // 查询证件编号，以次往下加，并创建发放表
    async searchKeep(company_id, data) {
      let p1 = await this.keepQuery();
      if (this.$checkRes(p1)) {
        let p2 = {
          company_id: company_id,
          company: data.company,
          purpose: data.purpose,
          legal_personal: data.legal_personal,
          legal_card: data.legal_card,
          addres: data.addres,
          baoan_sevicetype: data.baoan_sevicetype.replace(/[^\u4e00-\u9fa5]/gi, ''),
          register_money: data.register_money,
          tube_company: data.tube_company,
          approve_date: moment(new Date()).format('YYYY-MM-DD'),
          cert_date: moment(new Date()).format('YYYY-MM-DD'),
          effective_date: moment(moment().add(1, 'Y')).format('YYYY年MM月DD日'),
        };
        // 判断是否有证书，未有第一个证书为00001，有的话，以次往下加
        if (p1.total > 0) {
          // 查找是否已经发过证，已发证者编号不变，未发证查找编号，以次往下加
          let oneData = p1.data.find((i) => i.company_id == company_id);
          if (oneData) {
            p2.licence_num = oneData.licence_num;
            p2.approval_num = '吉林省公保服' + oneData.licence_num + '号';
          } else {
            let num = p1.total + 1;
            if (num.toString().length == 1) num = '000' + num;
            else if (num.toString().length == 2) num = '00' + num;
            else if (num.toString().length == 3) num = '0' + num;
            else num;
            p2.licence_num = moment(new Date()).format('YYYY') + num;
            p2.approval_num = '吉林省公保服' + moment(new Date()).format('YYYY') + num + '号';
          }
        } else {
          p2.licence_num = moment(new Date()).format('YYYY') + '0001';
          p2.approval_num = '吉林省公保服' + moment(new Date()).format('YYYY') + '0001' + '号';
        }
        let p3 = await this.keepCreate(p2);
        if (this.$checkRes(p3)) {
          this.$message({ type: `success`, message: `服务许可证创建成功` });
        } else {
          this.$message({ type: `error`, message: `${p3.errmsg}` });
        }
      }
    },
    changeS(value) {
      if (value == 0) this.$set(this.form, `resaon`, '建档，需要后期完善相关保安资料');
      else this.$set(this.form, `resaon`, '通过');
    },
  },
  computed: {
    ...mapState(['user']),
    id() {
      return this.$route.query.id;
    },
    type() {
      // 3种情况:
      /*
        1.info:详情 与状态无关
        2.accept:受理 0=>1 ;再走审批
        3.approve:审批 0/1=>2
        2,3 主要是区分受理/审核的接口
       */
      return this.$route.params.type === 'accept' ? 'accept' : 'examine';
    },
  },
  metaInfo() {
    return { title: this.$route.meta.title };
  },
};
</script>

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