<template>
  <div class="app-container">
    <!-- 添加人员 -->
    <div v-if="step==='1'">
      <el-form v-loading="formLoading" ref="dataForm" :label-position="labelPosition" :rules="rules" :model="personForm" class="main-form" label-width="120px">
        <el-row>
          <el-col :span="16">
            <el-row :gutter="20">
              <el-col :span="11">
                <el-form-item v-if="personType=='1'" label="员工编号" prop="personCode">
                  <el-input v-model.trim="personForm.personCode" :disabled="isEditMode" type="text" placeholder="必填"/>
                </el-form-item>
                <el-form-item v-else label="访客编号">
                  <el-input v-model.trim="personForm.personCode" disabled type="text" placeholder="系统将自动生成"/>
                </el-form-item>
              </el-col>
              <el-col :span="11" >
                <el-form-item label="身份证号" prop="idCardNo">
                  <el-input v-model.trim="personForm.idCardNo" :disabled="isEditMode" type="text" placeholder="必填"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="11">
                <el-form-item label="姓名" prop="name">
                  <el-input v-model.trim="personForm.name" :disabled="isEditMode" type="text" placeholder="必填"/>
                </el-form-item>
              </el-col>
              <el-col :span="11" >
                <el-form-item :disabled="isEditMode" label="出生日期" prop="birthday">
                  <el-date-picker
                    v-model="personForm.birthday"
                    type="date"
                    style="width: 100%"
                    format="yyyy-MM-dd"
                    placeholder="选择日期"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="11">
                <el-form-item label="性别" prop="sex">
                  <el-select v-model="personForm.sex" placeholder="性别" clearable>
                    <el-option v-for="item in sexList" :key="item.value" :label="item.name" :value="item.value"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="11" >
                <el-form-item label="民族" prop="nation">
                  <el-select v-model="personForm.nation" placeholder="民族" clearable>
                    <el-option v-for="item in nationList" :key="item.value" :label="item.name" :value="item.value"/>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="personType=='1'" :gutter="20">
              <el-col :span="11">
                <el-form-item label="部门" prop="deptid">
                  <dept-select v-model="personForm.deptid" :need-top="false" :dept-show="true" placeholder="单位/部门"/>
                </el-form-item>
              </el-col>
              <el-col :span="11" >
                <el-form-item label="职务" prop="duty">
                  <el-select v-model="personForm.duty" placeholder="职务" clearable>
                    <el-option v-for="item in dutyList" :key="item.value" :label="item.name" :value="item.value"/>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="22">
                <el-form-item label="颁证单位" prop="certification">
                  <el-input v-model.trim="personForm.ext.certificationUnit" type="text" placeholder="必填"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="22">
                <el-form-item label="住址" prop="address">
                  <el-input v-model.trim="personForm.ext.address" type="text" placeholder="必填"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="22">
                <el-form-item label="备注" prop="remarks">
                  <el-input v-model.trim="personForm.remarks" type="text" placeholder="必填"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="6" :offset="2">
            <el-row>
              <div class="avatar">
                <el-image
                  :src="photo!==''?photo:defaultPhoto"
                  fit="cover"
                  style="width: 130px; height: 175px"/>
              </div>
            </el-row>
            <el-row>
              <el-upload
                ref="upload"
                :before-upload="handleBeforeUpload"
                :http-request="uploadFile"
                :show-file-list="false"
                class="avatar-uploader"
                action="string"
                accept=".jpg,.jpeg,.png">
                <el-button type="primary">点击上传照片</el-button>
              </el-upload>
            </el-row>
            <el-row>
              <el-button type="primary" plain class="id-card-btn" @click="readIDCard">读取身份证</el-button>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
      <div style="height: 120px;">
        <el-row type="flex" justify="center">
          <el-col :span="15" style="text-align:center">
            <el-button v-show="!isEditMode" size="medium" @click="resetForm"> 重置 </el-button>
            <el-button :disabled="!canSave" type="primary" size="medium" style="margin-left: 20px;" @click="saveData"> 保存 </el-button>
            <el-button v-show="!isEditMode" type="primary" size="medium" style="margin-left: 20px;" @click="registerIris"> 下一步，注册虹膜 </el-button>
          </el-col>
        </el-row>
      </div>
    </div>
    <!-- 保存虹膜 -->
    <div v-if="step==='2'">
      <div class="iframeMsg">{{ iframeMsg }}</div>
      <div>
        <iframe name="iframeMap" scrolling="no" width="100%" height="450" frameBorder="no" src="static/eye/eye.html" style="z-index: -1;"/>
      </div>
      <!-- <div
        v-loading ="devLoading"
        element-loading-text="正在初始化设备，请稍候..."
        element-loading-spinner="el-icon-loading"
        class="button-div">
        <el-button :disabled="irisBtnDisable" class="button-width-middle" type="primary" @click="startCapture">{{ irisBtnName }}</el-button>
      </div> -->
    </div>
    <div>
      <iframe :src="idsrc" name = "iframeIDCard" scrolling="no" width="100%" height="0" frameBorder="no"/>
    </div>
  </div>
</template>

<script>
import DeptSelect from '@/components/DeptSelect'
// import { Uploadimg } from '@/api/common'
import { addPerson, updatePerson, personInfo, getSexType, getDutyType, getNationType, saveIris } from '@/api/person'
// import { getToken } from '@/utils/auth' // getToken from cookie
// import { getProject } from '@/utils/baseConfig'
import { getBirthdayByIdNO, getSexByIdNO } from '@/utils/dataAnalysis'
// import { isIE } from '@/utils/browser'

export default {
  name: 'AddPersonIris',
  components: { DeptSelect },
  data() {
    const validateIDCard = (rule, value, callback) => {
      if (value !== '') {
        if ((/^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/).test(value) === false) {
          callback(new Error('请输入合法的身份证号'))
        } else {
          callback()
        }
      } else {
        callback(new Error('身份证号不能为空'))
      }
    }
    return {
      dialogFormVisible: false, // 对话框是否显示
      dialogStatus: '', // 对话框类型：create,update
      isEditMode: false, // 是否为编辑模式，编辑模式部分字段不允许修改，且没有重置和虹膜注册功能
      personType: '', // 人员角色，1为员工，0为访客
      canSave: true, // 是否可以点击保存，当点击后该值置为false，直到后台返回结果再置为true
      isSave: false, // 当点击保存按钮后，并返回200结果，置为true，表示已经保存
      personForm: {
        id: '', // 人员id
        idCardNo: '', // 身份证号
        name: '', // 姓名
        deptid: '', // 单位/部门
        remarks: '', // 备注
        duty: '', // 职务
        sex: '', // 性别
        personType: '1', // 人员类型
        birthday: '', // 出生日期
        nation: '', // 民族
        photo: '',
        ext: {
          certificationUnit: '', // 颁发证件单位，
          address: ''// 住址
        }
      }, // 表单
      photo: '', // 图片路径
      defaultPhoto: require('../../assets/global_images/photo.png'), // 默认图片路径
      fileList: [],
      imageList: [],
      sexList: [], // 性别列表
      dutyList: [], // 职务列表
      nationList: [], // 民族列表
      rules: {
        // personCode: [{ required: true, message: '员工编号必填', trigger: ['blur', 'change'] }],
        name: [{ required: true, message: '姓名必填', trigger: ['blur', 'change'] }],
        idCardNo: [{ required: true, validator: validateIDCard, trigger: ['blur', 'change'] }],
        deptid: [{ required: true, message: '单位/部门必选', trigger: 'change' }],
        duty: [{ required: true, message: '职务必选', trigger: 'change' }],
        sex: [{ required: true, message: '性别必选', trigger: 'blur' }],
        birthday: [{ required: true, message: '出生日期必填', trigger: ['blur'] }]
      },
      dialogVisible: false,
      labelPosition: 'right',
      responseAssignShow: false,
      deptShowTop: false, // 权属单位下拉是否显示顶级
      deptShow: true,
      formLoading: false,
      devLoading: false,
      idsrc: 'static/IDCard/IDCardReader.htm',
      step: '1', // 添加步骤 1-保存人员 2-保存虹膜
      devInited: false,
      irisBtnName: '',
      irisBtnDisable: true,
      irisForm: {
        personId: '',
        idCardNo: '',
        image_zy0: '',
        image_yy0: '',
        image_zy1: '',
        image_yy1: ''
      },
      iframeMsg: ''
    }
  },
  watch: {
    'personForm.idCardNo': function(val) {
      this.personForm.birthday = getBirthdayByIdNO(val)
      this.personForm.sex = getSexByIdNO(val)
    }
  },
  mounted() {
    // 接收iframe的传值
    window['vueDefined'] = (receiveParams) => {
      this.receiveParamsFromHtml(receiveParams)
    }
    this.fetchSexType()// 获取性别列表
    this.fetchDutyType() // 获取职务列表
    this.fetchNationType() // 获取民族列表
    if (this.$route.query.personType) {
      this.personType = this.$route.query.personType
      this.personForm.personType = this.$route.query.personType
    }
    if (this.$route.query && this.$route.query.type) {
      const type = this.$route.query.type
      this.isSave = false // isSave置为false,表示没有点击过保存按钮
      if (type === 'create') {
        this.isEditMode = false // 不是编辑页面
      } else if (type === 'update') {
        this.isEditMode = true // 是编辑页面
        this.fetchData(this.$route.query.id)
      }
    }
  },
  activated() {
    // 接收iframe的传值
    window['vueDefined'] = (receiveParams) => {
      this.receiveParamsFromHtml(receiveParams)
    }
    if (this.$route.query && this.$route.query.type) {
      this.isSave = false // isSave置为false,表示没有点击过保存按钮
      const type = this.$route.query.type
      if (type === 'create') {
        this.isEditMode = false
        this.canSave = true
      } else if (type === 'update') {
        this.isEditMode = true
        this.canSave = true
        this.fetchData(this.$route.query.id)
      }
    }
    if (this.$route.query.personType) {
      this.personType = this.$route.query.personType
      this.personForm.personType = this.$route.query.personType
    }
  },
  methods: {
    // 取消
    cancel() {
      this.dialogFormVisible = false
      this.fileList = []
      // 清除验证
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    beforeRouteLeave(to, from, next) {
      window.frames['iframeMap'].closeDev()
      next()
    },
    fetchData(id) {
      this.formLoading = true
      const base_url = process.env.BASE_API + '/static/'
      personInfo(id).then(response => {
        const personForm = response.data
        this.personForm = {
          id: personForm.id, // 人员id
          personCode: personForm.personCode, // 人员编号
          idCardNo: personForm.idCardNo, // 身份证号
          name: personForm.name, // 姓名
          deptid: personForm.deptid, // 单位/部门
          remarks: personForm.remarks, // 备注
          duty: personForm.duty, // 职务
          sex: personForm.sex, // 性别
          personType: personForm.personType, // 人员类型
          birthday: personForm.birthday, // 出生日期
          nation: personForm.nation, // 民族
          photo: personForm.photo,
          ext: {
            certificationUnit: personForm.ext.certificationUnit, // 颁发证件单位，
            address: personForm.ext.address// 住址
          }
        }
        if (personForm.photo !== '') {
          this.photo = base_url + personForm.photo
        }
        this.formLoading = false
      })
    },
    readIDCard() {
      window.frames['iframeIDCard'].ReadCard()
      if (window.frames['iframeIDCard'].result) {
        this.personForm.idCardNo = window.frames['iframeIDCard'].CardNo
        this.personForm.name = window.frames['iframeIDCard'].Name
        // if (window.frames['iframeIDCard'].Sex === '2') { this.personForm.sex = '女' } else { this.personForm.sex = '男' }
        this.personForm.sex = parseInt(window.frames['iframeIDCard'].Sex)
        this.personForm.birthday = window.frames['iframeIDCard'].Born.substring(0, 4) + '-' + window.frames['iframeIDCard'].Born.substring(4, 6) + '-' + window.frames['iframeIDCard'].Born.substring(6, 8)
        this.photo = 'data:image/png;base64,' + window.frames['iframeIDCard'].Picture
        this.personForm.nation = window.frames['iframeIDCard'].Nation + '族'
        var nationName = window.frames['iframeIDCard'].Nation + '族'
        for (var item of this.nationList) {
          if (item.name === nationName) {
            this.personForm.nation = item.value
            break
          }
        }
        this.personForm.ext.certificationUnit = window.frames['iframeIDCard'].IssuedAt
        this.personForm.ext.address = window.frames['iframeIDCard'].Address
      } else {
        this.$message.warning('读卡失败')
      }
      // const baseUrl = getProject().register_url
      // // const url = 'openIE:' + baseUrl + '?token=' + token + '_id=' + id + '_idCardNo=' + idCardNo
      // window.location.href = url
    },
    // 重置表单
    resetForm() {
      this.personForm = {
        idCardNo: '', // 身份证号
        name: '', // 姓名
        deptid: '', // 单位/部门
        remarks: '', // 备注
        duty: '', // 职务
        sex: '', // 性别
        personType: '1', // 人员类型
        birthday: '', // 出生日期
        nation: '', // 民族
        photo: '',
        ext: {
          certificationUnit: '', // 颁发证件单位，
          address: ''// 住址
        }
      }
      this.photo = ''
      this.irisForm = {
        personId: '',
        idCardNo: '',
        image_zy0: '',
        image_yy0: '',
        image_zy1: '',
        image_yy1: ''
      }
      // 清除验证
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 保存数据
    saveData: function() {
      // 照片不为空则对照片进行处理
      if (this.photo !== '') {
        if (this.photo.startsWith('http')) { // 上传的普通图片,去掉static头
          let index = this.photo.indexOf('/static/')
          if (index !== -1) {
            index += 8
          }
          this.personForm.photo = this.photo.substring(index)
        } else if (this.photo.startsWith('data:image')) { // 读卡器读的base64图片，直接传编码
          console.log()
          this.personForm.photo = this.photo
        }
      }
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.canSave = false
          // 如果新增页面未保存，则调用add
          // 如果是新增页面已经保存，则调用update
          // 其他情况均为修改页面
          if (this.isSave === false && this.isEditMode === false) {
            addPerson(this.personForm).then(response => {
              if (response.code === 200) {
                // 保存用户id
                this.personForm.id = response.data.id
                this.personForm.personCode = response.data.code
                this.isSave = true
                this.$message.success('保存成功!')
              }
              this.canSave = true
            }).catch(() => {
              this.canSave = true
            })
          } else if (this.isSave === true && this.isEditMode === false) {
            updatePerson(this.personForm).then(response => {
              if (response.code === 200) {
                this.$message.success('保存成功!')
              }
              this.canSave = true
            })
          } else {
            updatePerson(this.personForm).then(response => {
              if (response.code === 200) {
                this.$message.success('保存成功!')
              }
              this.canSave = true
            })
          }
        }
      })
    },
    // 注册虹膜 (没用了)
    registerIris() {
      // 如果已经保存
      // this.isSave = true
      if (this.isSave) {
        this.step = '2'
        this.irisBtnName = '初始化设备'
        this.irisBtnDisable = true
        this.devLoading = true
      } else {
        this.$message.warning('请先保存用户基本信息')
      }
    },
    // 接收iframe传来的消息
    receiveParamsFromHtml(res) {
      if (res === 'saveIrisData') {
        this.saveIrisData()
      } else {
        this.iframeMsg = res
      }
    },
    // 没用了
    startCapture() {
      if (this.irisBtnName === '初始化设备') {
        this.devLoading = true
        this.irisBtnDisable = true
        window.frames['iframeMap'].initDev()
      } else if (this.irisBtnName === '立即采集') {
        this.irisBtnDisable = true
        window.frames['iframeMap'].StartCaptureStepTwo()
      } else if (this.irisBtnName === '保存虹膜数据') {
        this.irisBtnDisable = true
        this.saveIrisData()
      }
    },
    // 保存虹膜数据
    saveIrisData() {
      this.irisForm.image_zy0 = window.frames['iframeMap'].image0
      this.irisForm.image_zy1 = window.frames['iframeMap'].image1
      this.irisForm.image_yy0 = window.frames['iframeMap'].image2
      this.irisForm.image_yy1 = window.frames['iframeMap'].image3
      this.irisForm.personId = this.personForm.id
      this.irisForm.idCardNo = this.personForm.idCardNo
      saveIris(this.irisForm).then(response => {
        this.step = '1'
        if (response.code === 200) {
          // this.$message.success('保存虹膜成功')
          this.$confirm('新增成功，是否继续新增?', '提示', {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'info'
          }).then(() => {
            this.resetForm()
            this.isSave = false
            this.isEditMode = false
            this.$nextTick(() => {
              this.$refs['dataForm'].clearValidate()
            })
          }).catch(() => {
            this.$router.push({ path: '/staff' })
          })
        }
      })
    },
    // 图片上传
    uploadFile(file) {
      console.log('uploadFile:' + file.file.name)
      // const base_url = process.env.BASE_API + '/static/'
      // Uploadimg(file).then(res => {
      //   if (res.code === 200) {
      //     this.photo = base_url + res.data
      //   } else {
      //     this.$message.warning(res.message)
      //   }
      // })
      // 转base64
      this.getBase64(file.file).then(resBase64 => {
        this.photo = 'data:image/png;base64,' + resBase64.split(',')[1] // 直接拿到base64信息
        console.log(this.photo)
      })
    },
    // 上传前判断文件格式及大小
    handleBeforeUpload(file) {
      const isJPG = (file.type === 'image/jpeg') || (file.type === 'image/png')
      let res = true
      console.log(file.size)
      const isLt2M = file.size / 1024 < 200
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!')
        res = false
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 200KB!')
        res = false
      }
      return res
    },
    // 上传成功后回显
    handleSuccess(response, file) {
      console.log('handleSuccess')
      debugger
      const base_url = process.env.BASE_API + '/static/'
      if (response.code === 200) {
        this.photo = base_url + response.data
      } else {
        this.$message.warning(response.message)
      }
    },
    // 获取性别
    fetchSexType() {
      getSexType().then(response => {
        this.sexList = response.data
      })
    },
    // 获取职务
    fetchDutyType() {
      getDutyType().then(response => {
        this.dutyList = response.data
      })
    },
    // 获取民族
    fetchNationType() {
      getNationType().then(response => {
        this.nationList = response.data
      })
    },
    getBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        let fileResult = ''
        reader.readAsDataURL(file)
        // 开始转
        reader.onload = function() {
          fileResult = reader.result
        }
        // 转 失败
        reader.onerror = function(error) {
          reject(error)
        }
        // 转 结束  咱就 resolve 出去
        reader.onloadend = function() {
          resolve(fileResult)
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" >
  .hide .el-upload--picture-card {
    display: none;
  }
  .main-form{
    margin: 0px 30px;
    margin-top: 20px;
    padding: 10px;
    overflow: auto;
  }
  .el-dialog{
    width:700px
  }
  .el-select{
    width: 100%;
  }
  .line{
    width: 50px;
    margin-left: 5px;
  }
  .hide .el-upload-–picture-card{
    display: none;
  }
  .imgBox{
    width: 100%;
    text-align: center;
  }
  .avatar-uploader .el-upload {
    margin-left: 12px;
    margin-top: 10px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 238px;
    line-height: 238px;
    text-align: center;
  }
  .avatar {
    margin: 10px;
    display: block;
  }
  .id-card-btn{
    width:126px;
    margin-left: 12px;
    margin-top: 20px;
   }
  .button-div{
    height: 80px;
    text-align:center;
    padding-top: 15px;
  }
  .iframeMsg{
    height: 50px;
    text-align: center;
    margin-top: 5px;
  }
</style>
