<template>
  <el-form
    class="sell-form"
    ref="form"
    :model="form"
    :inline="true"
    label-width="90px">
    <div class="sell-form-inner">
      <div class="top-block">
        <div class="side-content">
          <TypeList
            slot="left"
            ref="ticketList"
            :disabled="isOnline"
            v-model="currentType"></TypeList>
        </div>
        <div class="main-content">
          <div class="content-inner custom-scroll block-wrap">
            <div
              class="block-title"
              v-if="currentType">
              会员信息：<b>{{ currentType.name }}</b>
            </div>
            <el-form-item
              verify
              :can-be-empty="(requiredField.length&&requiredField.indexOf('name')>-1)?undefined : true"
              label="姓名"
              prop="name">
              <el-input v-model="form.name"></el-input>
            </el-form-item>

            <el-form-item
              verify
              :can-be-empty="(requiredField.length&&requiredField.indexOf('papers_type')>-1)?undefined : true"
              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
              key="id1"
              :verify="verifyId"
              :can-be-empty="(requiredField.length&&requiredField.indexOf('papers_id')>-1)?undefined : true"
              v-if="form.papers_type==='ID_CARD'"
              label="证件号码"
              prop="papers_id">
              <ReaderInput
                type="ID"
                @changePapersId="changePapersId"
                @change="form.papers_id=$event.IDNumber,form.name=$event.Name"
                v-model="form.papers_id"></ReaderInput>
            </el-form-item>
            <el-form-item
              v-else
              key="id2"
              label="证件号码"
              prop="papers_id"
              verify
              :can-be-empty="(requiredField.length&&requiredField.indexOf('papers_id')>-1)?undefined : true"
            >
              <el-input
                @blur="changePapersId"
                v-model="form.papers_id"></el-input>
            </el-form-item>
            <el-form-item
              :verify="verifyPhone"
              :can-be-empty="(requiredField.length&&requiredField.indexOf('phone')>-1)?undefined : true"
              label="手机"
              prop="phone">
              <el-input v-model="form.phone"></el-input>
            </el-form-item>

            <el-form-item
              label="住址"
              prop="address">
              <el-input v-model="form.address"></el-input>
            </el-form-item>

            <el-form-item
              v-if="(currentType.category===5)"
              label="密码"
              prop="password">
              <el-input
                v-model="form.password"
                show-password></el-input>
            </el-form-item>

            <el-form-item
              v-if="projectName === 'shqzly'"
              label="儿童姓名"
              prop="child_name">
              <el-input v-model="form.child_name"></el-input>
            </el-form-item>

            <el-form-item
              v-if="projectName === 'shqzly'"
              label="出生日期"
              prop="birthday">
              <el-date-picker
                v-model="form.birthday"
                type="date"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>

            <el-form-item
              v-if="projectName === 'shqzly'"
              label="售票员"
              prop="sale_name">
              <el-input v-model="form.sale_name"></el-input>
            </el-form-item>

            <el-form-item
              label="线上会员"
              prop="isOnline">
              <el-switch
                v-model="isOnline"
                @change="val=>onlineOrder=[]">
              </el-switch>
            </el-form-item>

            <template v-if="isOnline">
              <div
                class="block-title"
                v-if="currentType">
                绑定线上会员订单 <el-button
                  type="primary"
                  size="small"
                  @click="$refs.orderSelector.show()">
                  选择线上订单
                </el-button>
              </div>

              <div class="table-wrap">
                <div class="inner">
                  <el-table
                    border
                    stripe
                    style="width:100%"
                    :data="onlineOrder">
                    <el-table-column
                      width="180"
                      prop="orderNo"
                      label="订单号">
                    </el-table-column>
                    <el-table-column
                      prop="otaOrderNo"
                      label="OTA订单号">
                    </el-table-column>
                    <el-table-column
                      prop="otaSourceName"
                      label="分销商">
                    </el-table-column>
                    <el-table-column
                      label="票种">
                      <template slot-scope="scope">
                        {{ scope.row.tickets[0].tname }}
                      </template>
                    </el-table-column>
                    <el-table-column
                      width="80"
                      prop="tickets.length"
                      label="票数量">
                    </el-table-column>
                    <el-table-column
                      width="100"
                      prop="buyerName"
                      label="预订人">
                    </el-table-column>
                    <el-table-column
                      width="120"
                      prop="buyerPhone"
                      label="预订手机">
                    </el-table-column>
                    <el-table-column
                      label="证件号码">
                      <template slot-scope="scope">
                        {{ scope.row.buyerIdentifyType | paperType }}
              &nbsp;
                        {{ scope.row.buyerIdentify }}
                      </template>
                    </el-table-column>
                    <el-table-column
                      width="150"
                      label="售票时间">
                      <template slot-scope="scope">
                        {{ scope.row.createTime | formatTime }}
                      </template>
                    </el-table-column>
                    <el-table-column
                      width="80"
                      label="总价">
                      <template slot-scope="scope">
                        {{ scope.row.tickets.length * scope.row.tickets[0].price }}
                      </template>
                    </el-table-column>
                    <el-table-column
                      width="100"
                      label="状态">
                      <template slot-scope="scope">
                        <el-tag :type="scope.row.status | orderStatusColor">
                          {{ scope.row.status | orderStatus }}
                        </el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column
                      label="操作"
                      fixed="right"
                      width="180"
                    >
                      <template slot-scope="scope">
                        <el-button
                          type="primary"
                          size="small"
                          @click="handleDeleteOnlineOrder">
                          删除
                        </el-button>
                        <el-button
                          type="primary"
                          size="small"
                          @click="$refs.upgradedialog.show({...scope.row,ticketId:ticketId})">
                          会员升级
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </template>

            <div class="block-title">
              检票信息
            </div>
            <el-form-item
              verify
              v-if="currentType.iccard_check"
              label="IC卡号"
              prop="iccard.cardNo">
              <ReaderInput
                type="IC"
                v-model="form.iccard.cardNo">
              </ReaderInput>
            </el-form-item>

            <el-form-item
              verify
              v-if="currentType.category === 2"
              class="is-required"
              label="姓名"
              prop="name">
              <el-input
                v-model="form.name"
                style="width: 100px"></el-input>
            </el-form-item>

            <el-form-item
              :verify="verifyId"
              key="id3"
              v-if="currentType.idcard_check"
              label="身份证号"
              prop="idcard.idcardNo">
              <ReaderInput
                type="ID"
                @change="setIdcardInfo"
                v-model="form.idcard.idcardNo">
              </ReaderInput>
            </el-form-item>

            <el-form-item
              class="is-required"
              v-if="currentType.fingerprint_check"
              label="指纹"
              prop="fingerPic">
              <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>
                <div
                  v-if="gettingFinger && fingerForm === form"
                  class="dark-btn"
                  @click="stopGettingFinger">
                  <svg-icon icon-class="stop" />
                  停止
                </div>
                <div
                  class="dark-btn"
                  @click="manualGetFingerInfo(form)"
                  v-else>
                  <svg-icon icon-class="finger" />
                  读取
                </div>
              </div>
            </el-form-item>
            <el-form-item
              class="is-required"
              v-if="currentType.face_check"
              label="照片"
              prop="facePic">
              <GetFace v-model="form.facePic"></GetFace>
            </el-form-item>
            <br>
            <!-- {{ form.childList }} -->
            <div v-if="currentType.category === 2">
              <div
                v-for="(item, index) in form.childList"
                :key="index">
                <el-form-item
                  verify
                  label="姓名"
                  :prop="'childList.'+index+'.name'">
                  <el-input
                    v-model="item.name"
                    style="width: 100px"></el-input>
                </el-form-item>

                <el-form-item
                  :verify="verifyId"
                  v-if="currentType.idcard_check"
                  label="身份证号"
                  :prop="'childList.'+index+'.idcardNo'">
                  <ReaderInput
                    @change="item.name=$event.Name"
                    type="ID"
                    v-model="item.idcardNo">
                  </ReaderInput>
                </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>
                    <div
                      class="dark-btn"
                      v-if="gettingFinger && fingerForm === item"
                      @click="stopGettingFinger">
                      <svg-icon icon-class="stop" />
                      停止
                    </div>
                    <div
                      class="dark-btn"
                      v-else
                      @click="manualGetFingerInfo(item)">
                      <svg-icon icon-class="finger" />
                      读取
                    </div>
                  </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-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 v-if="(scenicName === '狼山景区' || scenicName === 'demo')">
              <div v-if="currentType && currentType.name && currentType.name.indexOf('年卡') > -1">
                手动一年
                <el-switch
                  v-model="yearSwitchStatus"
                  @change="handleYearSwitchChange" />
              </div>
            </el-form-item>
            <el-form-item
              label="有效期至">
              <p class="cannot-edit">
                {{ endtime | formatDate }}
              </p>
            </el-form-item>
            <!-- <div v-if="currentType.check_pattern === 'time' && currentType.valid_days=== -2"> -->
            <el-form-item
              verify
              v-if="currentType.check_pattern === 'time' && currentType.valid_days=== -2"
              class="is-required"
              label="有效天数"
              prop="valid_days">
              <el-input-number
                controls-position="right"
                v-model.number="form.valid_days"
                :min="1"
                :precision="0"
              ></el-input-number>
            </el-form-item>
            <!-- </div> -->
          </div>

          <div class="footer block-wrap">
            <el-form-item label="交易总金额">
              <div class="input-space warning">
                <b class="strong">
                  {{ form.total_money }}
                </b> 元
              </div>
            </el-form-item>
            <el-form-item
              label="优惠价"
              v-if="allowDiscount">
              <div class="input-space warning longInput">
                <el-input-number
                  :min="0"
                  :precision="2"
                  controls-position="right"
                  v-model="form.total_money"
                  @change="handleChange"></el-input-number>
                元
              </div>
            </el-form-item>
            <el-form-item
              verify
              label="付款方式"
              prop="payChannel">
              <el-select
                v-model="form.payChannel"
                class="warning">
                <el-option
                  v-for="item in payChannelOptions"
                  :key="item"
                  :value="item"
                  :label="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              prop="pay_money"
              label="实付金额">
              <el-input-number
                :min="0"
                :precision="0"
                controls-position="right"
                v-model="form.pay_money"
              ></el-input-number>
            </el-form-item>
            <el-form-item
              :label="payBack>0?'找零':'还需支付'"
              v-if="payBack!==0">
              <div class="input-space">
                <b class="strong">
                  {{ Math.abs(payBack) }}
                </b> 元
              </div>
            </el-form-item>

            <el-form-item
              label="备注">
              <el-input
                type="textarea"
                v-model="form.remark"></el-input>
            </el-form-item>
            <div
              class="btn-wrap">
              <el-button
                size="medium"
                @click="reset">
                重置
              </el-button>
              <el-button
                type="primary"
                size="medium"
                class="warn-btn"
                :disabled="submitDisable"
                @click="confirm">
                {{ submitDisable?'正在处理':'确认办卡' }}
              </el-button>
            </div>
          </div>
        </div>
      </div>
      <ElDialog
        title="信息确认"
        width="740px"
        v-model="dialogVisible"
        :submit-disable="submitDisable"
        @closeTimer="closeTimer"
        @close="handleClose"
      >
        <ConfirmDialog
          :type-info="currentType"
          :info="form"
          :submit-disable="submitDisable"
          @submit="submit"

        ></ConfirmDialog>
      </ElDialog>
      <ElDialog
        title="当前证件已办理过会员（下表为会员销售记录）"
        width="90%"
        v-model="dialogMemberInfoVisible">
        <MemberHistoryInfoTable
          :member-history-info-table-data="memberHistoryInfoTableData"
        >
        </MemberHistoryInfoTable>
        <el-button style="display: none !important;"></el-button>
      </ElDialog>
    </div>

    <ReadValueCard
      ref="readValueCard"
      @getInfo="handleValueCardPay"
      @close="submitDisable=false"></ReadValueCard>
    <QueryPos
      ref="queryPos"></QueryPos>

    <!-- GlobalComponents 全局组件 -->
    <PosQrCodeReader
      ref="posQrCodeReader"
      @getQrcode="submit"></PosQrCodeReader>
    <XSCQrCodeReader
      ref="XSCQrCodeReader"
      @getQrcode="submit"></XSCQrCodeReader>

    <OrderSelector
      @select="handleSelectOnlineOrder"
      @selectTicketId="selectTicketId"
      @upgradeId="upgradeId"
      :member-type="currentType"
      ref="orderSelector"></OrderSelector>
    <UpgradeDialog
      @getUpgrade="upgrade"
      ref="upgradedialog"
    ></UpgradeDialog>
  </el-form>
</template>

<script>
import moment from 'moment'

import ElDialog from '@/components/Dialog'
import GetFace from '@/components/GetFace'

import ReaderInput from '@/components/ReaderInput'

import ConfirmDialog from './memberSales/ConfirmDialog'
import TypeList from './common/TypeList'

import { verifyId, verifyPhone } from '@/utils/validate.js'
import { papersType } from '@/assets/staticData'

import { getFingerInfo } from '@/api/ZTKReaderApi'
// import { getPayChannel } from '@/api/systemConfig'
import { compareFinger } from '@/api/finger'
import { createMember, getMemberTradeList, apiMember } from '@/api/member'
import { valuecardCreateMember } from '@/api/valueCard'
import ReadValueCard from '@/pages/sellManage/common/ReadValueCard'
import posMixin from '@/pages/common/posMixin'
import QueryPos from '../sellManage/common/QueryPos'

import handlePay from '@/pages/sellManage/common/handlePay'
import OrderSelector from './memberSales/OrderSelector'
import UpgradeDialog from './memberSales/UpgradeDialog'
import MemberHistoryInfoTable from './memberList/MemberHistoryInfoTable.vue'

const formData = {
  type_id: '',
  name: '',
  papers_type: '',
  address: '',
  papers_id: '', // 证件号码
  phone: '',
  iccard: {
    cardNo: ''
  },
  idcard: {
    idcardNo: ''
  },
  face: {
    face_img: ''
  },
  starttime: '',
  endtime: '',
  total_money: '',
  pay_money: 0,
  payChannel: '',
  fingerPic: '',
  facePic: '',
  remark: '',
  childList: [],
  valid_days: 1
}
export default {
  mixins: [posMixin],
  components: {
    ElDialog,
    TypeList,
    ConfirmDialog,
    ReaderInput,
    GetFace,
    ReadValueCard,
    QueryPos,
    OrderSelector,
    UpgradeDialog,
    MemberHistoryInfoTable
  },
  data () {
    return {
      projectName: process.env.VUE_APP_PROJECT,
      isOnline: this.$localStore.get('isOnline') || false,
      submitDisable: false,
      createOrderStatus: 0, // 创建订单状态
      payStatus: 0, // 支付状态
      orderTempInfo: {}, // 临时订单信息，防止重复创建订单
      timer: null, // 检查订单是否支付成功计时器
      papersOption: Object.keys(papersType).map(key => {
        return {
          id: key,
          name: papersType[key]
        }
      }),
      memberHistoryInfoTableData: [], // 会员历史信息表格信息
      currentType: {},
      pickerOptions: {
        disabledDate: (theTime) => {
          let startTime = moment().format('YYYY-MM-DD') + ' 00:00:00'
          if (moment(this.currentType.play_startdate).isAfter(startTime)) {
            startTime = this.currentType.play_startdate
          }
          let endTime = moment().add(this.currentType.pre_order_days, 'days').format('YYYY-MM-DD') + ' 00:00:00'
          if (moment(this.currentType.play_enddate).isBefore(endTime)) {
            endTime = this.currentType.play_enddate
          }
          return moment(theTime).isBefore(startTime) || moment(theTime).isAfter(endTime)
        }
      },
      yearSwitchStatus: false, // 狼山提供直接切换一年的选项
      dialogVisible: false, // 信息确认
      dialogMemberInfoVisible: false, // 会员信息弹窗
      form: JSON.parse(JSON.stringify(formData)),
      childList: [],
      fingerInfo: [],
      fingerForm: {}, // 正在获取指纹的人员，this.form或childList中的item
      fingerTimer: null, // 读取指纹的timeout
      gettingFinger: false, // 正在读取指纹信息
      fingerValid: false, // 指纹信息是否有效
      onlineOrder: [],
      ticketId: null // 线上会员订单选中的单个票
    }
  },
  computed: {
    scenicName () {
      return this.$localStore.get('scenicName') || this.$store.state.user.scenicName
    },
    payChannelOptions () {
      return this.$store.state.app.payChannelOptions.filter(i => i.indexOf('旅行社') < 0)
    },
    endtime () {
      if (this.form.starttime) {
        let endTime = ''
        if (this.currentType.check_pattern === 'count') {
          // 按次数，结束时间为会员类型的截止时间
          endTime = this.currentType.play_enddate
        } else {
          // 按时长
          if (this.currentType.valid_days === -1) {
            // 截止到会员有效期
            endTime = this.currentType.play_enddate
          } else if (this.currentType.valid_days === -2) {
            // 当前页面填写
            let validEnd = moment(this.form.starttime).add(this.form.valid_days, 'days').subtract(1, 'seconds')
            endTime = validEnd.isBefore(this.currentType.play_enddate) ? validEnd : this.currentType.play_enddate
          } else {
            // 按有效天数，结束时间为有效时长和会员类型截止的较早者
            let validEnd = moment(this.form.starttime).add(this.currentType.valid_days, 'days').subtract(1, 'seconds')
            endTime = validEnd.isBefore(this.currentType.play_enddate) ? validEnd : this.currentType.play_enddate
          }
        }
        if (this.yearSwitchStatus === true) {
          // 若狼山开启了'一年'开关，则直接加一年，然后减去一秒
          endTime = moment(this.form.starttime).add(1, 'years').subtract(1, 'seconds')
          return endTime
        }
        return endTime
      } else {
        return ''
      }
    },
    showPosQrcode () {
      // 需要手动扫码的景区
      const list = ['东方绿舟', '天津之眼', '绿博园']

      if (this.scenicName === '绿博园' && (!this.$localStore.get('posName') || this.$localStore.get('posName') === 'jianhang')) {
        return false
      }

      return list.indexOf(this.scenicName) > -1
    },
    // 是否允许优惠售票
    allowDiscount () {
      const value = this.$store.state.app.systemConfig.find(i => i.configKey === 'custom_member_price')?.configValue
      return value !== '0'
    },
    requiredField () {
      if (typeof this.currentType.requiredField === 'string') {
        return JSON.parse(this.currentType.requiredField)
      } else {
        return []
      }
    },
    payBack () {
      return (this.form.pay_money * 1000 - this.form.total_money * 1000) / 1000
    }
  },
  watch: {
    currentType (val) {
      this.reset()
      /* 狼山手动一年的重置放到reset()里了
        console.log('切换到的新卡名为：', val.name)
        if (val.name.indexOf('年卡') > -1) {
          this.yearSwitchStatus = false
        }
      */
    },
    isOnline (val) {
      this.form.total_money = val ? 0 : this.currentType.capital
      this.form.pay_money = val ? 0 : this.currentType.capital
    },
    'form.idcard.idcardNo' (newVal, oldVal) {
      // 检票信息里身份证号一改变就触发
      if (newVal.length === 18) {
      // 若是18位的有效身份证号，就查有没有办理会员
        console.log('检票信息里身份证号：', newVal)
        const params = {
          keyWords1: this.form.type_id,
          keyWords5: newVal // 此处不能用this.form.papers_id，而应用newVal。
        }
        apiMember('getMemberList', params).then(res => {
          if (res.list.length) {
            this.$message.error('当前证件已办理过会员。')
            /* 查会员交易记录中的销售记录并弹窗展示 */
            this.showMemberTradeTable(params)
          }
        })
      }
    },
    payChannelOptions: {
      handler (val) {
        this.setPayWay()
      },
      immediate: true
    }
  },
  methods: {
    verifyPhone,
    verifyId,
    handleChange (val) {
      this.form.pay_money = val
    },
    handleYearSwitchChange () { // 狼山会员闰年
      if (this.yearSwitchStatus === true) {
        console.log('一年：', moment(this.endtime).format('YYYY-MM-DD HH:mm:ss'))
        /* 一年：2023-05-23 （加一年）=> 2024-05-23 00:00:00 => (-1s) => 2024-05-22 23:59:59 */
      }
      /* 实际加一年的逻辑不写在这里，而写在computed的endtime()函数内，这里只输出展示一下 */
    },
    changePapersId () {
      if (this.form.papers_id === '') {
        return
      }
      const params = {
        keyWords1: this.form.type_id,
        keyWords5: this.form.papers_id
      }
      apiMember('getMemberList', params).then(res => {
        if (res.list.length) {
          this.$message.error('当前证件已办理过会员。')
          /* 查会员交易记录中的销售记录并弹窗展示 */
          this.showMemberTradeTable(params)
        }
      })
    },
    showMemberTradeTable (listParams) { // 若已经办理会员，则弹出会员办理记录弹窗，参数使用getMemberList的params转换
      const tradeParams = {
        keyWords6: listParams.keyWords1, // 会员类型id (getMemberList中为keyWords1，而getMemberTradeList中为keyWords6)
        keyWords5: listParams.keyWords5, // 身份证号
        keyWords1: 1 // keyWords1 => 交易类型. 1 销售; 2 充值; 3 结算; 4 补卡
      }
      apiMember('getMemberTradeList', tradeParams).then(res => {
        if (res.list.length) { // getMemberTradeList与getMemberList返回列表长度一致(限制交易类型为销售的情况下)，getMemberTradeList更适合展示
          // this.$message.error('会员交易记录也提示当前证件已办理过会员。')
          // console.log(tradeParams)
          this.memberHistoryInfoTableData = res.list
          this.dialogMemberInfoVisible = true
        }
      })
    },
    closeTimer () {
      window.clearTimeout(this.timer)
    },
    formatForm () {
      let val = this.currentType
      this.form.type_id = val.id

      this.form.total_money = this.isOnline ? 0 : val.capital
      this.form.pay_money = this.isOnline ? 0 : val.capital

      if (val.category === 2) {
        this.form.childList = []
        for (let i = 0; i < val.person_num - 1; i++) {
          let form = {
            fingerPic: '',
            facePic: '',
            name: ''
          }
          this.form.childList.push(form)
        }
      }
      this.setCreateTime()
    },
    // 预订日期的初始值是“游玩开始时间”和“今天”两者较后的时间
    setCreateTime () {
      if (moment().isAfter(this.currentType.play_startdate)) {
        this.form.starttime = new Date(moment().format('YYYY-MM-DD') + ' 00:00:00')
      } else {
        this.form.starttime = new Date(this.currentType.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)
      try {
        let res = await getFingerInfo()
        if (res.data.ret === 0) {
          // console.log('%c', `padding:120px 60px;background:url(data:image/png;base64,${res.data.data.jpgBase64}) no-repeat;`)
          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)
        }
      } catch (e) {
        this.$message.error('阅读器连接失败，请检查设备后重试。')
      }
    },
    // 验证指纹结果
    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.idcard.idcardNo = event.IDNumber
      this.form.name = event.Name
      if (this.form.papers_type === 'ID_CARD') {
        this.form.papers_id = event.IDNumber
      }
    },
    // 提交
    confirm () {
      if (this.isOnline && !this.onlineOrder.length) {
        return this.$message.error('请选择线上订单')
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.endtime = new Date(this.endtime)
          if (this.currentType.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.form.childList.some(item => !item.fingerPic)) {
              this.$message.error('请录入指纹')
              return
            } else {
              this.form.childList.forEach(item => {
                item.finger = {
                  finger_pic: item.fingerPic,
                  finger_type: 'AFIS'
                }
              })
            }
          } else {
            this.form.finger = null
            this.form.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.form.childList.some(item => !item.facePic)) {
              this.$message.error('请录入人脸照片')
              return
            } else {
              this.form.childList.forEach(item => {
                item.face = {
                  face_img: item.facePic
                }
              })
            }
          } else {
            this.form.face = { face_img: '' }
            this.form.childList.forEach(item => {
              item.face = { face_img: '' }
            })
          }

          if (!this.currentType.idcard_check) this.form.idcard = { idcardNo: '' }
          if (!this.currentType.iccard_check) this.form.iccard = { cardNo: '' }
          this.dialogVisible = true

          this.payStatus = 0
          this.orderTempInfo = {}
          this.createOrderStatus = 0
        } else {
          console.log('error submit!')
          this.$message.error('错误的提交！')
        }
      })
    },
    submit (qrcode, cardInfo) {
      // 西宁景区储值卡支付预留
      if (this.form.payChannel.indexOf('储值卡') > -1 && this.scenicName === '西宁景区') {
        // ID卡
        this.$refs.readValueCard.show(this.params)
        return
      }

      // 是否使用外部扫码
      if (this.form.payChannel === '聚合扫码' && !qrcode && this.showPosQrcode) {
        this.$refs.posQrCodeReader.show()
        return
      }
      const scanArr = ['中旅银行', '瑞通储值卡', '建行B扫C', '银联B扫C']
      // 是否使用外部扫码
      if (scanArr.indexOf(this.form.payChannel) > -1 && !qrcode) {
        this.$refs.XSCQrCodeReader.show([this.form], this.form.payChannel)
        return
      }
      // 防止重复提交
      if (this.submitDisable) return
      this.submitDisable = true
      if (this.form.iccard && this.form.iccard.cardNo) {
        this.form.iccard.cardNo = this.form.iccard.cardNo + ''
      }
      if (this.payStatus === 1) {
        this.createMember(this.params)
        return
      }
      let params = {
        payChannel: this.form.payChannel,
        member: { ...this.form,
          childList: this.form.childList.map(item => {
            return {
              name: item.name,
              face: item.face,
              finger: item.finger,
              idcard: { idcardNo: item.idcardNo || '' }
            }
          }) },
        memberTrade: {
          payChannel: this.form.payChannel,
          total_money: this.form.total_money,
          pay_money: this.form.total_money,
          trade_type: 1
        },
        orderId: (this.onlineOrder.length && this.onlineOrder[0].id) || '',
        ticketId: this.ticketId || ''
      }
      this.params = params
      this.params.qrCode = qrcode
      this.params.discount = cardInfo ? cardInfo.discount : ''
      this.params.password = cardInfo ? cardInfo.password : ''

      delete params.member.facePic
      // console.log(params)
      this.createMember(params)
      this.ticketId = null
    },
    handleValueCardPay (cardInfo) {
      console.log('储值卡信息', cardInfo)
      valuecardCreateMember({
        cardNo: cardInfo.cardCode,
        cardVendor: 'CHANGYI',
        member: this.params.member,
        memberTrade: this.params.memberTrade
      }).then(res => {
        this.$message.success('添加成功')
        this.reset()
      })
    },
    createMember (params) {
      this.submitDisable = true
      if (this.createOrderStatus === 1) {
        handlePay(this.params, this.orderTempInfo, this, () => {})
        if (this.payStatus !== 1) {
          this.getSingleMember(this.orderTempInfo, params)
        }
      } else {
        createMember(params).then(res => {
          this.$message.success('添加成功')
          this.createOrderStatus = 1
          this.orderTempInfo = res
          handlePay(this.params, res, this, () => {})
          if (this.payStatus !== 1) {
            this.getSingleMember(res, params)
          }
        }).catch(e => {
          this.submitDisable = false
        })
      }
    },
    getSingleMember (res, params) {
      getMemberTradeList({ keyWords7: res?.data }).then(order => {
        if (order.list[0] && order.list[0].pay_status === 'PAYED') {
          this.timer && window.clearTimeout(this.timer)
          this.handleCreateSuccess(params, res)
          this.onlineOrder = []
          this.$log.info('会员创建成功')
        } else if (order.list[0] && order.list[0].pay_status === 'CLOSED') {
          this.timer && window.clearTimeout(this.timer)
          this.$message.error('交易失败，订单关闭，请重新创建订单')
          this.$log.warn('会员创建失败，支付已关闭')
          this.submitDisable = false
          this.visible = false
        } else {
          this.timer = setTimeout(() => {
            this.getSingleMember(res, params)
          }, 2000)
        }
      })
    },
    handleClose () {
      window.clearTimeout(this.timer)
      if (this.submitDisable) {
        this.$confirm('支付尚未完成，是否强制关闭？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$log.info('支付进程被强制关闭')
          this.visible = false

          // 结束支付进程
          this.killAllPosProcess()
        }).catch(() => {})
        return
      }

      this.visible = false
      this.createOrderStatus = 0

      // 结束支付进程
      this.killAllPosProcess()
    },
    handleCreateSuccess (params, res) {
      this.$message.success('出票成功')
      this.dialogVisible = false
      this.submitDisable = false
      // 获取订单详情
      // 自动打印
      // 关闭弹窗
      this.handleClose()
      this.reset()

      // this.$emit('complete')
    },
    setPayWay () {
      const payment = this.$localStore.get('defaultPayWay') || this.payChannelOptions[0]

      this.form.payChannel = this.payChannelOptions.indexOf(payment) < 0 ? this.payChannelOptions[0] : payment
    },
    reset () {
      this.$refs.form.resetFields()
      this.form = JSON.parse(JSON.stringify(formData))
      this.setPayWay()

      this.form.childList = []

      if (!this.isOnline) {
        this.onlineOrder = []
      }

      this.formatForm()
      this.yearSwitchStatus = false /* 卡之前切换时，狼山手动一年的开关要重置关闭 */
    },
    // 升级完的回调
    upgrade (upgrade_id, currentMemberOrder) {
      this.onlineOrder = [currentMemberOrder]
      const order = { tickets: [{ memberTypeId: upgrade_id }] }
      this.$refs.ticketList.selectOrderMemberType(order)
    },
    handleSelectOnlineOrder (order) {
      if (order) {
        this.onlineOrder = [order]
        const params = order.upgrade_id ? { tickets: [{ memberTypeId: order.upgrade_id }] } : order
        this.$refs.ticketList.selectOrderMemberType(params)
        this.ticketId = null
      }
    },
    handleDeleteOnlineOrder () {
      this.onlineOrder = []
    },
    selectTicketId (id) {
      setTimeout(() => {
        this.ticketId = id
      }, 100)
    },
    upgradeId (upgrade_id) {
      this.$nextTick(() => {
        const order = { tickets: [{ memberTypeId: upgrade_id }] }
        this.$refs.ticketList.selectOrderMemberType(order)
      })
    }
  },
  mounted () {
    // getPayChannel().then(res => {
    //   this.payChannelOptions = res
    //   this.form.payChannel = this.payChannelOptions.length > 0 ? this.payChannelOptions[0] : ''
    // })
    this.$watch(
      () => {
        return this.$refs.ticketList.memberList.length
      },
      (val) => {
        console.log('memberListLength ', val)
        let currentType = this.$localStore.get('memberCurrentType')
        let form = this.$localStore.get('memberForm')
        if (currentType) {
          this.$nextTick(() => {
            let memberType = this.$refs.ticketList.memberList.find(v => v.id === currentType.id)
            if (memberType) {
              this.currentType = memberType
              let currentTypeIndex = this.$refs.ticketList.memberList.findIndex(v => v.id === currentType.id)
              this.$refs.ticketList.currentTypeIndex = currentTypeIndex
            }
            this.$localStore.set('memberCurrentType', null)
            if (form) {
              this.$nextTick(() => {
                this.form = form
                this.setCreateTime()
                this.$localStore.set('memberForm', null)
              })
            }
          })
        }
      }
    )
  },
  beforeDestroy () {
    this.fingerTimer && clearTimeout(this.fingerTimer)
    this.gettingFinger = false
    this.killAllPosProcess()
  },
  beforeRouteLeave (to, from, next) {
    this.$localStore.set('isOnline', this.isOnline)
    this.$localStore.set('memberForm', this.form)
    this.$localStore.set('memberCurrentType', this.currentType)
    next()
  }
}
</script>

<style lang="scss" scoped>
.sell-form {
  .cannot-edit {
    width: 170px;  height: 32px;  box-sizing: border-box; padding: 0 15px;  margin: 0;  line-height: 32px;  color: #666;  cursor: not-allowed;  background-color: #eee;  border: 1px solid #dcdfe6;  border-radius: 4px;
  }
  .finger-item {
    display: flex;  height: 120px;
    .el-icon-close {
      margin-left: 10px;  font-size: 20px;  color: #999;
    }
    .finger-pic {
      width: 90px;  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: 100px 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);
      }
    }
  }
}
.longInput{
 ::v-deep .el-input--small{
    width: 120px;
  }
  ::v-deep .el-input-number{
    width: 120px;
  }
}
</style>
<style lang="scss">
.big-padding {
  .el-input--suffix .el-input__inner {
    padding-right: 70px;
  }
}
</style>
