<template>
  <div id="basic-1">
    <el-row>
      <el-col :span="24" class="main">
        <el-col :span="24" class="one">
          <el-form :model="form" :rules="rules" ref="form" label-width="170px">
            <el-col :span="24">
              <el-col :span="24">
                <el-button type="primary" size="small" @click="toCard()">读取身份证信息</el-button>
              </el-col>
            </el-col>
            <el-col :span="24">
              <el-col :span="24">
                <el-form-item label="联系电话" prop="phone">
                  <el-input v-model="form.phone" placeholder="请输入联系电话"></el-input>
                </el-form-item>
              </el-col>
            </el-col>
            <el-col :span="24">
              <el-col :span="8">
                <el-form-item label="姓名" prop="name">
                  <el-input v-model="form.name" placeholder="请输入姓名"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="曾用名" prop="beforeName">
                  <el-input v-model="form.beforeName" placeholder="请输入曾用名"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="身份证号" prop="card">
                  <el-input v-model="form.card" placeholder="请输入身份证号"></el-input>
                </el-form-item>
              </el-col>
            </el-col>
            <el-col :span="24">
              <el-col :span="8">
                <el-form-item label="性别" prop="gender">
                  <el-select v-model="form.gender" clearable placeholder="请选择" style="width: 100%">
                    <el-option label="男" value="男"></el-option>
                    <el-option label="女" value="女"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="民族" prop="nation">
                  <el-select v-model="form.nation" filterable clearable placeholder="请选择" style="width: 100%">
                    <el-option v-for="(item, index) in nationList" :key="index" :label="item" :value="item"> </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="出生日期" prop="birth">
                  <el-date-picker v-model="form.birth" placeholder="请选择" value-format="yyyy-MM-dd" format="yyyy-MM-dd" type="date" style="width: 100%">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-col>
            <el-col :span="24">
              <el-col :span="8">
                <el-form-item label="政治面貌" prop="politics">
                  <el-select v-model="form.politics" filterable clearable placeholder="请选择" style="width: 100%">
                    <el-option v-for="(item, index) in politicsList" :key="index" :label="item" :value="item"> </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="文化程度" prop="education">
                  <el-select v-model="form.education" filterable clearable placeholder="请选择" style="width: 100%">
                    <el-option v-for="(item, index) in educationList" :key="index" :label="item" :value="item"> </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="兵役状况" prop="soldier">
                  <el-select v-model="form.soldier" filterable clearable placeholder="请选择" style="width: 100%">
                    <el-option v-for="(item, index) in soldierList" :key="index" :label="item" :value="item"> </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-col>
            <el-col :span="24">
              <el-col :span="8">
                <el-form-item label="婚姻状况" prop="marriage">
                  <el-select v-model="form.marriage" clearable placeholder="请选择" style="width: 100%">
                    <el-option label="已婚" value="已婚"></el-option>
                    <el-option label="未婚" value="未婚"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="血型" prop="blood">
                  <el-select v-model="form.blood" filterable clearable placeholder="请选择" style="width: 100%">
                    <el-option v-for="(item, index) in bloodList" :key="index" :label="item" :value="item"> </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="身高" prop="height">
                  <el-input v-model="form.height" placeholder="请输入身高"></el-input>
                </el-form-item>
              </el-col>
            </el-col>
            <el-col :span="24">
              <el-col :span="8">
                <el-form-item label="保安员等级" prop="grade">
                  <el-select v-model="form.grade" filterable clearable placeholder="请选择" style="width: 100%">
                    <el-option v-for="(item, index) in exam_gradeList" :key="index" :label="item" :value="item"> </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="驾驶证号" prop="drive_num">
                  <el-input v-model="form.drive_num" placeholder="请输入驾驶证号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="准驾车型" prop="drive_type">
                  <el-input v-model="form.drive_type" placeholder="请输入准驾车型"></el-input>
                </el-form-item>
              </el-col>
            </el-col>
            <el-col :span="24">
              <el-col :span="8">
                <el-form-item label="健康状态" prop="health">
                  <el-select v-model="form.health" clearable placeholder="请选择" style="width: 100%">
                    <el-option label="无疾病" value="无疾病"></el-option>
                    <el-option label="健康" value="健康"></el-option>
                    <el-option label="良好" value="良好"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="户籍省市县" prop="house_city">
                  <el-input v-model="form.house_city" placeholder="请输入户籍省市县"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="户籍/居住证派出所名称" prop="house_police">
                  <el-select v-model="form.house_police" filterable clearable placeholder="请选择" style="width: 100%">
                    <el-option v-for="(item, index) in house_policeList" :key="index" :label="item.name" :value="item.name"> </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-col>
            <el-col :span="24">
              <el-col :span="8">
                <el-form-item label="报名企业" prop="sign_company">
                  <el-select v-model="form.sign_company" filterable clearable placeholder="请选择" style="width: 100%">
                    <el-option v-for="(item, index) in sign_companyList" :key="index" :label="item.name" :value="item.name"> </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="培训机构编码" prop="train_num">
                  <el-input v-model="form.train_num" placeholder="请输入培训机构编码"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="现住地省市县" prop="onhouse_city">
                  <el-input v-model="form.onhouse_city" placeholder="请输入现住地省市县"></el-input>
                </el-form-item>
              </el-col>
            </el-col>
            <el-col :span="24">
              <el-col :span="8">
                <el-form-item label="户籍地详址" prop="house_address">
                  <el-input v-model="form.house_address" placeholder="请输入户籍地详址"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="现住地详址" prop="house_onaddress">
                  <el-input v-model="form.house_onaddress" placeholder="请输入现住地详址"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="家庭主要成员" prop="home_member">
                  <el-input v-model="form.home_member" placeholder="请输入家庭主要成员"></el-input>
                </el-form-item>
              </el-col>
            </el-col>
            <el-col :span="24">
              <el-col :span="12">
                <el-form-item label="教育经历" prop="education_experience">
                  <el-input v-model="form.education_experience" type="textarea" placeholder="请输入教育经历"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="工作经历" prop="work_experience">
                  <el-input v-model="form.work_experience" type="textarea" placeholder="请输入工作经历"></el-input>
                </el-form-item>
              </el-col>
            </el-col>
            <el-col :span="24" class="btn">
              <el-button type="primary" @click="submitForm('form')">提交</el-button>
            </el-col>
          </el-form>
        </el-col>
      </el-col>
    </el-row>
  </div>
</template>

<script>
const { nation, politics, education, soldier, blood, exam_grade } = require('@common/src/layout/deploy/dict');
import { mapState, createNamespacedHelpers } from 'vuex';
const { mapActions: security_guard_base } = createNamespacedHelpers('security_guard_base');
const { mapActions: police_department } = createNamespacedHelpers('police_department');
const { mapActions: company_base } = createNamespacedHelpers('company_base');
const moment = require('moment');
import axios from 'axios';
export default {
  name: 'basic-1',
  props: {},
  components: {},
  data: function () {
    return {
      form: {},
      rules: {
        phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        beforeName: [{ required: false, message: '请输入曾用名', trigger: 'blur' }],
        card: [{ required: true, message: '请输入身份证号', trigger: 'blur' }],
        gender: [{ required: true, message: '请选择', trigger: 'change' }],
        nation: [{ required: true, message: '请选择', trigger: 'change' }],
        birth: [{ required: true, message: '请选择', trigger: 'change' }],
        politics: [{ required: true, message: '请选择', trigger: 'change' }],
        education: [{ required: true, message: '请选择', trigger: 'change' }],
        soldier: [{ required: true, message: '请选择', trigger: 'change' }],
        marriage: [{ required: true, message: '请选择', trigger: 'change' }],
        blood: [{ required: false, message: '请选择', trigger: 'change' }],
        height: [{ required: false, message: '请输入身高', trigger: 'blur' }],
        grade: [{ required: true, message: '请选择', trigger: 'change' }],
        drive_num: [{ required: false, message: '请输入驾驶证号', trigger: 'blur' }],
        drive_type: [{ required: false, message: '请输入准驾车型', trigger: 'blur' }],
        health: [{ required: true, message: '请选择', trigger: 'change' }],
        house_city: [{ required: true, message: '请输入户籍省市县', trigger: 'blur' }],
        house_police: [{ required: true, message: '请选择', trigger: 'change' }],
        sign_company: [{ required: true, message: '请输入报名企业', trigger: 'blur' }],
        train_num: [{ required: false, message: '请输入培训机构编码', trigger: 'blur' }],
        onhouse_city: [{ required: true, message: '请输入现住地省市县', trigger: 'blur' }],
        house_address: [{ required: true, message: '请输入户籍地详址', trigger: 'blur' }],
        house_onaddress: [{ required: true, message: '请输入现住地详址', trigger: 'blur' }],
        home_member: [{ required: false, message: '请输入家庭主要成员', trigger: 'blur' }],
        education_experience: [{ required: false, message: '请输入教育经历', trigger: 'blur' }],
        work_experience: [{ required: false, message: '请输入工作经历', trigger: 'blur' }],
      },
      // 民族
      nationList: nation,
      // 政治面貌
      politicsList: politics,
      // 文化程度
      educationList: education,
      // 兵役状况
      soldierList: soldier,
      // 血型
      bloodList: blood,
      // 保安员等级
      exam_gradeList: exam_grade,
      // 派出所列表
      house_policeList: [],
      // 报名企业
      sign_companyList: [],
    };
  },
  created() {
    this.searchOther();
    if (this.id) this.search();
  },
  methods: {
    ...police_department({ deptQuery: 'query' }),
    ...security_guard_base(['query', 'fetch', 'create', 'update']),
    ...company_base({ companyQuery: 'query' }),
    // 查询详情
    async search() {
      let res = await this.fetch({ id: this.id });
      if (this.$checkRes(res)) {
        this.$set(this, `form`, res.data);
        this.$emit('basicBtn', res.data);
      }
    },
    // 提交
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let data = this.form;
          if (data.card) {
            const { pass, msg } = this.idCodeValid(data.card);
            if (!pass) {
              this.$message.error(msg || '身份证号有错误');
              return false;
            }
          }
          if (data.id) {
            let arr = await this.update(data);
            if (this.$checkRes(arr)) {
              this.$message({ type: `success`, message: `操作成功` });
            } else {
              this.$message({ type: `success`, message: `${arr.errmsg}` });
            }
          } else {
            // 查询保安员是否注册
            let res = await this.query({ card: data.card });
            if (this.$checkRes(res)) {
              if (res.total > 0) {
                this.$message({ type: `fail`, message: `账号已注册` });
              } else {
                data.password = '123456';
                let res = await this.create(data);
                if (this.$checkRes(res)) {
                  this.$message({ type: `success`, message: `操作成功` });
                  this.$emit('basicBtn', res.data);
                } else {
                  this.$message({ type: `success`, message: `${res.errmsg}` });
                }
              }
            }
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 查詢派出所列表
    async searchOther() {
      let res = await this.deptQuery({ type: '3' });
      if (this.$checkRes(res)) {
        this.$set(this, `house_policeList`, res.data);
      }
      // 报名企业
      res = await this.companyQuery({ status: '3' });
      if (this.$checkRes(res)) {
        res.data.push({ name: '无', id: '无' });
        this.$set(this, `sign_companyList`, res.data);
      }
    },
    // 读取身份证信息
    async toCard() {
      // 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.saveCard(res.IDCardInfo);
      // }
      $.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.saveCard(res.IDCardInfo);
          }
        },
      });
    },
    // 上传身份证信息
    async saveCard(data) {
      let p1 = {
        name: data.name,
        card: data.cardID,
        gender: data.sex,
        nation: data.nationCode + '族',
        birth: moment(data.birthday).format('YYYY-MM-DD'),
      };
      let res = await this.deptQuery({ type: '3', name: data.issueOrgan });
      if (this.$checkRes(res)) {
        if (res.total > 0) {
          p1.house_police = res.data[0].name;
          p1.house_city = data.issueOrgan;
          p1.house_address = data.address;
        } else {
          this.$message({ type: `warn`, message: `身份证签发机关未在系统中录入，暂无发获取户籍地信息！` });
        }
      }
      this.$set(this, `form`, p1);
    },
    // 身份证验证
    idCodeValid(code) {
      // 身份证号合法性验证
      // 支持15位和18位身份证号
      // 支持地址编码、出生日期、校验位验证
      const city = {
        11: '北京',
        12: '天津',
        13: '河北',
        14: '山西',
        15: '内蒙古',
        21: '辽宁',
        22: '吉林',
        23: '黑龙江 ',
        31: '上海',
        32: '江苏',
        33: '浙江',
        34: '安徽',
        35: '福建',
        36: '江西',
        37: '山东',
        41: '河南',
        42: '湖北 ',
        43: '湖南',
        44: '广东',
        45: '广西',
        46: '海南',
        50: '重庆',
        51: '四川',
        52: '贵州',
        53: '云南',
        54: '西藏 ',
        61: '陕西',
        62: '甘肃',
        63: '青海',
        64: '宁夏',
        65: '新疆',
        71: '台湾',
        81: '香港',
        82: '澳门',
        91: '国外 ',
      };
      let row = {
        pass: true,
        msg: '验证成功',
      };
      if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/.test(code)) {
        row = {
          pass: false,
          msg: '身份证号格式错误',
        };
      } else if (!city[code.substr(0, 2)]) {
        row = {
          pass: false,
          msg: '身份证号地址编码错误',
        };
      } else {
        // 18位身份证需要验证最后一位校验位
        if (code.length == 18) {
          code = code.split('');
          // ∑(ai×Wi)(mod 11)
          // 加权因子
          const factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
          // 校验位
          const parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
          let sum = 0;
          let ai = 0;
          let wi = 0;
          for (let i = 0; i < 17; i++) {
            ai = code[i];
            wi = factor[i];
            sum += ai * wi;
          }
          if (parity[sum % 11] != code[17].toUpperCase()) {
            row = {
              pass: false,
              msg: '身份证号校验位错误',
            };
          }
        }
      }
      return row;
    },
  },
  computed: {
    ...mapState(['user']),
    id() {
      return this.$route.query.id;
    },
  },
  metaInfo() {
    return { title: this.$route.meta.title };
  },
  watch: {
    test: {
      deep: true,
      immediate: true,
      handler(val) {},
    },
  },
};
</script>

<style lang="less" scoped>
.main {
  .one {
    .btn {
      text-align: center;
    }
  }
}
</style>
