<template>
  <div id="iris">
    <el-row v-if="view === 'list'">
      <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">
            <el-form ref="searchFrom" :model="searchFrom" label-width="80px">
              <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>
              <el-col :span="24" class="one_2txt">
                <el-col :span="24" class="btn">
                  <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="thr">
          <data-table
            @query="search"
            :fields="fields"
            :opera="opera"
            :data="list"
            :total="total"
            @eyesprint="toEyesprint"
            @photo="toPhoto"
            @fingerprint="toFingerprint"
            @reserve="toReserve"
          >
          </data-table>
        </el-col>
      </el-col>
    </el-row>
    <div v-else>
      <el-row>
        <el-col :span="6">
          <el-button @click="toBack()">返回</el-button>
        </el-col>
      </el-row>
      <collect @save="toSave" :irisData="irisData"></collect>
    </div>
    <el-dialog class="thrDialog" title="采集人像" :visible.sync="thrShow" width="50%" :before-close="thrClose" :close-on-click-modal="false">
      <el-col :span="24" class="info">
        <el-col :span="12" class="left">
          <el-col :span="24" class="title">摄像头</el-col>
          <img id="streamimage" class="xform" src="http://127.0.0.1:38088/video=stream&camidx=1" />
        </el-col>
        <el-col :span="12" class="left">
          <el-col :span="24" class="title">人像图片</el-col>
          <el-image :src="cardImg" class="xform">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </el-col>
        <el-col :span="24" class="right">
          <el-button type="primary" size="mini" @click="GrabImage()">拍照</el-button>
          <el-button type="primary" size="mini" @click="getCard()">获取身份证信息</el-button>
          <el-button type="primary" size="mini" @click="onSubmit()">提交保存</el-button>
        </el-col>
      </el-col>
    </el-dialog>
    <el-dialog class="fourDialog" title="采集指纹" :visible.sync="fourShow" width="45%" :before-close="fourClose" :close-on-click-modal="false">
      <iframe :src="`/baoanpolice/Demo.html`" class="iframe" id="mainIframe" ref="mainIframe"></iframe>
    </el-dialog>
    <el-dialog title="预约查询" :visible.sync="reserveShow" :close-on-click-modal="false">
      <data-table :fields="reserveFields" :data="reserveList" :usePage="false" :useFilter="false" height="500px"> </data-table>
    </el-dialog>
  </div>
</template>

<script>
const _ = require('lodash');
const moment = require('moment');
const { exam_grade } = require('@common/src/layout/deploy/dict');
import { mapGetters, createNamespacedHelpers } from 'vuex';
const { mapActions } = createNamespacedHelpers('system_account');
const { mapActions: security_guard_base } = createNamespacedHelpers('security_guard_base');
const { mapActions: security_guard_collect } = createNamespacedHelpers('security_guard_collect');
const { mapActions: mapUpload } = createNamespacedHelpers('upload');
const { mapActions: reserve_record } = createNamespacedHelpers('reserve_record');
import axios from 'axios';
export default {
  name: 'iris',
  props: {},
  components: {
    collect: () => import('@/components/collect.vue'),
  },
  data: function () {
    return {
      user: {},
      view: 'list',
      form: {},
      irisData: [],
      searchFrom: {},
      list: [],
      total: 0,
      fields: [
        { label: '姓名', model: 'name' },
        { label: '身份证号', model: 'card' },
        { label: '性别', model: 'gender' },
        { label: '状态', model: 'status' },
        { label: '采集虹膜', model: 'collect_iris' },
        { label: '采集人像', model: 'collect_photo' },
        { label: '采集指纹', model: 'collect_fingerprint' },
      ],
      opera: [
        { label: '虹膜采集', method: 'eyesprint' },
        { label: '人像采集', method: 'photo' },
        { label: '指纹采集', method: 'fingerprint' },
        { label: '预约查询', method: 'reserve' },
      ],
      // 保安员等级
      exam_gradeList: exam_grade,
      cardImg: undefined,
      // 人像采集
      thrShow: false,
      // 指纹采集
      fourShow: false,
      // 预约查询
      reserveShow: false,
      reserveList: [],
      reserveFields: [
        { label: '预约分局', model: 'dept_name' },
        { label: '预约日期', model: 'collect_date' },
        { label: '预约时间', model: 'time' },
      ],
    };
  },
  created() {},
  mounted() {
    this.init();
  },
  methods: {
    ...mapActions(['fetch']),
    ...security_guard_base(['query', 'delete', 'update']),
    ...security_guard_collect({ create: 'create', getCollect: 'query', collectDelete: 'delete' }),
    ...mapUpload(['uploadCreate']),
    ...reserve_record({ getRecordList: 'query' }),
    async init() {
      if (!_.get(this.tokenInfo, 'id')) return;
      const res = await this.fetch({ id: this.tokenInfo.id });
      if (this.$checkRes(res)) {
        let data = _.cloneDeep(res.data);
        this.$set(this, `user`, data);
      }
    },
    async search({ skip = 0, limit = 10, ...info } = {}) {
      if (!_.get(this.searchFrom, 'name') && !_.get(this.searchFrom, 'card')) {
        this.$message.error('请至少填写保安员 姓名 或 身份证号');
        return;
      }
      let res = await this.query({ skip, limit, ...this.searchFrom, ...info });
      if (this.$checkRes(res)) {
        this.$set(this, `list`, res.data);
        this.$set(this, `total`, res.total);
      }
    },
    async toEyesprint({ data }) {
      if (!data.id) {
        this.$message.error('所选择的人员数据有错误,无法进行信息采集!');
        return;
      }
      const res = await this.getCollect({ security_guard_id: data.id, type: '虹膜' });
      if (this.$checkRes(res)) {
        this.$set(this, 'irisData', res.data);
      }
      const obj = { name: data.name, security_guard_id: data.id, collect_personal: this.user.name, collect_police: this.user.belong_company };
      this.form = obj;
      this.view = 'collect';
    },
    async toPhoto({ data }) {
      this.form = data;
      this.thrShow = true;
    },
    async toFingerprint({ data }) {
      this.form = data;
      this.fourShow = true;
    },
    async toSave(imgs) {
      if (!_.isArray(imgs) || imgs.length <= 0) {
        this.$message.error('未获取到虹膜信息！');
        return false;
      }
      const dup = _.cloneDeep(this.form);
      let isChange = false;
      for (const i of imgs) {
        const { code, size } = i;
        const object = { extension: 'jpge', code };
        object.name = `${dup.name}_${size}`;
        object.uri = `/baoan/iris/${dup.security_guard_id}/upload`;
        const res = await this.uploadCreate(object);
        if (this.$checkRes(res)) {
          const obj = { ...dup, data: res.data.uri, type: `虹膜${size}` };
          // 创建虹膜记录
          if (this.irisData.length <= 0) {
            await this.create(obj);
            isChange = true;
          }
        }
      }
      if (isChange) await this.update({ id: dup.security_guard_id, collect_iris: '已采集' });
      this.$message.success('虹膜保存成功！');
      this.toBack();
      this.toClear();
    },
    // 拍照
    async GrabImage() {
      var cutpage = 0;
      var params = '{"filepath":"' + `` + '","rotate":"' + '0' + '","camidx":"' + '1' + '","cutpage":"' + '0' + '"}';
      // const ax = axios.create({ baseURL: 'http://127.0.0.1:38088/' });
      // const res = await ax.request({
      //   url: 'video=grabimage',
      //   method: 'post',
      //   data: params,
      //   responseType: 'json',
      // });
      // if (res.code != 0) {
      //   console.log(res);
      // } else {
      //   this.uploadImg(res, '1');
      // }
      $.ajax({
        url: `http://127.0.0.1:38088/video=grabimage`,
        type: 'post',
        dataType: 'json',
        data: params,
        success: (res) => {
          if (res.code != 0) {
            console.log(res);
          } else {
            this.uploadImg(res, '1');
          }
        },
      });
    },
    // 获取身份证人像信息
    async getCard() {
      // const ax = axios.create({ baseURL: 'http://127.0.0.1:38088/' });
      // const res = await ax.request({
      //   url: 'card=idcard',
      //   method: 'post',
      //   data: {},
      //   responseType: 'json',
      // });
      // if (res.code != 0) {
      //   console.log(res);
      // } else {
      //   this.uploadImg(res.IDCardInfo, '2');
      // }
      $.ajax({
        url: `http://127.0.0.1:38088/card=idcard`,
        type: 'post',
        dataType: 'json',
        data: {},
        success: (res) => {
          if (res.code != 0) {
            console.log(res);
          } else {
            this.uploadImg(res.IDCardInfo, '2');
          }
        },
      });
    },
    // 提交人像采集
    async onSubmit() {
      let basic = this.form;
      let p1 = {
        name: basic.name,
        security_guard_id: basic.id,
        type: '人像',
        collect_personal: this.user.name,
        collect_police: this.user.department_name,
        data: this.cardImg,
      };
      let p2 = await this.create(p1);
      if (this.$checkRes(p2)) {
        let p3 = await this.update({ id: basic.id, collect_photo: '已采集' });
        if (this.$checkRes(p3)) {
          this.$message({ type: `success`, message: `操作成功` });
          this.search();
          this.thrClose();
        } else {
          this.$message({ type: `error`, message: `${p3.errmsg}` });
        }
      }
    },
    //拍照上传图片。身份证信息头像上传图片
    async uploadImg(data, type) {
      let basic = this.form;
      let p1 = { extension: 'jpg' };
      if (type == '1') {
        p1.name = data.uuid;
        p1.uri = `/baoan/hightBeat/${moment().format('YYYYDDMM')}/${basic.card}/upload`;
        p1.code = `data:image/jpg;base64,${data.photoBase64}`;
      } else if (type == '2') {
        p1.name = basic.card + '-' + moment(Date.now()).format('YYYYMMDDHHmmss').valueOf();
        p1.uri = `/baoan/hightBeat/${moment().format('YYYYDDMM')}/${basic.card}/upload`;
        p1.code = `data:image/jpg;base64,${data.photoBase64}`;
      }
      let p2 = await this.uploadCreate(p1);
      if (this.$checkRes(p2)) {
        this.$set(this, `cardImg`, p2.data.uri);
      }
    },
    // 关闭
    thrClose() {
      this.thrShow = false;
    },
    // 关闭指纹采集
    fourClose() {
      this.fourShow = false;
    },
    toBack() {
      this.view = 'list';
    },
    toClear() {
      this.form = {};
      this.irisData = [];
    },
    // 查询并显示预约信息
    async toReserve({ data }) {
      if (!_.get(data, 'id')) return;
      const date = moment().format('YYYY-MM-DD');
      const res = await this.getRecordList({ security_guard_id: _.get(data, 'id'), 'collect_date@start': date });
      if (this.$checkRes(res)) {
        this.$set(this, 'reserveList', res.data);
      }
      this.reserveShow = true;
    },
  },

  computed: {
    ...mapGetters(['tokenInfo']),
  },
  metaInfo() {
    return { title: this.$route.meta.title };
  },
};
</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;
        }
      }
    }
  }
}
.thrDialog {
  /deep/.el-dialog__body {
    padding: 10px;
    height: 500px;
    overflow-y: auto;
  }
  .info {
    .left {
      width: 47%;
      margin: 0 10px;
      .title {
        text-align: center;
        font-weight: bold;
        margin: 0 0 10px 0;
      }
      .xform {
        width: 100%;
        height: 418px;
        border: 1px solid #ccc;
      }
    }
    .right {
      padding: 10px;
      text-align: center;
    }
  }
}

.fourDialog {
  /deep/.el-dialog__body {
    padding: 10px;
    height: 320px;
    overflow-y: auto;
  }
  .iframe {
    width: 100%;
    height: 310px;
  }
}
</style>
