<template>
  <view class="app">
    <!-- 支付倒计时 -->
    <view v-if="getObjectKey(displayInfo).length" class="price-box">
      <text class="price">{{ displayInfo.orderAmt }}</text>
      <view v-if="!overtime" class="time"
        >支付剩余时间：
        <uni-countdown
          :second="displayInfo.periodSeconds"
          :show-day="false"
          class="countdown"
          @timeup="timeup"
        />
      </view>
      <text v-else>支付超时，订单关闭</text>
    </view>
    <!-- 推荐信用支付 -->
    <!-- v-if中&&后为临时隐藏享花卡的需求 -->
    <payCard
      v-if="
        getObjectKey(creditPayList.payList).length &&
          creditStatus.indexOf(creditPayInfo.accountStatus) == -1 &&
          creditPayInfo.hasPwd
      "
      :value="creditPayList"
      :pay-type="payType"
      :disabled="overtime"
      :risk-limit="riskLimit"
      :show-coupon="showCoupon"
      :coupon-info="selectedCoupon"
      :has-pwd="creditPayInfo.hasPwd"
      :display-info="displayInfo"
      :pay-coupon-could-be-used="
        displayInfo.payCouponInfo && displayInfo.payCouponInfo.payCouponCouldBeUsed
      "
      :pay-coupon-list="payCouponList"
      @changePayType="changePayType"
    />
    <!-- 其他支付方式 -->
    <payCard
      v-if="getObjectKey(thirdPayList.payList).length"
      :value="thirdPayList"
      :pay-type="payType"
      :disabled="overtime"
      :show-coupon="showCoupon"
      :coupon-info="selectedCoupon"
      :has-pwd="creditPayInfo.hasPwd"
      :pay-coupon-list="payCouponList"
      :pay-coupon-could-be-used="
        displayInfo && displayInfo.payCouponInfo && displayInfo.payCouponInfo.payCouponCouldBeUsed
      "
      @changePayType="changePayType"
    />
    <label v-if="showProtocol" class="protocol" @click="confirmProtocol">
      <checkbox
        class="protocol__chk"
        :value="protocolChecked"
        color="#EC1500"
        :checked="protocolChecked === 1"
      />
      <view class="protocol__txt">
        勾选同意
        <text
          v-for="(item, index) in payContractInfo.contractInfos"
          :key="index"
          class="protocol__txt-item"
          @click.stop="viewProtocol(item.contractVisitUrl)"
        >
          《{{ item.contractName }}》
        </text>
      </view>
    </label>
    <view v-if="isReady && !overtime" class="btn">
      <button type="primary" class="btn-primary" :disabled="!!!payType" @click="nextAction">
        {{ accountS.text }}
      </button>
    </view>
    <view v-if="overtime" class="btn">
      <button type="default" class="btn-default" @click="goOrderDetail">查看订单</button>
      <button type="primary" class="btn-primary" @click="goHome">返回商城</button>
    </view>
    <view class="placeholder" />
    <!-- 支付密码弹窗 -->
    <!-- :amount="amount" -->
    <pwd-modal
      :modal="pwdModal"
      :error-info="error"
      :forget-pwd-jump-url="creditPayInfo.forgetPwdJumpUrl"
      @close="pwdModal = false"
      @submit="getPwd"
      @setPwd="setPwd"
    />
    <!-- 短信验证弹窗 -->
    <sms-modal
      :modal="smsModal"
      :error-info="error"
      @close="smsModal = false"
      @submit="getSms"
      @send="sendSms"
    />
    <tipModal :value="showTip" scene="pay" type="app" @change="changeTipStatus" />
    <!-- 享花券弹窗 -->
    <uni-popup
      ref="commonPopup"
      type="bottom"
      :closeable="true"
      title="选择优惠券"
      @change="changePop"
    >
      <coupon-list
        ref="couponList"
        :value="selectedCoupon.id"
        :list="payCouponList"
        :update="random"
        @select="handleSelectCoupon"
        @selectCouponItem="selectCouponItem"
      />
    </uni-popup>
    <!-- 提示授信弹窗 -->
    <tipModal :value="showGoFaceTip" type="appToFace" @change="changeTipStatus($event, true)" />
    <uni-popup ref="configPopup">
      <uni-popup-dialog
        type="base"
        :title="configPopup.title"
        :content="configPopup.content"
        :duration="2000"
        :before-close="true"
        :cancel-txt="configPopup.cancelTxt"
        :confirm-txt="configPopup.confirmTxt"
        :hide-cancel-btn="configPopup.hideCancelBtn"
        @cancel="configEvent(configPopup.cancel)"
        @confirm="configEvent(configPopup.confirm)"
      />
    </uni-popup>

    <uni-popup ref="appPay">
      <uni-popup-dialog
        type="base"
        content="支付完成"
        :duration="2000"
        :show-title="false"
        :before-close="true"
        open-type="launchApp"
        cancel-txt="留在微信"
        confirm-txt="返回羊小咩App"
        :hide-cancel-btn="true"
        @confirm="appPayConfirm"
        @cancel="appPayCancel"
      />
    </uni-popup>
    <tougdunCanvas />
    <login-popup ref="login-popup" type="center" :mask-click="false" title="用户授权登录" />
  </view>
</template>

<script>
import { kaFlow } from "@/api/ka.api.js";
import authApi from "@/api/address.api";
import { h5Mixin } from "@/utils/h5Mixin";
import { uniCountdown } from "@dcloudio/uni-ui";
import { encryptByDESModeEBC } from "@/utils/encrypt";
// import { throtte } from "@/utils/index";
import { saTrackEvent } from "@/utils/sa";
import smsModal from "@/components/sms-modal";
import payCard from "@/components/payCard";
import tipModal from "@/components/tip-modal";
import pwdModal from "@/components/pwd-modal";
import UniPopup from "@/components/uni-popup/uni-popup.vue";
import uniPopupDialog from "@/components/uni-popup/uni-popup-dialog";
import couponList from "./components/couponList";
import payMixin from "./payMixin.js";
import { pay, prepay, sendSms, queryPayInfo, queryPayStatus, getCoupon } from "@/api/pay.api.js";
import tougdunCanvas from "@/components/tougdunCanvas.vue";
import {
  codeArr,
  creditStatus,
  creditPayStatusType,
  ACCOUNT_APPLY_FAIL,
  ACCOUNT_APPLY_SUCCESS,
  CREDIT_PAY,
  WECHAT_PAY,
  VIRTUAL_PAY,
  IS_CREDIT_PAY,
  IS_THIRD_PAY,
  IS_GROUP_PAY,
  PAY_SUCCESS,
  PAYMENT_CODE_PAY, // 支付密码
  SMS_VERIFICATION_CODE_PAY, //短信验证码
  CENTER_CODE_PAY, //支付中
  filterAllPayList,
  isDetentionFn
} from "./STATIC_DATA";
import { getFincialData, getSchemaCode } from "@/api/home.api.js";
import loginPopup from "@/components/loginPopup";
export default {
  components: {
    payCard,
    tipModal,
    pwdModal,
    smsModal,
    uniCountdown,
    couponList,
    UniPopup,
    uniPopupDialog,
    tougdunCanvas,
    loginPopup
  },
  mixins: [h5Mixin(), payMixin],
  provide() {
    return {
      pay: this
    };
  },
  data() {
    return {
      queryParams: {},
      needUpdate: false, //回到小程序是否需要刷新页面
      error: "", // 错误信息提示
      random: "", // 刷新优惠卷列表随机数
      openId: "", // 微信唯一标识
      orderNo: "", // 订单号
      text: "推荐支付方式",
      isReady: false, // 是否显示支付按钮
      showTip: false,
      overtime: false, // 支付超时
      pwdModal: false, // 支付密码弹出框
      smsModal: false, // 短信验证码弹窗
      isDetention: false,
      showGoFaceTip: false, // 活体认证弹窗
      showCoupon: false, // 是否显示选择优惠卷
      payCouponList: [], // 优惠卷列表
      selectedCoupon: {}, // 优惠卷相关
      payType: null, // 支付类型
      flowOrderNo: null, // 预支付信息
      protocolChecked: 0, // 是否选择勾选合同同意
      // 合同签署相关
      payContractInfo: {
        contractInfos: []
      },
      bindBankCardInfo: {}, // 是否绑定银行卡信息，flase：没有绑定
      displayInfo: {}, // 支付金额合同等相关信息
      creditPayInfo: {}, // 支付方式，支付类型，描述信息等
      creditQuotaInfo: {}, // 本单信用额度可使用金额
      mergePayPretreatmentInfo: {}, // 组合支付信息
      accountS: {
        text: "确认支付",
        fn: this.pay
      },
      creditPayList: {
        title: "推荐信用支付",
        payList: {}
      },
      thirdPayList: {
        title: "其他支付方式",
        payList: {}
      },
      creditStatus // 临时隐藏享花卡的需求
    };
  },
  onLoad(option) {
    this.queryParams = option;
    const { orderNo, showTip } = option;
    /* #ifndef MP-WEIXIN */
    // 防止百度或支付宝小程序从某种渠道到支付，跳转到新的支付页面
    if (orderNo) {
      uni.redirectTo({ url: `/subPackages/common/pay/index?orderNo=${orderNo}` });
      return;
    }
    /* #endif */

    showTip === "true" && this.tip(); // 从h5授信跳转回来的需要提示下载app
    this.orderNo = orderNo || uni.getStorageSync("orderNo");
    uni.setStorageSync("orderNo", this.orderNo);
    this.init();
  },
  onShow() {
    if (this.needUpdate) {
      this.init();
    }
  },
  computed: {
    // 服务类商品从App跳过来支付
    sceneApp() {
      return this.queryParams.sceneFrom === "app";
    },

    riskLimit() {
      return this.isRiskLimit();
    },
    amount() {
      const faceValueNew = this.selectedCoupon.faceValueNew || 0;
      const orderAmt = this.displayInfo.orderAmt;
      // const canAmt = +this.creditPayInfo?.canAmt || 0;
      if (IS_GROUP_PAY(this.payType)) {
        const orderCanUseAmt = this.creditQuotaInfo?.orderCanUseAmt || 0;
        return (orderCanUseAmt - faceValueNew).toFixed(2);
      }
      return IS_THIRD_PAY(this.payType) || !faceValueNew
        ? orderAmt
        : (orderAmt - faceValueNew).toFixed(2);
    },
    showProtocol() {
      return (
        !IS_THIRD_PAY(this.payType) &&
        this.payContractInfo.payContractIsSign &&
        this.creditPayInfo.accountStatus === ACCOUNT_APPLY_SUCCESS
        // && !this.creditPayInfo.miniFace
      );
    },
    canUseAmount() {
      // （优惠卷面值 + 享花卡可用额度）- 支付总金额orderAmt
      return (
        ((this.selectedCoupon?.faceValueNew && +this.selectedCoupon.faceValueNew) || 0) +
        ((this.displayInfo?.creditPayInfo?.canAmt && +this.displayInfo.creditPayInfo.canAmt) || 0) -
        ((this.displayInfo?.orderAmt && +this.displayInfo.orderAmt) || 0)
      );
    }
  },
  watch: {
    payType() {
      this.getBtnStatus(this.isRiskLimit());
    }
  },
  methods: {
    appPayConfirm() {
      this.goHome();
    },
    appPayCancel() {
      console.log("app-pay----------cancel");
    },
    init() {
      // 如果是从App跳转过来的且未登录则，拦截以下请求
      if (this.initLaunchOpenWechat()) return;
      this.getCouponList(this.orderNo);
      this.setDatas();
      this.queryPayInfo();
    },

    // 通过App打开的小程序
    initLaunchOpenWechat() {
      const token = uni.getStorageSync("token");
      // 如果是App且未登录，跳转登录页
      console.log("是否从App jump服务类商品===================>", this.sceneApp);
      if (this.sceneApp && !token) {
        const launchOptions = uni.getLaunchOptionsSync();
        console.log(`App打开小程序------->场景值:${JSON.stringify(launchOptions)}`);
        /***************** 授权框登录 *********************/
        this.$refs["login-popup"].open();
        this.observeLogin();
        /***************** 授权框登录 *********************/
        return true;
      }
      return false;
    },
    observeLogin() {
      uni.$on("login", userInfo => {
        if (userInfo) {
          this.init();
          uni.$off("login");
        }
      });
    },

    getUserInfo() {
      return {
        userId: uni.getStorageSync("userAuthInfo").userId || "",
        phoneNo: uni.getStorageSync("userAuthInfo").phoneNo || ""
      };
    },
    setPwd() {
      this.jumpToFincialMiniApp("/pages/docking/index?type=RESET_PWS", "", false);
    },
    // 查询支付信息
    async queryPayInfo() {
      const [data, error] = await queryPayInfo({
        orderNo: this.orderNo,
        isUsedMergePayMethod: true // 是否开启组合支付
      });
      if (error && codeArr.indexOf(error?.response?.businessCode) < 0) {
        if (this.sceneApp) return this.$api.msg(error?.msg);
        this.payResult("Fail", error?.msg);
        return;
      }
      const { displayInfo = {}, payMethods, creditQuotaInfo, bindBankCardInfo } = data || {};
      // 有为完成支付的订单
      if (creditQuotaInfo?.isFreezeCreditInOtherOrder) {
        this.openConfigModal("freezeCred"); /* 有享花卡未支付的订单 */
      }
      this.isReady = true;
      this.overtime = displayInfo.periodSeconds <= 0;
      this.creditQuotaInfo = creditQuotaInfo || {};

      if (this.overtime) {
        // 当支付时间归零时
        this.displayInfo.orderAmt = displayInfo.orderAmt;
        return;
      }
      // 是否有优惠卷相关字段
      if (displayInfo.payCouponInfo && displayInfo.payCouponInfo.optimalPayCoupon) {
        this.selectedCoupon = displayInfo.payCouponInfo.optimalPayCoupon;
        this.selectedCoupon.id = this.selectedCoupon.pickupId;
        this.showCoupon = displayInfo.payCouponInfo.optimalType === 3; // 判断是否是最优优惠券
      }
      this.payContractInfo = displayInfo.payContractInfo || {};
      this.bindBankCardInfo = bindBankCardInfo;
      this.filterPayMethods(payMethods, displayInfo); // 过滤数据支付数据，筛选出推荐信用支付，和其他支付方式
      // 如果是信用支付 并且 disabled=true?
      if (this.payType === CREDIT_PAY && displayInfo.creditPayInfo.disabled) {
        this.payType = null;
      }
      this.sendPayTrack(); // 发送埋点
      this.displayInfo = displayInfo || {};
      this.creditPayInfo = displayInfo.creditPayInfo || {}; // 信用支付相关流程
      if (IS_CREDIT_PAY(this.payType) && !this.creditPayInfo.hasPwd) this.payType = 2;
      this.getBtnStatus(this.isRiskLimit());
    },
    isRiskLimit() {
      const { miniFace } = this.creditPayInfo;
      return miniFace;
      // return 是否有额度
      // {accountStatus: 信用支付状态, riskManagementAmt: 风控控制金额},
      // const { accountStatus, riskManagementAmt } = this.creditPayInfo;
      // const { orderAmt } = this.displayInfo;
      // // 信用支付账户状态 === 已开户
      // if (accountStatus === ACCOUNT_APPLY_SUCCESS) {
      //   const coupon = +this.selectedCoupon.faceValueNew || 0; // coupon = 优惠卷面值
      //   return +riskManagementAmt + coupon < +orderAmt;
      // } else {
      //   return false;
      // }
    },
    getBtnStatus(isRiskLimit) {
      const { accountStatus } = this.creditPayInfo; // 信用支付账户状态
      if (!accountStatus) return;
      // payType=1--享花卡支付，payType=2微信支付
      if (IS_CREDIT_PAY(this.payType) && creditStatus.indexOf(accountStatus) > -1) {
        // 临时隐藏享花卡的需求
        this.payType = 2;
        this.accountS = { text: "确认支付", fn: this.pay };
        return;
      }
      if (IS_CREDIT_PAY(this.payType)) {
        if (accountStatus === ACCOUNT_APPLY_FAIL) {
          // this.accountS = { text: "立即激活", fn: this.apply };
          this.accountS = { text: "确认支付", fn: this.pay }; // 临时隐藏享花卡的需求
        } else if (creditStatus.indexOf(accountStatus) > -1) {
          this.accountS = { text: "立即开通", fn: this.apply };
        } else if (isRiskLimit) {
          // this.accountS = {
          //   text: "认证提额",
          //   fn: () => this.jumpToFincialMiniApp("/pages/face/index", "pay")
          // }; // 展示限额提示
          this.payType = 2;
          this.accountS = { text: "确认支付", fn: this.pay }; // 临时隐藏享花卡的需求
        } else if (accountStatus === ACCOUNT_APPLY_SUCCESS) {
          const { orderAmt } = this.displayInfo;
          const { faceValueNew } = this.selectedCoupon;
          const showCoupon = this.showCoupon;
          const finalCount = showCoupon ? (orderAmt - (faceValueNew || 0)).toFixed(2) : orderAmt;
          this.accountS = { text: `实际支付${finalCount || "0.00"}`, fn: this.pay };
        }
      } else {
        if (this.payType === 6) {
          this.accountS = { text: "实际支付0.00", fn: this.pay };
          return;
        }
        this.accountS = { text: "确认支付", fn: this.pay };
      }
    },
    /* 获取优惠券信息 */
    async getCouponList(orderNo) {
      if (this.sceneApp) return;
      const [data] = await getCoupon({ orderNo: orderNo });
      this.payCouponList = [];
      if (data && data.coupons) {
        data.coupons.forEach(item => {
          if (item.couponCategory === 21) {
            this.payCouponList.push({
              ...item,
              id: item.pickupId,
              pickupAble: 1
            });
          }
        });
      }
    },
    async nextAction() {
      // 支付按钮埋点，上报错误等逻辑
      this.sendNextAction();
      if (this.showProtocol) {
        if (this.protocolChecked === 1) {
          this.reissueContract();
          this.accountS.fn();
        } else {
          this.$api.msg("请阅读并同意协议");
        }
        return;
      }
      this.accountS.fn();
    },
    // pay: throtte(async function(params) {
    async pay(params) {
      const tenantId = +uni.getStorageSync("tenantId");
      console.log("params=================>", params);
      if (this.overtime) {
        this.$api.msg("订单已超时！");
        return;
      }
      this.error = "";
      this.setAmount();
      if (!this.openId) {
        this.openId = await this.getOpenid();
      }
      if (!this.creditPayInfo.hasPwd) {
        this.isDetention = true;
      }
      if (
        tenantId === 560761 && // 羊小咩
        !params && // 没有支付传输数据
        !this.isDetention && // 用作拦截开关
        WECHAT_PAY === this.payType && // 是第三方支付
        !this.creditPayInfo.disabled && // 信用支付可选中状态
        this.creditPayInfo.accountStatus !== 3 && // 后两个&&为临时隐藏享花卡的需求
        this.creditPayInfo.accountStatus !== 1 &&
        this.creditPayInfo.accountStatus !== 2 &&
        !this.sceneApp
      ) {
        this.isDetention = true;
        isDetentionFn.call(this);
        return;
      }
      const riskLimitWindowDesc = this.creditPayInfo.riskLimitWindowDesc;
      const orderCanUseAmt = +(this.creditQuotaInfo?.orderCanUseAmt || 0);
      if (!orderCanUseAmt && IS_CREDIT_PAY(this.payType)) {
        this.openConfigModal("canUseAmt", riskLimitWindowDesc);
        return;
      }

      // 享花卡信用支付 且得意小于 额度小于0
      if (this.payType === CREDIT_PAY && this.canUseAmount < 0) {
        this.openConfigModal("insufficient", riskLimitWindowDesc);
        return;
      }

      // 判断没有绑定银行卡 且 有未绑定银行卡时跳转H5的地址 并且选择信用支付
      const { isBindBankCard, bindBankCardUrl } = this.bindBankCardInfo;
      if (!isBindBankCard && bindBankCardUrl && IS_CREDIT_PAY(this.payType)) {
        this.openConfigModal("cardPopup", riskLimitWindowDesc);
        return;
      }

      // 判断是否为信用支付 且 没有设置密码
      if (IS_CREDIT_PAY(this.payType) && !this.creditPayInfo.hasPwd) {
        // this.goH5(`${this.creditPayInfo.pwdSetJumpUrl}&vccChannel={vccChannel}`);
        this.jumpToFincialMiniApp("/pages/docking/index?type=SET_PWS", "pws");
        return;
      }
      this.isDetention = false;
      const paramsData = {
        ...params,
        ocrAuth: {
          isH5: false
        },
        openId: this.openId,
        // openId: "oul_L5F5XNIzzglpzQRjn498vrNk",
        orderNo: this.orderNo,
        payMethod: this.payType,
        payCouponId: this.selectedCoupon.id || "", // 下单使用优惠卷id
        mergePayPretreatmentId: this.mergePayPretreatmentInfo?.mergePayPretreatmentId,
        appMiniId: wx.getAccountInfoSync().miniProgram.appId || ""
      };
      console.log("支付参数============>", paramsData);
      const [data, error] = params ? await pay(paramsData) : await prepay(paramsData);
      if (error) {
        // App支付拦截错误页面
        if (this.sceneApp) {
          return;
        }
        if (error?.response?.businessCode === "3001") {
          return;
        }
        if (codeArr.indexOf(error.response.businessCode) < 0) {
          /* 其他异常原因造成支付失败 */
          this.payResult("Fail", error.msg);
          return;
        }
        error?.msg && this.$api.msg(error?.message);
        this.error = error?.msg;
        return;
      }
      const { creditPayInfo = {}, wxPayInfo, flowOrderNo, method } = data;
      const creditPayStatus = creditPayInfo.creditPayStatus;
      this.flowOrderNo = flowOrderNo;
      if ((!params && this.payType === WECHAT_PAY) || method === WECHAT_PAY) {
        this.close();
        this.wxPay(wxPayInfo);
        return;
      }
      if (creditPayStatus === PAY_SUCCESS) {
        this.close(); //支付成功，关闭密码输入框吗，或短信验证码框
        this.payResult("Success");
        return;
      }
      // creditPayStatus === 1 支付密码， || 2 === 短信验证码
      if (creditPayStatus === PAYMENT_CODE_PAY || creditPayStatus === SMS_VERIFICATION_CODE_PAY) {
        this.close(); // 密码或者短信鉴权
        this[`${creditPayStatusType[creditPayStatus]}Modal`] = true;
        return;
      }
      // 虚拟支付，0元支付
      if (this.payType === VIRTUAL_PAY) {
        if (!params) {
          this.pay({ flowOrderNo: this.flowOrderNo });
          return;
        }
        params && this.payResult("Success");
      }
      // 支付中
      if (creditPayStatus === CENTER_CODE_PAY) {
        this.isPayOrderSuccess();
      }
    },
    payCallback(payParams) {
      this.pay(payParams);
      console.log("回调自己======>", payParams);
    },
    async payResult(type, error) {
      if (error && !this.openId) error += "!"; // 测试openId是否存在
      const payType = this.payType;
      const showCoupon = this.showCoupon;
      const { orderAmt } = this.displayInfo;
      const { faceValueNew } = this.selectedCoupon;
      // eslint-disable-next-line prettier/prettier
      const finalAmt =
        payType === 2 || !showCoupon
          ? orderAmt || "0.00"
          : (orderAmt - (faceValueNew || 0)).toFixed(2);
      let freeAmount = payType === 1 && showCoupon ? faceValueNew || "0.00" : "0.00";
      if (IS_GROUP_PAY(payType)) {
        freeAmount = faceValueNew;
      }
      console.log(`${this.payType}payResult--------------------`);
      // 原有逻辑
      uni.redirectTo({
        url: `/pages/pay/pay${type}?amount=${finalAmt}&reason=${error}&orderNo=${this.orderNo}&freeAmount=${freeAmount}&payType=${this.payType}`
      });
    },
    changePayType(type, mergePayPretreatmentInfo) {
      console.log(type);
      if (this.payType == 6) {
        const title = this.$config("virtualMsg");
        uni.showToast({ title, icon: "none" });
        type = 6;
      }
      this.payType = type;
      this.isDetention = false;
      this.thirdPayList = filterAllPayList(this.payType, this.thirdPayList);
      this.creditPayList = filterAllPayList(this.payType, this.creditPayList);
      this.mergePayPretreatmentInfo = mergePayPretreatmentInfo || null;
    },
    openCouponModal() {
      // payCardItem 组件选择优惠卷之后的回调
      this.random = Math.random();
      this.$refs.commonPopup.open();
      saTrackEvent("PD_YXMMACP_UserClickCouponBanner");
    },
    // 选取优惠券
    handleSelectCoupon(selectedCoupon) {
      saTrackEvent("PD_YXMMACP_UserClickCouponPopupWindowComfirmBtn");
      this.selectedCoupon = selectedCoupon.length ? selectedCoupon.pop() : {};
      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.$refs.commonPopup.close();
    },
    close() {
      this.pwdModal = false;
      this.smsModal = false;
    },
    /* 支付时间超时 */
    timeup() {
      this.overtime = true;
      this.payType = null;
      this.close();
    },
    /* 获取支付密码 */
    async getPwd(e) {
      this.pay({
        flowOrderNo: this.flowOrderNo,
        password: await encryptByDESModeEBC(e)
      });
    },
    /*  短信验证码回调 */
    getSms(e) {
      this.pay({
        flowOrderNo: this.flowOrderNo,
        smsAuthorizationCode: e
      });
    },
    /******************使用享花卡支付需要您绑定银行卡便于后续的还款哦*******************/
    switchPayType() {
      const info = this.displayInfo;
      for (let item in info) {
        const show = info[item].show;
        if (show && info[item].payType !== 1) {
          this.displayInfo.creditPayInfo.disabled = true;
          this.changePayType(info[item].payType);
          this.$refs["configPopup"].close();
          return;
        }
      }
    },
    openCard() {
      if (this.bindBankCardInfo?.bindBankCardUrl) {
        const url = `${this.bindBankCardInfo.bindBankCardUrl}&fromXcxPage=pay`;
        uni.redirectTo({
          url: `/pages/webview/webview?url=${encodeURIComponent(JSON.stringify(url))}`
        });
        this.$refs["configPopup"].close();
        return;
      }
    },
    /******************使用享花卡支付需要您绑定银行卡便于后续的还款哦*******************/
    setDatas() {
      if (uni.getStorageSync("channlFlag") === "ka") this.kaFlowState();
      const { userAuthInfo } = this.$store.state;
      this.openId = (userAuthInfo && userAuthInfo.openid) || uni.getStorageSync("openid");
      if (!this.openId) this.text = "推荐支付方式：";
    },
    // 是否授信
    async kaFlowState() {
      const [data] = await kaFlow();
      if (data.value) {
        /* #ifdef MP-WEIXIN */
        uni.setStorageSync("vccChannel", "159913");
        uni.setStorageSync("sonVccChannel", "");
        /* #endif */
      }
    },
    getObjectKey(obj) {
      return Object.keys(obj);
    },
    getOpenid() {
      return new Promise(reslove => {
        /* #ifdef MP-WEIXIN */
        uni.login({
          provider: "weixin",
          success: async function(res) {
            const [getData] = await authApi.login({ code: res.code });
            getData ? reslove(getData.openid) : reslove();
          }
        });
        /* #endif */
      });
    },
    wxPay(params) {
      if (params) {
        uni.requestPayment({
          ...params,
          complete: res => {
            this.queryPayStatus(res);
          }
        });
        return;
      }
      this.$api.msg("微信支付错误!");
    },
    checkStatus({ accountStatus, canAmt, miniFace }, { orderAmt }) {
      // 开户成功已有额度小于订单额度和审核被拒
      const faceValueNew = this.selectedCoupon.faceValueNew;
      const orderCanUseAmt = this.creditQuotaInfo?.orderCanUseAmt;
      // 风控金额为0的时候享花卡不可选中

      if (+orderCanUseAmt === 0 && miniFace === 0) {
        return true;
      }
      if (!faceValueNew) {
        // （是否是信用支付状态已开户并且 支付总金额是否大于可使用信用额度）或者 信用账户vcc审核失败
        return (accountStatus === 5 && +orderAmt > +canAmt) || accountStatus === 3;
      }
      return (accountStatus === 5 && +orderAmt > +canAmt + +faceValueNew) || accountStatus === 3;
    },
    async sendSms(fn) {
      const [, error] = await sendSms({ orderNo: this.orderNo, flowOrderNo: this.flowOrderNo });
      !error && fn();
    },
    async jumpToFincialMiniApp(path, faceType = "", type = true) {
      const params = {
        orderNo: this.orderNo,
        miniUrl: "/pages/pay/index",
        miniAppId: uni.getAccountInfoSync().miniProgram.appId
      };
      const [schemaCode] = await getSchemaCode(params);
      const [res] = await getFincialData();
      uni.navigateToMiniProgram({
        appId: "wx7c92f8bed76ea778",
        path,
        extraData: {
          fromAPPID: uni.getAccountInfoSync().miniProgram.appId,
          fromPage: "pages/pay/index",
          params: {
            faceType,
            appName: "yxm",
            token: res.token || "",
            bind: res.bind,
            code: res.code || "",
            phoneNo: res.phoneNo || "",
            uuid: res.uuid || "",
            userId: res.userId || "",
            tenantId: uni.getStorageSync("tenantId"),
            channel: res.vccChannel || "",
            schemaCode
          },
          needQuery: ["phoneNo", "token"]
        },
        envVersion: "trial"
      });
      this.needUpdate = type;
    },
    apply() {
      // this.goApply("pay");
      this.jumpToFincialMiniApp("/pages/vccCardBag/index");
    },
    tip() {
      this.showGoFaceTip = true;
    },
    async queryPayStatus(res) {
      // App过来的支付
      if (this.sceneApp) {
        if (res.errMsg === "requestPayment:ok") {
          this.$refs.appPay.open(); // 支付成功弹窗提示返回App
        }
        return;
      }
      // 微信支付之后的回调
      const [{ payStatus }, error] = await queryPayStatus({ orderNo: this.orderNo });
      if (error) {
        this.payResult("Fail", error.msg);
        return;
      }
      if (+payStatus === 3) {
        this.payResult("Success");
        return;
      }
      this.openConfigModal("isPaySuccess");
    },
    goHome() {
      uni.switchTab({
        url: "/pages/index/index"
      });
    },
    goOrderDetail() {
      uni.redirectTo({
        url: `/pages/order/orderDetail?orderNo=${this.orderNo}`
      });
    },
    changeTipStatus(obj, isAppToFace) {
      if (!isAppToFace) {
        this.showTip = obj.show;
      } else {
        this.showGoFaceTip = obj.show;
      }
    },
    confirmProtocol() {
      this.protocolChecked = this.protocolChecked ? 0 : 1;
    },
    setAmount() {
      const faceValue = +this.selectedCoupon?.faceValueNew || 0;
      const orderAmt = +this.displayInfo?.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";
      uni.setStorageSync("amount", { finalAmt, freeAmount });
    }
  }
};
</script>

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