<template>
  <div>
    <el-form
      :model="form"
      ref="form"
      class="dialog-info"
      inline
      label-width="130px"
    >
      <div class="block-title">
        会员信息
      </div>
      <el-form-item label="会员类型">
        {{ currentItem.memberType.name }}
      </el-form-item>
      <el-form-item label="姓名">
        {{ currentItem.name }}
      </el-form-item>
      <el-form-item label="联系方式">
        {{ currentItem.phone }}
      </el-form-item>
      <el-form-item label="证件类型">
        {{ currentItem.papers_type | paperType }}
      </el-form-item>
      <el-form-item label="证件号码">
        <!--
        {{ currentItem.papers_id }}
         -->
        {{ isPapersIdDesensitize ? $options.filters.formatIDCard(currentItem.papers_id,'') : (currentItem.papers_id || '') }}
      </el-form-item>
      <el-form-item label="生效时间">
        {{ currentItem.starttime | formatDate }}
      </el-form-item>
      <el-form-item label="卡类截止时间">
        {{ currentItem.memberType.play_enddate | formatDate }}
      </el-form-item>
      <el-form-item label="创建时间">
        {{ currentItem.createTime | formatTime }}
      </el-form-item>
      <div class="block-title">
        余额信息
      </div>
      <el-form-item label="检票方式">
        {{
          [
            currentItem.memberType.check_pattern,
            currentItem.memberType.scenic_checkTimes_type,
            currentItem.memberType.valid_days,
            currentItem.memberType.checkLimitTimes
          ] | complicatedCheckType
        }}
      </el-form-item>
      <el-form-item label="原截止日期">
        {{ currentItem.endtime | formatDate }}
      </el-form-item>
      <el-form-item
        label="剩余次数"
        v-if="currentItem.memberType.check_pattern === 'count'">
        {{ currentItem.checkLimitTimes - currentItem.has_checked_times }}
      </el-form-item>
      <div class="block-title">
        有效期 / 次数 设置
      </div>
      <el-form-item
        v-if="currentItem.memberType.check_pattern === 'count'"
        prop="recharge_times"
        label="充值次数"
        verify>
        <el-input-number
          controls-position="right"
          :step="1"
          :precision="0"
          v-model="form.recharge_times">
        </el-input-number>
        <br><span style="color:red">（负数为减少次数）</span>
      </el-form-item>
      <el-form-item
        v-if="currentItem.memberType.check_pattern === 'time'"
        prop="recharge_day_time"
        label="充值天数"
        verify>
        <el-input-number
          :max="maxDays"
          :step="1"
          :precision="0"
          controls-position="right"
          v-model="form.recharge_day_time">
        </el-input-number>
        <br><span style="color:red">（负数为减少天数）</span>
      </el-form-item>
      <el-form-item
        v-if="currentItem.memberType.check_pattern === 'time'"
        label="新截止日期">
        {{ newEndDate }}
      </el-form-item>
      <el-form-item
        prop="recharge_start_time"
        label="充值开始生效时间">
        <el-date-picker
          default-time="00:00:00"
          v-model="form.recharge_start_time"
          :picker-options="dateOption"
          type="datetime"
          placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>
      <span
        class="tips"
        v-if="maxDays === 0">
        暂时无法充值，该会员的截止日期未小于会员类型的截止时间 {{ currentItem.memberType.play_enddate | formatDate }}，请修改会员类型的截至时间
      </span>
      <br>
      <div class="block-title">
        交易信息
      </div>
      <el-form-item
        verify
        prop="total_money"
        label="交易总金额">
        <el-input-number
          :min="0"
          :precision="2"
          controls-position="right"
          v-model="form.total_money">
        </el-input-number>
      </el-form-item>
      <el-form-item
        verify
        prop="payChannel"
        label="付款方式"
        class="is-required">
        <el-select v-model="form.payChannel">
          <el-option
            v-for="item in payChannelOptions"
            :key="item"
            :value="item"
            :label="item"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div class="dialog-btn-wrap">
      <el-button
        @click="submit()"
        type="primary"
        :disabled="submitDisable">
        确定
      </el-button>
    </div>
    <!-- GlobalComponents 全局组件 -->
    <PosQrCodeReader
      ref="posQrCodeReader"
      @getQrcode="goPay"></PosQrCodeReader>
    <XSCQrCodeReader
      ref="XSCQrCodeReader"
      @getQrcode="goPay"></XSCQrCodeReader>
  </div>
</template>

<script>
import { apiMember, getMemberTradeList } from '@/api/member'
import moment from 'moment'
import handlePay, { getPayType } from '@/pages/sellManage/common/handlePay'

export default {
  props: {
    currentItem: {
      type: Object,
      default: () => {}
    },
    submitDisable: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      visible: false,
      maxDays: 100,
      form: {
        member_id: '',
        total_money: 0,
        recharge_times: 0,
        recharge_day_time: 365,
        payChannel: '现金',
        recharge_start_time: ''
      },
      dateOption: {
        disabledDate () {
          return false
        }
      },
      // submitDisable: false,
      payStatus: 0, // 支付状态
      orderTempInfo: {}, // 临时订单信息，防止重复创建订单
      timer: null, // 检查订单是否支付成功计时器
      qrcode: ''
    }
  },
  computed: {
    computed: {
      isPapersIdDesensitize () {
        const value = this.$store.state.app.systemConfig.find(i => i.configKey === 'papers_id_desensitize')?.configValue
        return value === '1'
      }
    },
    newEndDate () {
      if (this.form.recharge_start_time) {
        return moment(this.form.recharge_start_time).add(this.form.recharge_day_time, 'days').format('YYYY-MM-DD')
      } else {
        return moment(this.currentItem.endtime).add(this.form.recharge_day_time, 'days').format('YYYY-MM-DD')
      }
    },
    payChannelOptions () {
      // return this.$store.state.app.payChannelList.filter(i => i.name.indexOf('旅行社') < 0 && i.type === 'NOPAY').map(i => i.name)
      return this.$store.state.app.payChannelOptions.filter(i => i.indexOf('旅行社') < 0)
    },
    scenicName () {
      return this.$localStore.get('scenicName') || this.$store.state.user.scenicName
    },
    showPosQrcode () {
      // 需要手动扫码的景区
      const list = ['东方绿舟', '天津之眼', '绿博园']

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

      return list.indexOf(this.scenicName) > -1
    },
    payType () {
      return getPayType(this.form.payChannel)
    },
    showRefresh () {
      return this.payType === 'B_SCAN_C_PAY' && this.submitDisable
    }
  },
  watch: {
    visible (val) {
      console.log('visible的currentItem.id', this.currentItem.id, this.currentItem.id)
      if (val) {
        this.reset()
        if (this.currentItem) {
          this.form.member_id = this.currentItem.id
          this.maxDays = 0
          if (this.currentItem.memberType.check_pattern === 'time' &&
            moment(this.currentItem.endtime).isBefore(this.currentItem.memberType.play_enddate)) {
            this.maxDays = moment(this.currentItem.memberType.play_enddate).diff(this.currentItem.endtime, 'days')
          }
        }
        let endtime = moment(this.currentItem.endtime).format('YYYY-MM-DD') + ' 00:00:00'
        this.form.recharge_start_time = moment(endtime).add(1, 'd')
        // 设置不可选日期
        this.dateOption.disabledDate = (theTime) => {
          let startTime = moment(this.currentItem.endtime).format('YYYY-MM-DD hh:mm:ss')
          return moment(theTime).isBefore(startTime)
        }
        if (this.payChannelOptions.length) {
          this.form.payChannel = this.payChannelOptions[0]
        }
      } else {
        console.log('清空表单reset')
        this.reset()
      }
    },
    submitDisable (val) {
      if (!val) {
        this.timer && window.clearTimeout(this.timer)
      }
    }
  },
  filters: {
    complicatedCheckType (arr) {
      /* 0: check_pattern,
         1: scenic_checkTimes_type,
         2: valid_days,
         3: checkLimitTimes */
      switch (arr[0]) {
        case 'count':
          switch (arr[1]) {
            case 1:
              return `单人按次 单独限制`
            case 2:
              return `单人按次 批量限制 共可检${arr[3]}次`
            default:
              return ''
          }
        case 'time':
          switch (arr[2]) {
            case -1:
              return `按有效期 截止到票种有效期`
            default:
              return `按有效期 ${arr[2]}天`
          }
        default:
          return ''
      }
    }
  },
  methods: {
    reset () {
      // v-if导致一些prop不能正确清空
      this.form = {
        member_id: '',
        total_money: 0,
        recharge_times: 0,
        recharge_day_time: 365,
        recharge_start_time: '',
        payChannel: '现金'
      }
    },
    // handleClose () {
    //   this.$parent.handleClose()
    // },
    submit () {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.submitDisable) return
          this.$emit('updateBtn', true)

          let params = {
            ...this.form,
            member: {
              ...this.form
            },
            memberTrade: {
              payChannel: this.form.payChannel,
              total_money: this.form.total_money,
              pay_money: this.form.total_money,
              trade_type: 1
            }
          }
          this.params = params
          this.rechargeMember(params)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    rechargeMember (params) {
      this.$emit('updateBtn', true)
      apiMember('rechargeMemberMoney', params).then(res => {
        this.orderTempInfo = res
        this.goPay()
      }).catch(e => {
        this.$emit('updateBtn', false)
      })
    },
    goPay (qrCode) {
      // POS支付是否使用外部扫码
      if (this.payType === 'POS' && this.form.payChannel === '聚合扫码' && !qrCode && this.showPosQrcode) {
        this.$refs.posQrCodeReader.show()
        return
      }

      const scanArr = ['瑞通储值卡']
      // 是否使用外部扫码
      if ((scanArr.indexOf(this.form.payChannel) > -1 || this.payType === 'B_SCAN_C_PAY') && !qrCode) {
        this.$refs.XSCQrCodeReader.show()
        return
      }
      if (qrCode) this.params.qrCode = qrCode
      /*
      handlePay(this.params, this.orderTempInfo, this, () => {})
      */

      handlePay(this.params, this.orderTempInfo, this, () => {
        this.updateBtnHandler()
      })
      if (this.payStatus !== 1) {
        this.getSingleMember(this.orderTempInfo, this.params)
      }
    },
    updateBtnHandler () {
      this.$emit('updateBtn', false)
      setTimeout(() => {
        this.$emit('updateBtn', false)
        console.log('关闭弹窗')
        this.handleClose() // 支付后回调关闭弹窗
      }, 300)
    },
    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.$emit('updateBtn', false)
          */
          this.handleSuccess(params, res)
          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.$emit('updateBtn', false)
        } else {
          this.timer = setTimeout(() => {
            this.getSingleMember(res, params)
          }, 2000)
        }
      })
    },
    handleSuccess (params, res) {
      this.$message.success('充值成功')
      this.$emit('updateBtn', false)
      this.$emit('updateList')
      setTimeout(() => {
        this.handleClose()
      }, 300)
    },
    handleClose () {
      this.timer && window.clearTimeout(this.timer)
      this.$parent.handleClose()
    },
    closeTimer () {
      this.timer && window.clearTimeout(this.timer)
    }
  },
  beforeDestroy () {
    this.$emit('updateBtn', false)
    this.timer && window.clearTimeout(this.timer)
  }
}
</script>

<style lang="scss" scoped>
.finger-pic {
  width: 90px;
  height: 120px;
  background-size: contain;
  background-position: center;
}
.tips{
  color:red;
  white-space:nowrap;
  margin-bottom: 10px;
  margin-left: 20px;
}
</style>
