<template lang="pug">
  el-dialog(:title="id ? '修改' :'新增'"  :visible.sync='visible' :modal-append-to-body='false')
    div(slot='title')
      span.title-bold {{id ? '修改' :'新增' }}
    el-form(:model='dataForm', :rules='dataRule', ref='dataForm',  label-width='110px')
      el-row()
        el-col(:span='12')
          el-form-item(label="姓名:", prop="name")
            el-input(  v-model="dataForm.name" placeholder="姓名" clearable)
        el-col(:span='12')
          el-form-item(label='性别:', prop='gender')
            el-radio-group(v-model='dataForm.gender')
              el-radio(:label='1') 男
              el-radio(:label='0') 女
        el-col(:span='12')
          el-form-item(label='出生日期:', prop='birthday')
            el-date-picker(style='width:100%;' v-model='dataForm.birthday', type="date", placeholder='出生日期')
        el-col(:span='12')
          el-form-item(label='政治面貌:', prop='politicCountenance')
            el-select(style='width:100%;'  v-model="dataForm.politicCountenance" @blur="checkRule('politicCountenance')" placeholder="政治面貌" clearable)
              el-option(v-for="(item, index) in politicCountenance" :key='index' :label="item.name" :value="item.id")
        el-col(:span='12')
          el-form-item(label='民族:', prop='nation')
            el-select(style='width:100%;'  v-model="dataForm.nation" @blur="checkRule('nation')" placeholder="民族" clearable)
              el-option(v-for="(item, index) in nations" :key='index' :label="item.name" :value="item.id.toString()")
        el-col(:span='12')
          el-form-item( label='证件号码:', prop='cardNumber',)
            el-input( v-model='dataForm.cardNumber', placeholder='证件号码')
        el-col(:span='12')
          el-form-item(label='联系电话:', prop='mobile')
            el-input( v-model='dataForm.mobile', placeholder='请填写联系电话')
        el-col(:span='24')
          el-form-item(label='人员类型:', prop='types')
            el-checkbox-group(v-model="dataForm.types" placeholder="人员类型" clearable)
              el-checkbox(v-for="(item, index) in types" :key="index" :label="item.id") {{item.name}}
        el-col(:span='24')
          el-form-item(label='专长:', prop='skill')
            el-input(type="textarea" :rows="4" resize='none' v-model='dataForm.skill', placeholder='专长' clearable)
      el-form-item(label='状态:', prop='status')
        el-radio-group(v-model='dataForm.status')
          el-radio(:label='1') 正常
          el-radio(:label='0') 禁用
    span.dialog-footer(slot='footer')
      el-button(type='danger' size='medium' @click='visible = false') 取消
      el-button(type='primary' size='medium' @click='dataFormSubmit' v-prevent-re-click) 保存
</template>

<script>
// import { isEmail, isMobile } from '@/util/validate'
export default {
  data() {
    var validatecardNumber = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入身份证号码'))
      } else {
        if (!this.checkIDCard(value)) {
          callback(new Error('请输入正确的身份证号码'))
        }
        callback()
      }
    }
    return {
      id: '',
      show: true,
      clickFlag: false,
      visible: false,
      roleList: [],
      sysOrgList: [],
      dataListSelections: [],
      nations: [],
      types: [],
      politicCountenance: [],
      dataForm: {
        name: '',
        gender: '',
        birthday: '',
        politicCountenance: '',
        nation: '',
        cardNumber: '',
        mobile: '',
        types: [],
        skill: '',
        status: ''
      },
      dataRule: {
        name: [
          { required: true, message: '姓名不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 30,
            message: '长度在 1 到 30 个字符',
            trigger: ['change', 'blur']
          }
        ],
        gender: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
        birthday: [
          { required: true, message: '生日不能为空', trigger: 'blur' }
        ],
        politicCountenance: [
          { required: true, message: '政治面貌不能为空', trigger: 'change' }
        ],
        nation: [
          { required: true, message: '民族不能为空', trigger: 'change' }
        ],
        cardNumber: [
          { required: true, message: '身份证号码不能为空', trigger: 'blur' },
          { validator: validatecardNumber, trigger: ['change', 'blur'] }
        ],
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { pattern: /^1[12345789]\d{9}$/, message: '请输入正确的手机号码' }
        ]
      }
    }
  },
  mounted() {
    this.getNation()
    this.getAllTypes()
    this.getAllPoliticCountenance()
  },
  watch: {
    visible: {
      handler(val) {
        // console.log("监听", val);
        if (val === false) {
          this.$refs.dataForm.resetFields()
        }
      },
      deep: true
    }
  },
  methods: {
    init(id) {
      // console.log(id);
      this.visible = true
      this.id = id || null
      if (id) {
        this.$http({
          url: this.$http.adornUrl(`/emPerson/getId/` + id),
          method: 'get'
        }).then(data => {
          let da = data.bean
          da.types = da.types.split(',')
          this.dataForm = da
          // console.log("dataForm", this.dataForm);
        })
      } else {
        this.show = true
        this.dataForm = {
          name: '',
          gender: '',
          birthday: '',
          politicCountenance: '',
          nation: '',
          cardNumber: '',
          mobile: '',
          types: [],
          skill: '',
          status: 1
        }
      }
    },
    checkRule(value) {
      // console.log("value", value);
      this.$refs.dataForm.validateField(value)
    },
    //身份证校验
    checkIDCard(idcode) {
      // 加权因子
      var weight_factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
      // 校验码
      var check_code = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']

      var code = idcode + ''
      var last = idcode[17] //最后一位

      var seventeen = code.substring(0, 17)

      // ISO 7064:1983.MOD 11-2
      // 判断最后一位校验码是否正确
      var arr = seventeen.split('')
      var len = arr.length
      var num = 0
      for (var i = 0; i < len; i++) {
        num = num + arr[i] * weight_factor[i]
      }

      // 获取余数
      var resisue = num % 11
      var last_no = check_code[resisue]

      // 格式的正则
      // 正则思路
      /*
    第一位不可能是0
    第二位到第六位可以是0-9
    第七位到第十位是年份，所以七八位为19或者20
    十一位和十二位是月份，这两位是01-12之间的数值
    十三位和十四位是日期，是从01-31之间的数值
    十五，十六，十七都是数字0-9
    十八位可能是数字0-9，也可能是X
    */
      var idcard_patter = /^[1-9][0-9]{5}([1][9][0-9]{2}|[2][0][0|1][0-9])([0][1-9]|[1][0|1|2])([0][1-9]|[1|2][0-9]|[3][0|1])[0-9]{3}([0-9]|[X])$/

      // 判断格式是否正确
      var format = idcard_patter.test(idcode)

      // 返回验证结果，校验码和格式同时正确才算是合法的身份证号码
      return !!(last === last_no && format)
    },
    //获取民族信息
    getNation() {
      this.$http({
        url: this.$http.adornUrl('/emPerson/getAllNation'),
        method: 'get'
      }).then(data => {
        // console.log("data", data);
        if (data && data.code === 0) {
          this.nations = data.result
          // console.log("nations", this.nations);
        }
      })
    },
    //获取人员类型
    getAllTypes() {
      this.$http({
        url: this.$http.adornUrl('/emPerson/getAllTypes'),
        method: 'get'
      }).then(data => {
        // console.log("data", data);
        if (data && data.code === 0) {
          this.types = data.result
        }
      })
    },
    //获取政治面貌
    getAllPoliticCountenance() {
      this.$http({
        url: this.$http.adornUrl('/emPerson/getAllPoliticCountenance'),
        method: 'get'
      }).then(data => {
        // console.log("data", data);
        if (data && data.code === 0) {
          this.politicCountenance = data.result
          // console.log("政治面貌", this.politicCountenance);
        }
      })
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val
    },
    change() {
      this.$forceUpdate()
    },
    //格式化时间
    formatDate(time, format = 'YY-MM-DD hh:mm:ss') {
      var date = new Date(time)

      var year = date.getFullYear(),
        month = date.getMonth() + 1, //月份是从0开始的
        day = date.getDate(),
        hour = date.getHours(),
        min = date.getMinutes(),
        sec = date.getSeconds()
      var preArr = Array.apply(null, Array(10)).map(function(elem, index) {
        return '0' + index
      }) ////开个长度为10的数组 格式为 00 01 02 03

      var newTime = format
        .replace(/YY/g, year)
        .replace(/MM/g, preArr[month] || month)
        .replace(/DD/g, preArr[day] || day)
        .replace(/hh/g, preArr[hour] || hour)
        .replace(/mm/g, preArr[min] || min)
        .replace(/ss/g, preArr[sec] || sec)

      return newTime
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/emPerson/${!this.dataForm.id ? 'save' : 'update'}`
            ),
            method: 'post',
            data: {
              id: this.dataForm.id,
              name: this.dataForm.name,
              gender: this.dataForm.gender,
              birthday: this.formatDate(this.dataForm.birthday),
              politicCountenance: this.dataForm.politicCountenance,
              nation: this.dataForm.nation,
              cardNumber: this.dataForm.cardNumber,
              mobile: this.dataForm.mobile,
              types: this.dataForm.types.join(','),
              skill: this.dataForm.skill,
              status: this.dataForm.status
            }
          }).then(data => {
            // console.log(data, '======')
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshdatalist')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    }
  }
}
</script>
<style>
.el-table__header {
  width: 100% !important;
}
.el-table__body {
  width: 100% !important;
}
</style>
