<template>
  <div v-loading="loading">
    <el-form
      inline
      :model="form"
      ref="form"
      class="dialog-info"
      label-width="100px">
      <div
        style="width:100%"
        v-if="checkPermission('member:member_edit')">
        <div class="block-title">
          个人信息
        </div>
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="姓名"
              prop="name">
              <el-input
                v-model="form.name"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="证件类型"
              prop="papers_type">
              <el-select
                value-key="id"
                v-model="form.papers_type"
                placeholder="请选择">
                <el-option
                  v-for="item in papersOption"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              key="id1"
              :verify="verifyId"
              can-be-empty
              v-if="form.papers_type-0===1"
              label="证件号码"
              prop="papers_id">
              <ReaderInput
                type="ID"
                v-model="form.papers_id"></ReaderInput>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              v-if="form.papers_type-0!==1"
              can-be-empty
              key="id2"
              label="证件号码"
              prop="papers_id">
              <el-input v-model="form.papers_id"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :verify="verifyPhone"
              can-be-empty
              label="手机"
              prop="phone">
              <el-input v-model="form.phone"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="住址"
              prop="address">
              <el-input
                v-model="form.address"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="备注"
              prop="remark">
              <el-input
                v-model="form.remark"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col
            v-if="(form.memberType&&form.memberType.category===5)"
            :span="12">
            <el-form-item
              label="密码"
              prop="password">
              <el-input
                v-model="form.password"
                show-password
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col
            v-if="(form.memberType&&form.memberType.category===5)"
            :span="12">
            <el-form-item
              label="确认密码"
              prop="confirmPassword">
              <el-input
                v-model="form.confirmPassword"
                show-password
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div style="width:100%">
        <div class="block-title">
          会员有效期
        </div>
        <el-col :span="12">
          <el-form-item
            verify
            label="会员有效期开始日期"
            prop="starttime">
            <el-date-picker
              :clearable="false"
              :editable="false"
              style="width: 200px;"
              :picker-options="pickerOptions"
              v-model="form.starttime"
              type="date">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            verify
            label="会员有效期截止日期"
            prop="starttime">
            <el-date-picker
              :clearable="false"
              :editable="false"
              style="width: 200px;"
              :picker-options="pickerOptions"
              v-model="form.endtime"
              type="date">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </div>
      <div
        style="width:100%"
        v-if="checkPermission('member:member_passinfo_edit')">
        <div class="block-title">
          通关方式
        </div>
        <el-row>
          <el-col :span="12">
            <el-form-item
              class="is-required"
              v-if="currentType.iccard_check && form.iccard"
              label="IC卡号"
              prop="iccard.cardNo">
              <ReaderInput
                type="IC"
                v-model="form.iccard.cardNo"></ReaderInput>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              class="is-required"
              v-if="currentType.idcard_check && form.idcard"
              label="身份证号"
              prop="idcard.idcardNo">
              <ReaderInput
                type="ID"
                v-model="form.idcard.idcardNo"
                @change="setIdcardInfo"></ReaderInput>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              v-if="currentType.category === 2"
              class="is-required"
              label="姓名">
              <el-input
                v-model="form.name"
                style="width: 100px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              class="is-required"
              v-if="currentType.fingerprint_check"
              label="指纹">
              <div class="finger-item">
                <div
                  class="finger-pic"
                  :class="{'finger-active': gettingFinger && fingerForm === form}"
                  :style="{
                    'background-image': `url(data:image/png;base64,${form.fingerPic})`
                  }">
                </div>
                <i
                  v-if="gettingFinger && fingerForm === form"
                  class="el-icon-close"
                  @click="stopGettingFinger"></i>
                <svg-icon
                  v-else
                  @click.native="manualGetFingerInfo(form)"
                  icon-class="finger" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              class="is-required"
              v-if="currentType.face_check"
              label="照片">
              <GetFace v-model="form.facePic"></GetFace>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div v-if="((currentType.category === 2) && (!checkPermission('member:member_passinfo_edit')))">
        要编辑子卡信息，权限上需要勾选“会员管理”->“会员通关信息编辑”
      </div>
      <!-- 子卡信息编辑权限保持与主卡通关信息权限一致 {{ checkPermission('member:member_passinfo_edit') }}  -->
      <div
        v-if="currentType.category === 2 && checkPermission('member:member_passinfo_edit')"
        style="width: 100%">
        <div class="block-title">
          子卡信息
        </div>
        <div
          class="child-item"
          v-for="(item, index) in childList"
          :key="index">
          <el-form-item
            class="is-required"
            label="姓名">
            <el-input
              v-model="item.name"
              style="width: 100px"></el-input>
          </el-form-item>
          <el-form-item
            class="is-required"
            v-if="currentType.fingerprint_check"
            label="指纹">
            <div class="finger-item">
              <div
                class="finger-pic"
                :class="{'finger-active': gettingFinger && fingerForm === item}"
                :style="{
                  'background-image': `url(data:image/png;base64,${item.fingerPic})`
                }">
              </div>
              <i
                v-if="gettingFinger && fingerForm === item"
                class="el-icon-close"
                @click="stopGettingFinger"></i>
              <svg-icon
                v-else
                @click.native="manualGetFingerInfo(item)"
                icon-class="finger" />
            </div>
          </el-form-item>
          <el-form-item
            class="is-required"
            v-if="currentType.face_check"
            label="人脸照片">
            <GetFace v-model="item.facePic"></GetFace>
          </el-form-item>
        </div>
      </div>
    </el-form>
    <div class="dialog-btn-wrap">
      <el-button
        @click="submit"
        type="primary">
        保存
      </el-button>
    </div>
  </div>
</template>

<script>
import checkPermission from '@/utils/checkPermission'
import { verifyId, verifyPhone } from '@/utils/validate.js'
import { apiMember, getSingleMember } from '@/api/member'
import { getFingerInfo } from '@/api/ZTKReaderApi'
import { compareFinger } from '@/api/finger'
import { papersType } from '@/assets/staticData'
import ReaderInput from '@/components/ReaderInput'
import GetFace from '@/components/GetFace'
export default {
  components: {
    ReaderInput,
    GetFace
  },
  props: {
    comName: {
      type: String,
      default: ''
    },
    currentItem: {
      type: Object,
      default: () => {}
    },
    currentType: {
      type: Object,
      default: () => {}
    }
  },
  data () {
    return {
      loading: false,
      visible: false,
      papersOption: Object.keys(papersType).map(key => {
        return {
          id: key,
          name: papersType[key]
        }
      }),
      fingerInfo: [],
      fingerForm: {},
      fingerTimer: null,
      gettingFinger: false,
      fingerValid: false,
      childList: [],
      form: {
        name: '',
        papers_type: '',
        address: '',
        papers_id: '', // 证件号码
        phone: '',
        password: '',
        confirmPassword: '',
        // 20230516 狼山 增加会员有效期开始和截止日期回显和编辑功能，对应字段为starttime和endtime
        starttime: '', // 会员有效期开始日期
        endtime: '', // 会员有效期截止日期
        iccard: {
          cardNo: ''
        },
        idcard: {
          idcardNo: ''
        },
        finger: {
          finger_pic: ''
        },
        face: {
          face_img: ''
        },
        fingerPic: '',
        facePic: '',
        childList: []
      }
    }
  },
  watch: {
    visible (val) {
      this.fingerTimer && clearTimeout(this.fingerTimer)
      this.clearFinger()
      this.form.facePic = ''
      if (val && this.currentItem.id) {
        this.form = Object.assign({}, this.form, JSON.parse(JSON.stringify(this.currentItem)))
        this.loading = true
        getSingleMember(this.form.id).then(res => {
          this.form.finger = res.finger
          this.form.face = res.face
          this.form.childList = res.childList
          if (this.currentType.fingerprint_check) {
            if (this.form.finger && this.form.finger.finger_pic) {
              this.fingerInfo = [this.form.finger.finger_pic, this.form.finger.finger_pic]
              this.fingerValid = true
              this.form.fingerPic = this.form.finger.finger_pic
            } else {
              this.form.finger = {
                finger_pic: '',
                finger_type: 'AFIS'
              }
              this.fingerInfo = []
              this.fingerValid = false
              this.form.fingerPic = ''
            }
          } else {
            this.form.finger = null
          }
          if (this.currentType.face_check) {
            if (this.form.face && this.form.face.face_img) {
              this.form.facePic = this.form.face.face_img
            } else {
              this.form.face = {
                face_img: ''
              }
              this.form.facePic = ''
            }
          } else {
            this.form.face = null
          }
          if (this.currentType.idcard_check && !this.form.idcard) {
            this.form.idcard = {
              idcardNo: ''
            }
          }
          if (this.currentType.iccard_check && !this.form.iccard) {
            this.form.iccard = {
              cardNo: ''
            }
          }
          if (this.currentType.category === 2 && this.form.childList) {
            this.childList = this.form.childList.map(item => {
              return {
                id: item.id,
                name: item.name,
                face: item.face,
                finger: item.finger,
                facePic: item.face ? item.face.face_img : '',
                fingerPic: item.finger ? item.finger.finger_pic : ''
              }
            })
          }
          this.form.password = ''
          this.form.confirmPassword = ''
          // 余额不应该在编辑接口能编辑
          this.form.total_balance = undefined
          this.form.pay_balance = undefined
          this.form.extra_balance = undefined
        }).finally(() => {
          this.loading = false
        })
        console.log(this.currentType)
      }
    }
  },
  methods: {
    verifyId,
    verifyPhone,
    checkPermission,
    // 读取身份证后设置人员姓名
    setIdcardInfo (event) {
      this.form.idcard.idcardNo = event.IDNumber
      this.form.name = event.Name
      if (this.form.papers_type === 'ID_CARD') {
        this.form.papers_id = event.IDNumber
      }
    },
    manualGetFingerInfo (form) {
      this.fingerForm = form
      this.gettingFinger = true
      this.playMP3(1)
      this.clearFinger()
      this.getFingerInfo()
    },
    stopGettingFinger () {
      this.gettingFinger = false
      this.fingerForm = {}
      this.fingerTimer && clearTimeout(this.fingerTimer)
    },
    // 清空指纹
    clearFinger () {
      this.fingerInfo = []
      this.fingerValid = false
      this.fingerForm.fingerPic = ''
    },
    // 从读卡器读取指纹
    async getFingerInfo () {
      if (!this.gettingFinger || this.fingerInfo.length >= 2) return
      this.fingerTimer && clearTimeout(this.fingerTimer)
      let res = await getFingerInfo()
      if (res.data.ret === 0) {
        this.fingerInfo.push(res.data.data.jpgBase64)
        if (this.fingerInfo.length < 2) {
          this.playMP3(2)
        }
      }
      if (this.fingerInfo.length === 2) {
        this.getFingerResult()
      } else {
        this.fingerTimer = setTimeout(() => {
          this.getFingerInfo()
        }, 300)
      }
    },
    // 验证指纹结果
    getFingerResult () {
      this.compareFinger(this.fingerInfo[0], this.fingerInfo[1]).then(res => {
        if (res) {
          this.playMP3(3)
          this.fingerValid = true
          this.gettingFinger = false
          this.fingerForm.fingerPic = this.fingerInfo[0]
          // hack 修复指纹灯常亮
          getFingerInfo()
        } else {
          this.playMP3(2)
          this.fingerValid = false
          this.fingerForm.fingerPic = ''
          this.fingerInfo.shift()
          this.getFingerInfo()
        }
      })
    },
    // 比对两个指纹
    compareFinger (data1, data2) {
      let params = {
        type: 'AFIS',
        data1: data1,
        data2: data2
      }
      return compareFinger(params).then(res => {
        let result = res?.data.match
        return result === '1'
      })
    },
    // 播放提示音
    playMP3 (n) {
      let src = ''
      switch (n) {
        case 1:
          src = require('@/assets/mp3/finger.mp3')
          break
        case 2:
          src = require('@/assets/mp3/fingeragain.mp3')
          break
        case 3:
          src = require('@/assets/mp3/success.mp3')
          break
      }
      let elem = document.createElement('audio')
      elem.src = src
      elem.play()
    },
    handleClose () {
      this.$parent.handleClose()
      this.fingerTimer && clearTimeout(this.fingerTimer)
      this.gettingFinger = false
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.password && (this.form.password !== this.form.confirmPassword)) return this.$message.error('两次密码不一致,请重新输入')
          if (this.currentType.fingerprint_check) {
            // 检查父级会员的指纹信息
            if (this.form.fingerPic) {
              console.log(this.form.finger)
              this.form.finger.finger_pic = this.form.fingerPic
              this.form.fingerPic = ''
            } else {
              this.$message({
                type: 'error',
                message: '请录制指纹'
              })
              return
            }
            // 不用判断category === 2，因为person_num为1时childList为空
            if (this.childList.some(item => !item.fingerPic)) {
              this.$message.error('请录入指纹')
            } else {
              this.childList.forEach(item => {
                item.finger.finger_pic = item.fingerPic
              })
            }
          } else {
            this.form.finger = null
            this.childList.forEach(item => {
              item.finger = null
            })
          }
          // 检查父级会员的人脸信息
          if (this.currentType.face_check) {
            if (this.form.facePic) {
              this.form.face.face_img = this.form.facePic
            } else {
              this.$message.error('请录入人脸照片')
              return
            }
            if (this.childList.some(item => !item.facePic)) {
              this.$message.error('请录入人脸照片')
              return
            } else {
              this.childList.forEach(item => {
                if (!item.face) {
                  item.face = {}
                }
                item.face.face_img = item.facePic
              })
            }
          } else {
            this.form.face = null
            this.childList.forEach(item => {
              item.face = null
            })
          }
          this.form.childList = this.childList
          if (!this.currentType.idcard_check) this.form.idcard = null
          if (!this.currentType.iccard_check) this.form.iccard = null
          apiMember('updateMember', this.form).then(res => {
            this.$message.success('修改成功')
            this.$emit('updateList')
            this.handleClose()
            this.form.facePic = ''
            this.childList = []
          }).catch(err => {
            console.error(err)
          })
        } else {
          console.log('error submit!')
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.child-item {
  display: flex;
  border-bottom: 1px dashed $blue;
  &:not(:nth-child(2)) {
    padding-top: 18px;
  }
}
.dialog-info .el-form-item{
  width: auto;
}
.finger-item {
  height: 120px;
  display: flex;
  .finger-pic {
    margin-right: 5px;
    width: 90px;
    height: 120px;
    border-radius: 5px;
    border: 1px solid #e2e2e2;
    background-size: contain;
    background-position: center;
    overflow: hidden;
  }
  .finger-active::after {
    content: '';
    display: block;
    width: 100%;
    height: 1px;
    border-top: 120px solid rgba(3, 3, 3, 0.3);
    animation: scan 3s forwards infinite linear;
  }
  @keyframes scan {
    0% {
      transform: translateY(-120px);
    }
    25% {
      transform: translateY(-120px);
    }
    100% {
      transform: translateY(0);
    }
  }
  .svg-icon{
    cursor: pointer;
    width: 20px; height: 20px; color: #999;
  }
}
</style>
