<template>
  <div class="pay">
    <!-- 支付倒计时 -->
    <div v-if="success" class="price-box">
      <p class="price">{{ paymentInfo.orderAmt }}</p>
      <p v-if="!overtime" class="time">
        支付剩余时间：
        <cr-count-down :time="paymentInfo.periodSeconds" @finish="timeup" />
      </p>
      <p v-else>支付超时，订单关闭</p>
    </div>
    <template v-if="!overtime">
      <!-- 推荐信用支付 -->
      <cr-pay-card
        v-if="
          getObjectKey(creditPayList.payList).length ||
            getObjectKey(otherCreditPayList.payList).length
        "
        v-model="creditPayList"
        :pay-type="payType"
        :disabled="overtime"
        :risk-limit="riskLimit"
        :show-coupon="showCoupon"
        :new-comer-promotion-info="newComerPromotionInfo"
        :coupon-info="selectedCoupon"
        :has-pwd="creditPayInfo.hasPwd"
        :other-pays="otherCreditPayList"
        :pay-coupon-could-be-used="
          paymentInfo &&
            paymentInfo.creditPayInfo &&
            paymentInfo.creditPayInfo.payCouponInfo &&
            paymentInfo.creditPayInfo.payCouponInfo.payCouponCouldBeUsed
        "
        @changePayType="changePayType"
      />

      <!-- 其他支付方式 -->
      <cr-pay-card
        v-if="getObjectKey(thirdPayList.payList).length"
        v-model="thirdPayList"
        :pay-type="payType"
        :disabled="overtime"
        :show-coupon="showCoupon"
        :coupon-info="selectedCoupon"
        :has-pwd="creditPayInfo.hasPwd"
        :pay-coupon-could-be-used="
          paymentInfo &&
            paymentInfo.creditPayInfo &&
            paymentInfo.creditPayInfo.payCouponInfo &&
            paymentInfo.creditPayInfo.payCouponInfo.payCouponCouldBeUsed
        "
        @changePayType="changePayType"
      />
    </template>

    <!-- 支付按钮 -->
    <p v-if="isReady && !overtime" class="payBtn">
      <cr-contract
        v-if="isShowProtocol"
        ref="agreement"
        v-model="isCheckAgreement"
        :contract-list="contractList"
      />
      <cr-button type="primary" class="btn-primary" :disabled="!payType" @click="nextAction">
        {{ accountS.text }}
      </cr-button>
    </p>
    <p v-if="overtime" class="btn">
      <cr-button type="default" class="btn-default" @click="goOrderList">我的订单</cr-button>
      <cr-button type="primary" class="btn-primary" @click="goHome">返回商城</cr-button>
    </p>
    <p class="placeholder" />
    <!-- 支付密码弹窗 -->
    <cr-pwd-field
      ref="pwd"
      v-model="pwdModal"
      :amount="amount"
      @getData="getPwd"
      @retrieveLink="retrieveLink"
    />

    <!-- 短信验证弹窗 -->
    <cr-sms-code-modal
      v-model="smsModal"
      :error-info="error"
      :order-no="orderNo"
      :flow-order-no="flowOrderNo"
      @close="smsModal = false"
      @submit="getSms"
    />

    <!-- 享花券弹窗 -->
    <cr-popup v-model="couponPopup" closeable round position="bottom">
      <CouponList
        no-render-disable-tab
        :show-coupon="couponPopup"
        :enable-list="payCouponList"
        :coupon-info="newComerPromotionInfo"
        :value="selectedCoupon.id"
        @toggleNewPerson="toggleNewPerson"
        @change="handleSelectCoupon"
      />
    </cr-popup>
  </div>
</template>

<script>
import crPayCard from './components/PayCard';
import CouponList from './components/CouponList';
import { payByWay } from '@/service/pay.service';
import crContract from './components/Contract.vue';
import crSmsCodeModal from './components/SmsModal';
import { isWechat } from '@/service/validation.service';
import { encryptByDESModeEBC } from '@/service/encrypt.pay';
import localStorage from '@/service/localStorage.service';
import { sStorage } from '@/service/sessionStorage.service';
import { throttle } from '@/service/utils.service';
import { goUrlExtends } from './extends';
import cookies from '@/service/cookieStorage.service';
// let interval = null;
import {
  codeArr,
  CASH_PAY,
  CREDIT_PAY,
  Jinmeixin_CODE_PAY,
  BOE_PAY,
  PAY_SUCCESS,
  creditStatus,
  IS_THIRD_PAY,
  IS_GROUP_PAY,
  IS_CREDIT_PAY,
  isDetentionFn,
  havePayingOrder,
  filterAllPayList,
  PAYMENT_CODE_PAY,
  CASH_PAY_SUCCESS,
  ACCOUNT_APPLY_FAIL,
  creditPayStatusType,
  ACCOUNT_APPLY_SUCCESS,
  SMS_VERIFICATION_CODE_PAY, //短信验证码
  FACE_VERIFICATION_CODE_PAY,
  IS_VCC_PAY,
  CENTER_CODE_PAY,
  sceneSourceKeys
} from './STATIC_DATA';
import {
  pay,
  prepay,
  getCoupon,
  ocrFaceId,
  queryPayInfo,
  kaGetNextUrl,
  reissueContract
} from '@/api/pay.api.js';
const VCC_CHANNEL = localStorage.get('vccChannel');
let Current_Url = null;
export default {
  components: {
    crPayCard,
    crContract,
    crSmsCodeModal,
    CouponList
  },
  provide() {
    return {
      pay: this
    };
  },
  extends: goUrlExtends,
  data() {
    return {
      error: '',
      random: '',
      orderNo: '',
      payInfo: {},
      success: false,
      payType: null,
      isReady: false,
      overtime: false,
      pwdModal: false,
      smsModal: false,
      showCoupon: false,
      flowOrderNo: null,
      couponPopup: false,
      showGoFaceTip: false, // h5支付活体提示怎么处理
      payTypeList: {},
      creditPayList: {
        title: '信用支付',
        payList: {}
      },
      otherCreditPayList: {
        title: '信用支付',
        payList: {}
      },
      thirdPayList: {
        title: '其他支付方式',
        payList: {}
      },
      creditPayInfo: {},
      otherCreditPayInfo: {},
      accountS: {
        text: '确认支付',
        fn: this.pay
      },
      payCouponList: [],
      newComerPromotionInfo: {},
      isDetention: false,
      selectedCoupon: {},
      payContractInfo: {},
      isCheckAgreement: false,
      mergePayPretreatmentInfo: {},
      tradeType: isWechat ? 'JSAPI' : 'MWEB',
      paymentInfo: {},
      payMethods: {},
      installmentInfo: null,
      selectNewPerson: false, // 是否选中VCC新人券
      contractList: [] // 合同列表
    };
  },
  computed: {
    riskLimit() {
      return this.isRiskLimit();
    },
    amount() {
      const faceValueNew = this.selectedCoupon.faceValueNew || 0;
      const orderAmt = this.paymentInfo.orderAmt;
      const vccNewPersonAmt = this.selectNewPerson ? +this.newComerPromotionInfo.amount : 0;
      if (IS_GROUP_PAY(this.payType)) {
        const orderCanUseAmt = this.paymentInfo?.creditPayInfo?.orderCanUseAmt || 0;
        return (orderCanUseAmt - faceValueNew - vccNewPersonAmt).toFixed(2);
      } else if (IS_VCC_PAY(this.payType)) {
        return (orderAmt - faceValueNew - vccNewPersonAmt).toFixed(2);
      }
      return IS_THIRD_PAY(this.payType) || !faceValueNew
        ? orderAmt
        : (orderAmt - faceValueNew).toFixed(2);
    },
    isShowProtocol() {
      return (
        IS_VCC_PAY(this.payType) &&
        this.payContractInfo.payContractIsSign &&
        this.creditPayInfo.accountStatus === ACCOUNT_APPLY_SUCCESS
      );
    }
  },
  watch: {
    payType() {
      this.getBtnStatus(this.isRiskLimit());
    }
  },
  beforeDestroy() {
    // clearInterval(interval);
    localStorage.remove('tdOrderInfo');
  },
  mounted() {
    this.orderNo = this.$route.query.orderNo || cookies.get('orderNo')?.orderNo;
    cookies.set('orderNo', { orderNo: this.orderNo });
    if (this.$route?.query?.ocrflag) {
      this.payInfo = cookies.get('info') || {};
      console.log(this.payInfo);
      cookies.remove('ocrflag');
      cookies.remove('info');
      // 先支付再查询信息
      this.pay(this.payInfo?.paramsData, 'ocr', cookies.get('ocrflag'));
    }
    !this.$route?.query?.ocrflag && this.$track?.registeredEvents('h5_CheckOutCouterExposure');
    const vccToken = localStorage.get('vccToken');
    Current_Url = `${window.location.origin}/payWaiting?vccToken=${vccToken}&orderNo=${this.orderNo}`;
    this.queryPayInfo();
    this.getCouponList(this.orderNo);
    setInterval(() => {
      this.getPayStatus();
    }, 10000);

    // 支付结果页 - 场景值
    const sceneSource = this.$route.query.sceneSource || 'normal';
    sStorage.setItem('sceneSource', sceneSourceKeys[sceneSource]);
    console.log('sStorage.getItem(sceneSource) :>> ', sStorage.getItem('sceneSource'));
    this.$track.registeredEvents('H5_2B_CashierPageExposure');
  },
  methods: {
    changeDefaultPayMethod(payMethods) {
      const isDefaultBoE = payMethods.some(item => item.method === BOE_PAY && item.isDefault);
      let isSet = false;
      if (isDefaultBoE) {
        for (let i = 0; i < payMethods.length; i++) {
          if (!isSet && IS_THIRD_PAY(payMethods[i].method)) {
            payMethods[i].isDefault = true;
            isSet = true;
          } else if (payMethods[i].method === BOE_PAY) {
            payMethods[i].isDefault = false;
          }
        }
      }
    },
    /* 查询支付信息 */
    async queryPayInfo() {
      const [data, error] = await queryPayInfo({
        orderNo: this.orderNo,
        isUsedMergePayMethod: true
      });
      // const data = CheckOutRes;
      // const error = undefined;
      if (error?.response.msg === '订单已支付成功') {
        this.payResult('Success');
      }
      if (error && codeArr.indexOf(error?.response?.businessCode) < 0) {
        return;
      }
      this.isReady = true;
      const { payMethods, creditPayInfo = {} } = data || {};
      this.paymentInfo = data || {};
      // 如果使用渤e贷 则删掉该行代码
      this.changeDefaultPayMethod(payMethods);

      this.payMethods = payMethods;
      this.success = true;
      if (data.periodSeconds > 0) {
        data.periodSeconds = data.periodSeconds * 1000;
      } else {
        this.overtime = true;
        return;
      }
      if (creditPayInfo.payCouponInfo && creditPayInfo.payCouponInfo.optimalPayCoupon) {
        this.selectedCoupon = creditPayInfo.payCouponInfo.optimalPayCoupon;
        this.selectedCoupon.id = this.selectedCoupon.pickupId;
        this.showCoupon = creditPayInfo.payCouponInfo.optimalType === 3;
      }
      // VCC新人券
      if (creditPayInfo.payCouponInfo && creditPayInfo.payCouponInfo.newComerPromotionInfo) {
        creditPayInfo.payCouponInfo.newComerPromotionInfo.checked = true;
        this.newComerPromotionInfo = creditPayInfo.payCouponInfo.newComerPromotionInfo || {};
        this.showCoupon = true;
        this.selectNewPerson = true;
      }
      // VCC 合同
      this.payContractInfo = creditPayInfo.payContractInfo || {};
      if (
        this.payContractInfo &&
        this.payContractInfo.contractInfos &&
        this.payContractInfo.contractInfos.length
      ) {
        this.contractList = this.payContractInfo.contractInfos;
      }
      for (const p of this.payMethods) {
        // 默认支付方式
        if (p.isDefault) {
          this.payType = p.method;
        }
        for (const key in this.paymentInfo) {
          const payType = this.paymentInfo[key].payMethod;
          if (!payType) {
            continue;
          }
          /* 三方支付 */
          if (IS_THIRD_PAY(p.method) && p.method === payType) {
            this.$set(this.thirdPayList.payList, key, {
              ...this.paymentInfo[key],
              ...p,
              show: true,
              isCheck: p.isDefault || false
            });
            break;
          }
          // 分期默认选中第一个
          if (this.paymentInfo[key].installmentInfo?.detailList?.length) {
            this.paymentInfo[key].installmentInfo.detailList[0].checked = true;
          }
          /* 推荐信用支付 */
          if (
            IS_VCC_PAY(p.method) &&
            (p.method === payType || (p.method > 3 && p.method - 2 === payType))
          ) {
            this.creditPayList.isGroupPay = IS_GROUP_PAY(p.method);
            if (p.isDefault) {
              this.mergePayPretreatmentInfo = p.mergePayPretreatmentInfo;
            }
            if (this.paymentInfo[key].accountDesc && !this.paymentInfo[key].accountStatusDesc) {
              this.paymentInfo[key].accountStatusDesc = this.paymentInfo[key].accountDesc;
            }
            this.$set(this.creditPayList.payList, key, {
              ...this.paymentInfo[key],
              ...p,
              show: true,
              payType: p.method,
              isCheck: p.isDefault || false,
              isGroupPay: IS_GROUP_PAY(p.method)
            });
            if (!('creditPayInfo' in this.creditPayList.payList)) {
              this.$set(this.creditPayList.payList, 'creditPayInfo', {
                ...this.paymentInfo['creditPayInfo'],
                show: true,
                isCheck: false
              });
            }
          }
          // 隐藏渤e贷
          // else if (BOE_PAY === payType) {
          //   /* 其它信用支付 */
          //   this.otherCreditPayList.isGroupPay = false;
          //   if (this.paymentInfo[key].accountDesc && !this.paymentInfo[key].accountStatusDesc) {
          //     this.paymentInfo[key].accountStatusDesc = this.paymentInfo[key].accountDesc;
          //   }
          //   this.$set(this.otherCreditPayList.payList, key, {
          //     ...this.paymentInfo[key],
          //     ...p,
          //     show: true,
          //     payType: payType,
          //     isCheck: p.isDefault || false,
          //     isGroupPay: false
          //   });
          // }
        }
      }

      if (this.payType === CREDIT_PAY && creditPayInfo.disabled) {
        this.payType = null;
      }
      this.creditPayInfo = this.paymentInfo.creditPayInfo || {};
      this.otherCreditPayInfo = this.paymentInfo.boECreditPayInfo || {};
      this.getBtnStatus(this.isRiskLimit());
      if (this.payInfo?.payType) {
        this.selectedCoupon = this.payInfo.selectedCoupon;
        this.changePayType(this.payInfo.payType, this.payInfo.mergePayPretreatmentInfo, true);
        this.isShowProtocol && (this.isCheckAgreement = true);
        this.setAmount();
      } else {
        this.changePayType(this.payType, this.mergePayPretreatmentInfo, true);
      }
      if (
        this.paymentInfo?.creditPayInfo?.isFreezeCreditInOtherOrder &&
        !this.payInfo?.payType &&
        IS_VCC_PAY(this.payType)
      ) {
        havePayingOrder.call(this);
      }
    },
    isRiskLimit() {
      const { accountStatus, riskManagementAmt } = this.creditPayInfo;
      const { orderAmt } = this.paymentInfo;
      if (accountStatus === ACCOUNT_APPLY_SUCCESS) {
        const coupon = +this.selectedCoupon.faceValueNew || 0;
        return +riskManagementAmt + coupon < +orderAmt;
      } else {
        return false;
      }
    },
    getBtnStatus(isRiskLimit) {
      const { accountStatus } = this.creditPayInfo;
      if (!accountStatus) return;
      if (IS_CREDIT_PAY(this.payType)) {
        // payType=1--享花卡支付，payType=2微信支付
        if (accountStatus === ACCOUNT_APPLY_FAIL) {
          this.accountS = {
            text: '立即激活',
            fn: this.goApply
          };
        } else if (creditStatus.indexOf(accountStatus) > -1) {
          this.accountS = {
            text: '立即开通',
            fn: this.goApply
          };
        } else if (isRiskLimit) {
          // 展示限额提示
          this.accountS = {
            text: '认证提额',
            fn: this.goOcr
          };
        } else if (accountStatus === ACCOUNT_APPLY_SUCCESS) {
          const faceValueNew = this.selectedCoupon.faceValueNew || 0;
          const vccNewPersonAmt = this.selectNewPerson ? +this.newComerPromotionInfo.amount : 0;
          const finalCount = (this.paymentInfo.orderAmt - faceValueNew - vccNewPersonAmt).toFixed(
            2
          );
          const txt = `实际支付${finalCount || '0.00'}`;
          this.accountS = {
            text: txt,
            fn: this.pay
          };
        }
      } else {
        const txt = `确认支付`;
        this.accountS = {
          text: txt,
          fn: this.pay
        };
      }
    },
    /* 获取优惠券信息 */
    async getCouponList(orderNo) {
      const [data] = await getCoupon({ orderNo: orderNo });
      if (!data) {
        return;
      }
      this.payCouponList = [];
      if (data.coupons) {
        data.coupons.forEach(item => {
          // 享花券
          if (item.couponCategory === 21) {
            this.payCouponList.push({
              ...item,
              id: item.pickupId,
              pickupAble: 1
            });
          }
        });
      }
    },
    getUserInfo() {
      const { userId } = localStorage.get('userInfo') || {};
      return {
        userId,
        phoneNo: localStorage.get('userPhoneNo') + '' || ''
      };
    },
    nextAction: throttle(function() {
      const trackParams = {
        order_id: this.orderNo,
        pay_method: this.payType,
        vcc_state: !IS_THIRD_PAY(this.payType) ? this.creditPayInfo?.accountStatus : '',
        buttons_name: this.accountS.text
      };
      cookies.set('payTrackInfo', trackParams);
      this.$track?.registeredEvents('h5_CheckOutCounterConfirmPayClick', trackParams);
      this.$track?.registeredEvents('H5_2BCashierPageConfirmPaymentBtnClick', trackParams);
      if (this.isShowProtocol) {
        if (!this.isCheckAgreement) {
          this.$toast('请仔细阅读并同意相关协议');
          return;
        }
        this.reissueContract();
      }
      this.accountS.fn();
    }, 1000),
    /* 预支付 */
    async pay(params, isOcr) {
      // 组合支付的提示和享花卡支付逻辑
      if (this.overtime) {
        this.$toast('订单已超时！');
        return;
      }
      this.error = '';
      this.setAmount();
      if (
        !params &&
        !this.isDetention &&
        IS_THIRD_PAY(this.payType) &&
        this.payType !== CASH_PAY &&
        !isOcr &&
        this.$config.xincheng
      ) {
        this.isDetention = true;
        isDetentionFn.call(this);
        return;
      }
      this.isDetention = false;
      /* 享花卡设置密码 */
      if (IS_CREDIT_PAY(this.payType) && this.payType !== BOE_PAY && !this.creditPayInfo.hasPwd) {
        this.retrieveLink();
        return;
      }
      // 验证状态并弹提示
      const statusRes = await this.onCheckStatusAndTrip();
      if (!statusRes) {
        return;
      }
      const paramsData = {
        ...params,
        quitUrl: Current_Url,
        returnUrl: Current_Url,
        ocrAuth: {
          isH5: true
        },
        orderNo: this.orderNo,
        payMethod: this.payType,
        payCouponId: this.selectedCoupon.id || '',
        newComersPromotionId: (this.selectNewPerson && this.newComerPromotionInfo?.id) || '',
        mergePayPretreatmentId: this.mergePayPretreatmentInfo?.mergePayPretreatmentId
      };
      // 信用支付选择分期
      if (IS_CREDIT_PAY(this.payType) && this.installmentInfo) {
        paramsData.rate = this.installmentInfo.rate;
        paramsData.term = this.installmentInfo.term;
      }
      const [data, error] = params
        ? isOcr
          ? await pay(params)
          : await pay(paramsData)
        : await prepay(paramsData);
      /* 支付失败 */
      if (error) {
        if (error?.response?.businessCode === '3001') {
          /* 有享花卡未支付的订单 */
          havePayingOrder.call(this);
          return;
        }
        if (codeArr.indexOf(error?.response?.businessCode) < 0) {
          // this.payResult('Fail', error.message);
          return;
        }
        error?.message && this.$toast(error?.message);
        this.error = error?.message;
        this.pwdModal && this.retrieve();
        return;
      }
      // TODO 此处在获取与支付信息后，，跳转前通过判断渠道号，来判断是否在app中的打开，来规避支付等待页中的schema跳转问题
      if (localStorage.get('vccChannel')) localStorage.set('isAppInner', true);
      const {
        creditPayInfo = {},
        wxPayInfo = {},
        flowOrderNo,
        aliPayInfo = {},
        vmPayInfo = {},
        boECreditPayInfo = {},
        tips = {}
      } = data;
      const creditPayStatus = creditPayInfo.creditPayStatus;
      this.flowOrderNo = flowOrderNo;
      if (wxPayInfo.mwebUrl) {
        /* 微信支付 */
        payByWay(this.tradeType, { ...wxPayInfo, url: wxPayInfo.mwebUrl }, this.$config.yxm);
        return;
      } else if (aliPayInfo.order_string) {
        /* 支付宝支付 */
        window.sessionStorage.setItem('aliOrderString', aliPayInfo.order_string);
        this.$router.replace({
          name: 'payWaitingAli',
          query: { orderNo: this.orderNo }
        });
        // payByWay('ALIWEB', { ...aliPayInfo, url: aliPayInfo.order_string});
        return;
      } else if (creditPayStatus === PAY_SUCCESS) {
        /*  信用支付成功 */
        this.close();
        this.payResult('Success');
        return;
      } else if (creditPayStatus === Jinmeixin_CODE_PAY) {
        // 金美信引导
        this.checkJinmeixinStatus(tips);
      } else if (
        creditPayStatus === PAYMENT_CODE_PAY ||
        creditPayStatus === SMS_VERIFICATION_CODE_PAY
      ) {
        /* 密码或者短信鉴权 */
        this.close();
        this[`${creditPayStatusType[creditPayStatus]}Modal`] = true;
        return;
      } else if (creditPayStatus === FACE_VERIFICATION_CODE_PAY) {
        /* 人脸鉴权 */
        cookies.set('info', {
          paramsData: {
            flowOrderNo: this.flowOrderNo,
            ...paramsData
          },
          payType: this.payType,
          selectedCoupon: this.selectedCoupon,
          isCheckAgreement: this.isCheckAgreement,
          mergePayPretreatmentInfo: this.mergePayPretreatmentInfo
        });
        this.close();
        this.goOcr();
      } else if (vmPayInfo?.vmPayStatus === CASH_PAY_SUCCESS) {
        !params && this.pay({ flowOrderNo: this.flowOrderNo });
        params && this.payResult('Success');
      } else if (creditPayStatus === CENTER_CODE_PAY) {
        this.payResult('Waiting');
      } else if (boECreditPayInfo.url) {
        window.location.href = boECreditPayInfo.url;
      }
    },
    payResult(type, error) {
      /* 跳转支付结果页面 */
      this.$router.replace({
        name: `pay${type}`,
        query: {
          reason: error,
          orderNo: this.orderNo,
          payType: this.payType
        }
      });
    },
    /* 选择支付方式 */
    changePayType(type, mergePayPretreatmentInfo, isFirst) {
      if (this.payType === CASH_PAY && !isFirst) {
        this.$toast(this.$config.payTip);
        type = CASH_PAY;
      }
      this.payType = type;
      this.isDetention = false;
      this.thirdPayList = filterAllPayList(type, this.thirdPayList);
      this.creditPayList = filterAllPayList(type, this.creditPayList);
      this.otherCreditPayList = filterAllPayList(type, this.otherCreditPayList);
      for (let key in this.creditPayList.payList) {
        if (this.creditPayList.payList[key].isCheck) {
          this.creditPayInfo = this.creditPayList.payList['creditPayInfo'];
        }
      }
      for (let key in this.otherCreditPayList.payList) {
        if (this.otherCreditPayList.payList[key].isCheck) {
          this.otherCreditPayInfo = this.otherCreditPayList.payList[key];
        }
      }
      this.mergePayPretreatmentInfo = mergePayPretreatmentInfo || null;
      if (IS_CREDIT_PAY(type)) {
        this.changeInstallment(0, type);
      } else {
        this.installmentInfo = null;
      }
    },
    /* 选择分期 */
    changeInstallment(i, type) {
      let method = IS_VCC_PAY(type) ? 1 : type;
      let payList = this.creditPayList.payList;
      if (!IS_VCC_PAY(type)) {
        method = type;
        payList = this.otherCreditPayList.payList;
        this.otherCreditPayList.payList = {};
      } else {
        this.creditPayList.payList = {};
      }
      this.installmentInfo = null;
      for (let key in payList) {
        if (
          payList[key]?.payMethod === method &&
          payList[key]?.installmentInfo?.detailList?.length
        ) {
          payList[key].installmentInfo.detailList.forEach((item, index) => {
            item.checked = i === index;
            if (i === index) {
              this.installmentInfo = item;
            }
          });
        }
      }
      this.$nextTick(() => {
        if (IS_VCC_PAY(type)) {
          this.creditPayList.payList = payList;
          if (
            this.payContractInfo &&
            this.payContractInfo.contractInfos &&
            this.payContractInfo.contractInfos.length
          ) {
            if (
              i > 0 &&
              this.payContractInfo.installmentContractList &&
              this.payContractInfo.installmentContractList.length
            ) {
              this.contractList = [
                ...this.payContractInfo.contractInfos,
                ...this.payContractInfo.installmentContractList
              ];
            } else {
              this.contractList = this.payContractInfo.contractInfos;
            }
          }
        } else {
          this.otherCreditPayList.payList = payList;
        }
      });
    },
    openCouponModal() {
      this.random = Math.random();
      this.couponPopup = true;
      this.$track?.registeredEvents('h5_CheckOutCouterCouponBannerClick');
    },
    /* 选择VCC新人券 */
    toggleNewPerson(e) {
      this.selectNewPerson = e;
    },
    /* 选取优惠券 */
    handleSelectCoupon(id, selectedCoupon) {
      this.$track?.registeredEvents('h5_CheckOutCounterCouponPopupWindowClick', {
        coupon_type: '享花券',
        check_or_not: id ? '勾选' : '取消',
        coupon_id: id
      });
      this.selectedCoupon = selectedCoupon || {};
      if (!('faceValueNew' in this.selectedCoupon) && 'faceValue' in this.selectedCoupon) {
        this.selectedCoupon.faceValueNew = this.selectedCoupon.faceValue;
      }
      if (!('limitAmountNew' in this.selectedCoupon) && 'limitAmount' in this.selectedCoupon) {
        this.selectedCoupon.limitAmountNew = this.selectedCoupon.limitAmount;
      }
      this.getBtnStatus(this.isRiskLimit());
      this.couponPopup = false;
    },
    close() {
      this.pwdModal = false;
      this.smsModal = false;
    },
    /* 支付时间超时 */
    timeup() {
      this.overtime = true;
      this.close();
    },
    /* 获取支付密码 */
    async getPwd({ pwd }) {
      this.retrieve();
      this.pay({ flowOrderNo: this.flowOrderNo, password: await encryptByDESModeEBC(pwd) });
    },
    /*  短信验证码回调 */
    getSms(e) {
      this.pay({ flowOrderNo: this.flowOrderNo, smsAuthorizationCode: e });
    },
    /* 进入h5授信流程 */
    async goApply() {
      if (this.creditPayInfo.openH5Url) {
        const nextUrl = this.creditPayInfo.openH5Url
          .replace('{token}', localStorage.get('vccToken'))
          .replace('{registerFrom}', VCC_CHANNEL);
        window.location.href = nextUrl;
      } else {
        const [{ nextUrl }] = await kaGetNextUrl();
        if (!nextUrl) return;
        window.location.href = `${nextUrl}&returnUrl=${window.location.origin}/pay&from=pay`;
      }
    },
    /* 走h5活体流程 */
    async goOcr() {
      const [res] = await ocrFaceId({
        isH5: true,
        type: 'xyqb',
        orderNo: this.orderNo,
        flowOrderNo: this.flowOrderNo,
        callBackUrl: encodeURIComponent(`${window.location.href}&ocrflag=1`)
      });
      if (!res.callBackUrl) return;
      window.location.href = res.callBackUrl;
    },
    /* 密码支付失败 */
    retrieve() {
      this.$refs.pwd.tips(false, this.error);
    },
    /* 忘记密码 */
    retrieveLink() {
      let url = `${this.creditPayInfo.forgetPwdJumpUrl}&vccChannel=${VCC_CHANNEL}&redirectUrl=${window.location.href}`;
      url = url.replace('{token}', localStorage.get('vccToken'));
      window.location.href = url;
    },
    getObjectKey(obj) {
      return Object.keys(obj);
    },
    setAmount() {
      const faceValue = +this.selectedCoupon?.faceValueNew || 0;
      const orderAmt = +this.paymentInfo?.orderAmt || 0;
      const finalAmt =
        IS_THIRD_PAY(this.payType) || !this.showCoupon
          ? orderAmt || '0.00'
          : (orderAmt - faceValue || 0).toFixed(2);
      const freeAmount =
        !IS_THIRD_PAY(this.payType) && this.showCoupon ? faceValue || '0.00' : '0.00';
      cookies.set('amount', { finalAmt, freeAmount });
    },
    async reissueContract() {
      const templateIdList = this.contractList.map(item => item.contractId);
      await reissueContract({
        templateIdList
      });
    },

    async getPayStatus() {
      if (localStorage.get('inPay')) {
        localStorage.remove('inPay');
        setTimeout(() => {
          this.$router.replace({
            name: 'payWaiting',
            query: { orderNo: this.orderNo }
          });
        }, 500);
      }
    }
  }
};
</script>

<style lang="less">
@import './index';
</style>
