<template>
  <div id="index">
    <el-row>
      <el-col :span="24" class="main">
        <el-col :span="24" class="one">
          <el-col :span="24" class="one_1"> 保安服务公司备案市局审核查询 </el-col>
          <el-col :span="24" class="one_2">
            <search-1 :form="searchForm" @onSubmit="search" :tube_companyList="tube_companyList"></search-1>
          </el-col>
        </el-col>
        <el-col :span="24" class="thr">
          <data-table @query="search" :fields="fields" :opera="opera" :data="list" :total="total" @view="toView" @check="toCheck"> </data-table>
        </el-col>
      </el-col>
    </el-row>
    <el-dialog class="dialog" :title="dialog.title" :visible.sync="dialog.show" width="60%" :before-close="toClose" :close-on-click-modal="false">
      <template v-if="dialog.type == '1'">
        <form-1 :form="form" :info="info" @toReset="toClose" @onSubmit="onSubmit" :statusList="statusList"></form-1>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import form1 from '../one/parts/form-1.vue';
import search1 from '../one/parts/search-1.vue';
const _ = require('lodash');
const moment = require('moment');
import { mapState, createNamespacedHelpers } from 'vuex';
const { mapActions } = createNamespacedHelpers('company_base');
const { mapActions: dept } = createNamespacedHelpers('police_department');
const { mapActions: examine } = createNamespacedHelpers('company_examine');
const { mapActions: company_licence } = createNamespacedHelpers('company_licence');
export default {
  name: 'index',
  props: {},
  components: { search1, form1 },
  data: function () {
    return {
      // 查询
      searchForm: {},
      // 管辖单位
      deptList: [],
      tube_companyList: [],
      list: [],
      total: 0,
      fields: [
        { label: '企业名称', model: 'company' },
        { label: '企业类别', model: 'purpose' },
        { label: '法定负责人', model: 'legal_personal' },
        { label: '联系电话', model: 'phone' },
        { label: '提交时间', model: 'submit_date' },
        {
          label: '管辖单位',
          model: 'tube_company',
          format: (i) => {
            let data = this.deptList.find((r) => r.id == i);
            if (data) return data.name;
          },
        },
      ],
      opera: [
        { label: '详情', method: 'view' },
        { label: '审核', method: 'check', type: 'danger', display: (i) => i.status == '4' },
      ],
      // 审核
      dialog: { title: '审核信息', show: false, type: '1' },
      info: {},
      form: {},
      // 审核状态
      statusList: [
        { label: '通过', value: '5' },
        { label: '拒绝', value: '2' },
      ],
    };
  },
  async created() {
    await this.searchOther();
    await this.search();
  },
  methods: {
    ...mapActions(['query', 'fetch', 'update']),
    ...dept({ getDept: 'query' }),
    ...examine({ examineCreate: 'create' }),
    ...company_licence({ licenceQuery: 'query', licenceCreate: 'create' }),
    async search({ skip, limit } = {}) {
      // 状态为：1
      // todo:查询该管辖下的注册企业，关联派出所，分局，市局（查询全部）
      const condition = _.cloneDeep(this.searchForm);
      const res = await this.query({ skip, limit, ...condition, '^purpose_id': 'purpose_one,purpose_six', status: '4' });
      if (this.$checkRes(res)) {
        this.$set(this, `list`, res.data);
        this.$set(this, `total`, res.total);
      }
    },
    // 详细信息
    toView({ data }) {
      this.$router.push({ path: '/adminPolice/companyInfo', query: { id: data.id, purpose_id: data.purpose_id } });
    },
    // 审核信息
    async toCheck({ data }) {
      let res = await this.fetch({ id: data.id });
      if (this.$checkRes(res)) {
        this.$set(this, `info`, res.data);
        this.dialog = { title: '审核信息', show: true, type: '1' };
      }
    },
    // 提交审核
    async onSubmit({ data }) {
      data.company_id = this.info.id;
      let res = await this.examineCreate(data);
      if (res.errcode == '0') {
        // 修改企业信息
        this.updateUnit({ id: data.company_id, status: data.status, status_two: data.status_two });
        this.$message({ type: `success`, message: `审核信息创建成功` });
        this.toClose();
      } else {
        this.$message({ type: `error`, message: `${res.errmsg}` });
      }
    },
    // 修改企业信息
    async updateUnit(data) {
      let res = await this.update(data);
      if (res.errcode == '0') {
        // 创建服务许可证表信息
        if (data.status == '5') this.createCert();
        this.$message({ type: `success`, message: `企业信息审核成功` });
      } else {
        this.$message({ type: `error`, message: `${res.errmsg}` });
      }
    },
    // 创建服务许可证表信息
    async createCert() {
      let p1 = await this.licenceQuery();
      if (this.$checkRes(p1)) {
        let p2 = {
          company_id: this.info.id,
          company: this.info.company,
          purpose: this.info.purpose,
          legal_personal: this.info.legal_personal,
          legal_card: this.info.legal_card,
          addres: this.info.addres,
          baoan_sevicetype: this.info.baoan_sevicetype.replace(/[^\u4e00-\u9fa5]/gi, ''),
          register_money: this.info.register_money,
          tube_company: this.info.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 == this.info.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 (p3.errcode == '0') {
          this.$message({ type: `success`, message: `服务许可证创建成功` });
        } else {
          this.$message({ type: `error`, message: `${p3.errmsg}` });
        }
      }
    },
    // 关闭弹框
    toClose() {
      this.dialog = { title: '审核信息', show: false, type: '1' };
      this.search();
    },
    // 查询其他信息
    async searchOther() {
      const res = await this.getDept();
      if (this.$checkRes(res)) {
        this.$set(this, `deptList`, res.data);
        // 按type分类,1:市局;2,分局;3,派出所
        let mid = _.cloneDeep(res.data);
        mid = _.groupBy(mid, 'type');
        let data = [];
        let keys = ['1', '2', '3'];
        for (const key of keys) {
          let label = '';
          let children;
          if (key === '1') {
            label = '市局';
            children = mid[key];
          } else if (key === '2') {
            label = '分局';
            children = mid[key];
          } else if (key === '3') {
            label = '派出所';
            children = mid[key];
          }
          if (children) data.push({ label, children });
        }
        this.$set(this, `tube_companyList`, data);
      }
    },
  },
  computed: {
    ...mapState(['user']),
  },
  metaInfo() {
    return { title: this.$route.meta.title };
  },
  watch: {
    test: {
      deep: true,
      immediate: true,
      handler(val) {},
    },
  },
};
</script>

<style lang="less" scoped>
.main {
  .one {
    .one_1 {
      height: 40px;
      line-height: 40px;
      border-bottom: 1px solid #ccc;
      margin: 0 0 10px 0;
      font-size: 18px;
      font-weight: bold;
    }
  }
}
</style>
