<template>
  <div
    class="sell-form">
    <div class="sell-form-inner">
      <div class="top-block">
        <div
          class="side-content block-wrap"
          style="width: 400px">
          <div
            class="block-title"
            style="margin-bottom:20px">
            请刷IC卡
          </div>
          <div class="searchInput">
            <ReaderInput
              type="IC"
              v-model="iccardNo"></ReaderInput>

            <el-button
              type="primary"
              @click="getCardInfo(iccardNo)">
              查询
            </el-button>
          </div>
          <div
            class="block-title"
            style="margin:20px 0 10px;"
            v-if="memberTypeInfo.name">
            会员类型信息
          </div>
          <el-form
            v-if="memberTypeInfo.name"
            inline
            label-width="100px"
            class="dialog-info">
            <el-form-item
              style="white-space: nowrap"
              label="会员类型">
              {{ memberTypeInfo.name }}
            </el-form-item>
            <el-form-item
              label="价格">
              {{ memberTypeInfo.capital }}
            </el-form-item>
            <el-form-item
              label="会员大类">
              {{ memberTypeInfo.category | memberCategory }}
            </el-form-item>
            <el-form-item
              label="人数">
              {{ memberTypeInfo.person_num }}
            </el-form-item>
            <el-form-item
              style="width: 100%"
              label="游玩有效期">
              {{ memberTypeInfo.play_startdate | formatDate }} 至 {{ memberTypeInfo.play_enddate | formatDate }}
            </el-form-item>
            <el-form-item
              style="width: 100%"
              label="通关方式">
              <el-tag v-if="memberTypeInfo.iccard_check">
                IC卡
              </el-tag>
              <el-tag v-if="memberTypeInfo.idcard_check">
                身份证
              </el-tag>
              <el-tag v-if="memberTypeInfo.face_check">
                人脸
              </el-tag>
              <el-tag v-if="memberTypeInfo.fingerprint_check">
                指纹
              </el-tag>
            </el-form-item>
            <el-form-item
              style="width: 100%"
              label="检票规则">
              {{
                [
                  memberTypeInfo.check_pattern,
                  memberTypeInfo.scenic_checkTimes_type,
                  memberTypeInfo.valid_days,
                  memberTypeInfo.checkLimitTimes
                ] | complicatedCheckType
              }}
            </el-form-item>
            <el-form-item
              style="width: 100%"
              label="激活截止日期">
              <b :style="showWarning?'color:red':'color:green'">
                {{ memberInfo.activate_end_time | formatDate }}
                <span v-show="showWarning">(已过期)</span>
              </b>
            </el-form-item>
            <div
              class="block-wrap">
              <div class="block-title">
                适用景点及检票次数
              </div>
              <ul class="pill-wrap">
                <li
                  class="pill"
                  v-for="(item,index) in memberTypeInfo.memberTypeScenic"
                  :key="index">
                  <span>{{ getScenicName(item.scenic_id) }}</span>
                  <span v-if="memberTypeInfo.check_pattern === 'count' && memberTypeInfo.scenic_checkTimes_type === 1">
                    {{ item.checkLimitTimes }}
                  </span>
                </li>
              </ul>
            </div>
          </el-form>
        </div>
        <div class="main-content">
          <el-form
            ref="form"
            :model="form"
            :inline="true"
            label-width="90px"
            class="content-inner custom-scroll block-wrap">
            <div
              class="block-title">
              会员信息：
            </div>
            <el-form-item
              verify
              label="姓名"
              prop="name">
              <el-input v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item
              verify
              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-form-item
              label="住址"
              prop="address">
              <el-input v-model="form.address"></el-input>
            </el-form-item>
            <el-form-item
              key="id1"
              :verify="verifyId"
              v-if="form.papers_type==='ID_CARD'"
              label="证件号码"
              prop="papers_id">
              <ReaderInput
                type="ID"
                v-model="form.papers_id"
                @change="form.papers_id=$event.IDNumber,form.name=$event.Name"></ReaderInput>
            </el-form-item>
            <el-form-item
              v-else
              verify
              key="id2"
              label="证件号码"
              prop="papers_id">
              <el-input v-model="form.papers_id"></el-input>
            </el-form-item>
            <el-form-item
              :verify="verifyPhone"
              class="is-required"
              label="联系方式"
              prop="phone">
              <el-input v-model="form.phone"></el-input>
            </el-form-item>
            <div class="block-title">
              检票信息
            </div>
            <el-form-item
              verify
              v-if="memberTypeInfo.iccard_check"
              label="IC卡号"
              prop="iccardNo">
              <ReaderInput
                type="IC"
                v-model="form.iccardNo"></ReaderInput>
            </el-form-item>
            <el-form-item
              :verify="verifyId"
              key="id1"
              class="is-required"
              v-if="memberTypeInfo.idcard_check"
              label="身份证号"
              prop="idcardNo">
              <ReaderInput
                type="ID"
                v-model="form.idcardNo"
                @change="setIdcardInfo"></ReaderInput>
            </el-form-item>
            <br>
            <el-form-item
              v-if="memberTypeInfo.category === 2"
              class="is-required"
              label="姓名">
              <el-input
                v-model="form.name"
                style="width: 100px"></el-input>
            </el-form-item>
            <el-form-item
              class="is-required"
              v-if="memberTypeInfo.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-form-item
              class="is-required"
              v-if="memberTypeInfo.face_check"
              label="照片">
              <GetFace v-model="form.facePic"></GetFace>
            </el-form-item>
            <br>
            <div v-if="memberTypeInfo.category === 2">
              <div
                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="memberTypeInfo.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="memberTypeInfo.face_check"
                  label="照片">
                  <GetFace v-model="item.facePic"></GetFace>
                </el-form-item>
              </div>
            </div>
            <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-form-item
              label="有效期至">
              {{ endtime | formatDate }}
            </el-form-item>
          </el-form>
          <div class="footer block-wrap">
            <div
              class="btn-wrap">
              <el-button
                size="medium"
                @click="reset">
                重置
              </el-button>
              <el-button
                size="medium"
                type="primary"
                class="warn-btn"
                @click="confirm">
                确认激活
              </el-button>
            </div>
          </div>
        </div>
      </div>
      <ElDialog
        title="信息确认"
        width="740px"
        v-model="dialogVisible">
        <ConfirmDialog
          :type-info="memberTypeInfo"
          :info="form"
          @submit="submit"
        ></ConfirmDialog>
      </ElDialog>
    </div>
  </div>
</template>

<script>
import moment from 'moment'

import ElDialog from '@/components/Dialog'
import ConfirmDialog from './memberActive/ConfirmDialog'
import ReaderInput from '@/components/ReaderInput'
import GetFace from '@/components/GetFace'

import { verifyId, verifyPhone } from '@/utils/validate.js'
import { getScenic } from '@/api/ticketType'
import { iccardActivation, getIccardInfo } from '@/api/member'
import { papersType } from '@/assets/staticData'
import { getFingerInfo } from '@/api/ZTKReaderApi'
import { compareFinger } from '@/api/finger'

export default {
  components: {
    ElDialog,
    ConfirmDialog,
    ReaderInput,
    GetFace
  },
  data () {
    return {
      iccardNo: '',
      memberTypeInfo: {},
      memberInfo: {},
      scenicList: [],
      papersOption: Object.keys(papersType).map(key => {
        return {
          id: key,
          name: papersType[key]
        }
      }),
      pickerOptions: {
        disabledDate: (theTime) => {
          let startTime = moment().format('YYYY-MM-DD') + ' 00:00:00'
          if (moment(this.memberTypeInfo.play_startdate).isAfter(startTime)) {
            startTime = this.memberTypeInfo.play_startdate
          }
          return moment(theTime).isBefore(startTime) || moment(theTime).isAfter(this.memberTypeInfo.play_enddate)
        }
      },
      dialogVisible: false, // 信息确认
      form: {
        id: '',
        storage_id: '',
        type_id: '',
        name: '',
        papers_type: '',
        address: '',
        papers_id: '', // 证件号码
        phone: '',
        iccard: {
          cardNo: ''
        },
        iccardNo: '',
        idcard: {
          idcardNo: ''
        },
        idcardNo: '',
        face: {
          face_img: ''
        },
        starttime: '',
        endtime: '',
        fingerPic: '',
        facePic: ''
      },
      childList: [],
      fingerInfo: [],
      fingerForm: {}, // 正在获取指纹的人员，this.form或childList中的item
      fingerTimer: null, // 读取指纹的timeout
      gettingFinger: false, // 正在读取指纹信息
      fingerValid: false // 指纹信息是否有效
    }
  },
  computed: {
    showWarning () {
      if (!this.memberInfo.activate_end_time) return false
      return new Date(this.memberInfo.activate_end_time).getTime() < new Date().getTime()
    },
    endtime () {
      if (this.form.starttime) {
        let endTime = ''
        if (this.memberTypeInfo.check_pattern === 'count') {
          // 按次数，结束时间为会员类型的截止时间
          endTime = this.memberTypeInfo.play_enddate
        } else if (this.memberTypeInfo.check_pattern === 'time') {
          // 按时长
          if (this.memberTypeInfo.valid_days === -1) {
            // 截止到会员有效期
            endTime = this.memberTypeInfo.play_enddate
          } else {
            // 按有效天数，结束时间为有效时长和会员类型截止的较早者
            let validEnd = moment(this.form.starttime).add(this.memberTypeInfo.valid_days, 'days').subtract(1, 'seconds')
            endTime = validEnd.isBefore(this.memberTypeInfo.play_enddate) ? validEnd : this.memberTypeInfo.play_enddate
          }
        }
        return endTime
      } else {
        return ''
      }
    }
  },
  mounted () {
    this.getScenicList()
  },
  beforeDestroy () {
    this.fingerTimer && clearTimeout(this.fingerTimer)
    this.gettingFinger = false
  },
  methods: {
    verifyId,
    verifyPhone,
    // 获取景点列表
    getScenicList () {
      return getScenic().then(res => {
        let treeArr = res?.data.children.map(item => item.data)
        this.scenicList = treeArr
      })
    },
    // 获取卡信息
    getCardInfo (no) {
      getIccardInfo(no).then(res => {
        console.log(res)
        this.memberTypeInfo = res.memberType
        this.memberInfo = res.member
        this.form = Object.assign({}, this.form, res.member)
        this.form.iccardNo = this.form.iccard ? this.form.iccard.cardNo : ''
        this.form.idcardNo = this.form.idcard ? this.form.idcard.idcardNo : ''
        this.childList = this.form.childList.map(item => {
          return {
            id: item.id,
            fingerPic: '',
            facePic: '',
            name: ''
          }
        })
        console.log(this.form)
        this.setCreateTime()
      })
    },
    getScenicName (id) {
      let scenic = this.scenicList.find(s => s.id === id)
      return scenic ? scenic.name : ''
    },
    getCheckCount (typeInfo, item) {
      switch (typeInfo.check_pattern) {
        case 'count':
          return typeInfo.scenic_checkTimes_type === 1 ? item.checkLimitTimes + ' 次' : ''
        case 'time':
          return ''
      }
    },
    // 预订日期的初始值是“游玩开始时间”和“今天”两者较后的时间
    setCreateTime () {
      if (moment().isAfter(this.memberTypeInfo.play_startdate)) {
        this.form.starttime = new Date(moment().format('YYYY-MM-DD') + ' 00:00:00')
      } else {
        this.form.starttime = new Date(this.memberTypeInfo.play_startdate)
      }
    },
    // 点击指纹开关，开始采集指纹
    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()
    },
    // 读取身份证后设置人员姓名
    setIdcardInfo (event) {
      this.form.idcardNo = event.IDNumber
      this.form.name = event.Name
      if (this.form.papers_type === 'ID_CARD') {
        this.form.papers_id = event.IDNumber
      }
    },
    // 提交
    confirm () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.endtime = new Date(this.endtime)
          if (this.memberTypeInfo.fingerprint_check) {
            // 检查父级会员的指纹信息
            if (this.form.fingerPic) {
              this.form.finger = {
                finger_pic: this.form.fingerPic,
                finger_type: 'AFIS'
              }
              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,
                  finger_type: 'AFIS'
                }
              })
            }
          } else {
            this.form.finger = null
            this.childList.forEach(item => {
              item.finger = null
            })
          }
          // 检查父级会员的人脸信息
          if (this.memberTypeInfo.face_check) {
            if (this.form.facePic) {
              this.form.face = {
                face_img: this.form.facePic
              }
              this.form.facePic = ''
            } else {
              this.$message.error('请录入人脸照片')
              return
            }
            if (this.childList.some(item => !item.facePic)) {
              this.$message.error('请录入人脸照片')
            } else {
              this.childList.forEach(item => {
                item.face = {
                  face_img: item.facePic
                }
              })
            }
          } else {
            this.form.face = null
            this.childList.forEach(item => {
              item.face = null
            })
          }
          this.form.childList = this.childList.map(item => {
            return {
              id: item.id,
              name: item.name,
              face: item.face,
              finger: item.finger
            }
          })
          if (this.memberTypeInfo.idcard_check) {
            this.form.idcard = {
              idcardNo: this.form.idcardNo
            }
          } else {
            this.form.idcard = null
          }
          if (this.memberTypeInfo.iccard_check) {
            this.form.iccard = {
              cardNo: this.form.iccardNo
            }
          } else {
            this.form.iccard = null
          }
          this.dialogVisible = true
        } else {
          console.log('error submit!')
        }
      })
    },
    submit () {
      iccardActivation(this.form).then(res => {
        this.$message.success('激活成功')
        this.reset()
      })
    },
    reset () {
      this.$refs.form.resetFields()
      this.iccardNo = ''
      this.memberTypeInfo = {}
      this.childList = []
    }
  }
}
</script>

<style lang="scss" scoped>
.sell-form {
  .svg-icon {
    width: 20px; height: 20px;  margin-left: 10px; color: #999;  cursor: pointer;
  }
  .searchInput{
    display: flex;
    .el-input{
      flex: 1
    }
    .el-button{
      margin-left: 10px;
    }
  }
  .finger-item {
    display: flex;  height: 100px;
    .el-icon-close {
      margin-left: 10px;  font-size: 20px;  color: #999;
    }
    .finger-pic {
      width: 80px;  height: 100px;  overflow: hidden;  background-position: center;  background-size: contain;  border: 1px solid #e2e2e2;  border-radius: 5px;
    }
    .finger-active::after {
      display: block;  width: 100%;  height: 1px;  content: '';  border-top: 120px solid rgba(100, 100, 100, .2);  animation: scan 2s forwards infinite linear;
    }
    @keyframes scan {
      0% {
        transform: translateY(-120px);
      }
      25% {
        transform: translateY(-120px);
      }
      100% {
        transform: translateY(0);
      }
    }
  }
}

</style>
