<template>
  <div id="index">
    <el-row>
      <el-col :span="24" class="main">
        <el-col :span="24" v-if="printShow == '1'">
          <el-col :span="24" class="one">
            <el-col :span="24" class="one_1"> 保安员证制作信息查询 </el-col>
            <el-col :span="24" class="one_2">
              <el-form ref="searchFrom" :model="searchFrom" label-width="130px">
                <el-col :span="24" class="one_2txt">
                  <el-col :span="8">
                    <el-form-item label="姓名">
                      <el-input v-model="searchFrom.name"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="身份证号">
                      <el-input v-model="searchFrom.card"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="联系电话">
                      <el-input v-model="searchFrom.phone"></el-input>
                    </el-form-item>
                  </el-col>
                </el-col>
                <el-col :span="24" class="one_2txt">
                  <el-col :span="24" class="btn">
                    <el-button type="primary" size="mini" @click="morePrint()">批量打印</el-button>
                    <el-button type="primary" size="mini" @click="search()">查询</el-button>
                  </el-col>
                </el-col>
              </el-form>
            </el-col>
          </el-col>
          <el-col :span="24" class="two">
            <data-table
              @query="search"
              :fields="fields"
              :opera="opera"
              :data="list"
              :total="total"
              @print="toPrint"
              :select="true"
              :selected="selected"
              @handleSelect="handleSelect"
            >
            </data-table>
          </el-col>
        </el-col>
        <el-col :span="24" v-else-if="printShow == '2'">
          <el-col :span="24" class="thr">
            <el-button type="primary" size="mini" @click="setSize()">设置尺寸</el-button>
            <el-button type="primary" size="mini" @click="certPrint()">打印证书</el-button>
            <el-button type="primary" size="mini" @click="previewPrint()">预览打印</el-button>
            <el-button type="primary" size="mini" @click="back()">返回</el-button>
          </el-col>
          <el-col :span="24" class="four" ref="print">
            <list-1 :list="printList" :baoan_cert_size="baoan_cert_size"></list-1>
          </el-col>
        </el-col>
      </el-col>
    </el-row>
    <el-dialog class="twodialog" title="设置尺寸" :visible.sync="setShow" width="50%" :before-close="setClose" :close-on-click-modal="false">
      <size-1 :baoan_cert_size="baoan_cert_size" @close="setClose" @onSubmit="setSubmit"></size-1>
    </el-dialog>
  </div>
</template>

<script>
import list1 from './parts/list-1.vue';
import size1 from './parts/size-1.vue';
const { exam_grade } = require('@common/src/layout/deploy/dict');
import { mapState, createNamespacedHelpers } from 'vuex';
const { mapActions: certificates_base } = createNamespacedHelpers('certificates_base');
const { mapActions: certificates_grant } = createNamespacedHelpers('certificates_grant');
const { mapActions: certificates_print_log } = createNamespacedHelpers('certificates_print_log');
const { mapActions: sendTemplate } = createNamespacedHelpers('sendTemplate');
const { mapActions: security_guard_base } = createNamespacedHelpers('security_guard_base');
const moment = require('moment');
export default {
  name: 'index',
  props: {},
  components: { list1, size1 },
  data: function () {
    return {
      // 页面显示
      printShow: '1',
      // 查询表单
      searchFrom: {},
      fields: [
        { label: '姓名', model: 'name' },
        { label: '身份证号', model: 'card' },
        { label: '出生日期', model: 'birth' },
        { label: '联系电话', model: 'phone' },
        { label: '职业等级', model: 'exam_grade' },
        { label: '保安员编号', model: 'baoan_num' },
        { label: '打印日期', model: 'print_date' },
        { label: '发证日期', model: 'cert_date' },
        { label: '发证公安机关', model: 'cert_police' },
        { label: '是否制作保安员证', model: 'is_cert', format: (i) => (i == '0' ? '否' : '是') },
        { label: '是否领取', model: 'is_receive', format: (i) => (i == '0' ? '未领取' : '已领取') },
      ],
      opera: [{ label: '打印', method: 'print', display: (i) => i.is_cert == '0' }],
      list: [],
      total: 0,
      exam_gradeList: exam_grade,
      // 打印
      // 打印所选原数据列表
      selected: [],
      // 打印尺寸处理数据集
      printList: [],
      // 打印设置尺寸
      baoan_cert_size: {},
      setShow: false,
    };
  },
  async created() {
    // 默认尺寸
    this.searchSize();
    await this.search();
  },
  methods: {
    ...certificates_base(['query', 'fetch', 'update']),
    ...certificates_grant({ grantCreate: 'create' }),
    ...certificates_print_log({ printlogCreate: 'create' }),
    ...sendTemplate(['send']),
    ...security_guard_base({ baseFetch: 'fetch', baseQuery: 'query', baseUpdate: 'update' }),
    async search({ skip = 0, limit = 10, ...info } = {}) {
      const condition = _.cloneDeep(this.searchFrom);
      let res = await this.query({ skip, limit, ...condition, ...info });
      if (this.$checkRes(res)) {
        this.$set(this, `list`, res.data);
        this.$set(this, `total`, res.total);
      }
    },
    // 打印
    // 批量选择打印证书数据
    handleSelect(data) {
      this.$set(this, `selected`, data);
    },
    // 单个选择打印证书数据
    toPrint({ data }) {
      this.selected.push(data);
      this.morePrint();
    },
    // 打印跳转
    morePrint() {
      let data = _.cloneDeep(this.selected);
      console.log(data);
      for (const val of data) {
        val.birth = moment(val.birth).format('yyyy  MM  DD');
        val.year = moment(new Date()).format('yyyy');
        val.month = moment(new Date()).format('MM');
      }
      this.$set(this, `printList`, data);
      this.printShow = '2';
    },
    // 证书打印
    async certPrint() {
      this.$confirm(`证书一旦打印不可更改,请谨慎操作！`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          // 打印,修改证件表，创建发放记录表，创建打印日志
          let selected = this.selected;
          for (const data of selected) {
            data.cert_police = this.user.department_name;
            data.print_date = moment(new Date()).format('YYYY-MM-DD');
            data.cert_date = data.cert_date ? data.cert_date : moment(new Date()).format('YYYY-MM-DD');
            data.is_cert = '1';
            data.cert_status = '0';
            let p1 = await this.update(data);
            if (this.$checkRes(p1));
          }
          // 创建发放记录
          this.createGrant(selected);
          // 创建打印日志
          this.createJournal(selected);
          // 给考生发送信息，保安员已打印，可预约领取证书了
          this.sendTem(selected);
          this.$print(this.$refs.print);
        })
        .catch(() => {});
    },
    // 预览证书打印
    previewPrint() {
      this.$print(this.$refs.print);
    },
    // 发放记录
    async createGrant(selected) {
      for (const data of selected) {
        let arr = {
          certificates_id: data.id,
          baoan_num: data.baoan_num,
          name: data.name,
          card: data.card,
          exam_grade: data.exam_grade,
          cert_police: this.user.department_name,
          print_date: moment(new Date()).format('YYYY-MM-DD'),
          print_personal: data.cert_police,
          security_guard_id: data.security_guard_id,
        };
        let p2 = await this.grantCreate(arr);
        if (this.$checkRes(p2)) {
        } else {
          this.$message({ type: `success`, message: `${p2.errmsg}` });
        }
      }
    },
    // 创建打印日志
    async createJournal(selected) {
      for (const data of selected) {
        let arr = {
          baoan_num: data.baoan_num,
          name: data.name,
          print_date: moment(new Date()).format('YYYY-MM-DD'),
          print_personal: this.user.department_name,
          print_policenum: this.user.department_code,
          print_policename: this.user.department_name,
          is_make: '否',
        };
        let p3 = await this.printlogCreate(arr);
        if (this.$checkRes(p3)) {
          this.$message({ type: `success`, message: `操作成功` });
        } else {
          this.$message({ type: `success`, message: `${p3.errmsg}` });
        }
      }
    },
    // 发送消息
    async sendTem(selected) {
      for (const val of selected) {
        let res = await this.baseFetch({ id: val.security_guard_id });
        if (this.$checkRes(res)) {
          let p1 = {
            openid: res.data.gopenid,
            unionid: res.data.unionid,
            templateId: process.env.VUE_APP_templateId,
            url: '',
            topColor: '',
            data: {
              first: { value: '保安员证发放情况' },
              keyword1: { value: '保安员证' },
              keyword2: { value: '已打印' },
              keyword3: { value: moment(new Date()).format('YYYY-MM-DD') },
              remark: { value: '保安员证已打印，您可登录系统，进行保安员证的预约领取！' },
            },
          };
          let p2 = await this.send(p1);
          if (p2.errcode == '0' && p2.wxOpenid) {
            let p3 = await this.baseUpdate({ id: this.basic_id, gopenid: p2.wxOpenid });
            if (this.$checkRes(p3));
          }
        }
      }
    },
    // 设置尺寸
    setSize() {
      this.setShow = true;
    },
    // 提交设置的尺寸
    setSubmit({ data }) {
      localStorage.setItem('baoan_cert_size', JSON.stringify(data));
      this.searchSize();
      this.setClose();
    },
    // 关闭设置尺寸
    setClose() {
      this.setShow = false;
    },
    // 返回
    back() {
      this.printShow = '1';
      this.search();
    },
    // 打印尺寸默认值查询
    searchSize() {
      let data = JSON.parse(localStorage.getItem('baoan_cert_size'));
      if (data) {
        this.$set(this, `baoan_cert_size`, data);
      } else {
        let data = {
          p0: { width: 720, height: 485 },
          p1: { top: 90, right: 0, bottom: 0, left: 70 },
          p2: { top: 220, right: 0, bottom: 0, left: 110 },
          p3: { top: 300, right: 0, bottom: 0, left: 165 },
          p4: { top: 380, right: 0, bottom: 0, left: 185 },
          p5: { top: 200, right: 0, bottom: 0, left: 495 },
          p6: { top: 240, right: 0, bottom: 0, left: 495 },
          p7: { top: 280, right: 0, bottom: 0, left: 495 },
          p8: { top: 380, right: 0, bottom: 0, left: 495 },
        };
        localStorage.setItem('baoan_cert_size', JSON.stringify(data));
        this.$set(this, `baoan_cert_size`, data);
      }
    },

    // // 打印
    // // 批量选择打印证书数据
    // handleSelect(data) {
    //   this.$set(this, `selected`, data);
    // },
    // // 单个选择打印证书数据
    // toPrint({ data }) {
    //   this.selected.push(data);
    //   this.morePrint();
    // },
    // // 打印跳转
    // morePrint() {
    //   let data = _.cloneDeep(this.selected);
    //   this.$set(this, `printList`, data);
    //   this.printShow = '2';
    // },
    // 打印
    // // 打印,修改证件表，创建发放记录表，创建打印日志
    // async toPrint({ data }) {
    //   data.cert_police = '发证公安机关';
    //   data.print_date = moment(new Date()).format('YYYY-MM-DD');
    //   data.is_cert = '1';
    //   data.cert_status = '0';
    //   let p1 = await this.update(data);
    //   if (this.$checkRes(p1)) {
    //     // 创建发放记录
    //     this.createGrant(data);
    //     // 创建打印日志
    //     this.createJournal(data);
    //   }
    // },
    // // 创建发放记录
    // async createGrant(data) {
    //   let arr = {
    //     certificates_id: data.id,
    //     baoan_num: data.baoan_num,
    //     name: data.name,
    //     card: data.card,
    //     exam_grade: data.exam_grade,
    //     cert_police: '发证公安机关',
    //     print_date: moment(new Date()).format('YYYY-MM-DD'),
    //     print_personal: data.cert_police,
    //     security_guard_id: data.security_guard_id,
    //   };
    //   let p2 = await this.grantCreate(arr);
    //   if (this.$checkRes(p2)) {
    //   } else {
    //     this.$message({ type: `success`, message: `${p2.errmsg}` });
    //   }
    // },
    // // 创建打印日志
    // async createJournal(data) {
    //   let arr = {
    //     baoan_num: data.baoan_num,
    //     name: data.name,
    //     print_date: moment(new Date()).format('YYYY-MM-DD'),
    //     print_personal: '打印人',
    //     print_policenum: '打印公安机关编码',
    //     print_policename: '打印公安机关名称',
    //     is_make: '否',
    //   };
    //   let p3 = await this.printlogCreate(arr);
    //   if (this.$checkRes(p3)) {
    //     this.$message({ type: `success`, message: `操作成功` });
    //   } else {
    //     this.$message({ type: `success`, message: `${p3.errmsg}` });
    //   }
    // },

    // // 批量打印
    // morePrint() {
    //   console.log(this.selected);
    // },
  },
  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;
    }
    .one_2 {
      .one_2txt {
        border: 1px solid #ccc;
        /deep/.el-form-item {
          margin: 0;
        }
        /deep/.el-date-editor.el-input,
        .el-date-editor.el-input__inner {
          width: 100%;
        }
        /deep/.el-select {
          width: 100%;
        }
        .btn {
          text-align: right;
          padding: 5px 5px;
        }
      }
    }
  }
  .thr {
    margin: 0 0 10px 0;
  }
}
.twodialog {
  /deep/.el-dialog__body {
    height: 500px;
    overflow-y: auto;
  }
}
</style>
