<template>
  <view class="app">
    <view 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>
    <payCard
      :pay-type="payType"
      :value="displayInfo"
      :coupon-info="selectedCoupon"
      :disabled="overtime"
      :has-pwd="creditPayInfo.hasPwd"
      :pay-text="text"
      :show-coupon="showCoupon"
      :risk-limit="riskLimit"
      @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>
    <pwd-modal
      :modal="pwdModal"
      :error-info="error"
      :amount="
        payType === 2 || !selectedCoupon.faceValueNew
          ? displayInfo.orderAmt
          : (displayInfo.orderAmt - selectedCoupon.faceValueNew).toFixed(2)
      "
      :forget-pwd-jump-url="creditPayInfo.forgetPwdJumpUrl"
      @close="pwdModal = false"
      @submit="getPwd"
    />
    <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.pickupId"
        :list="payCouponList"
        :update="random"
        @select="handleSelectCoupon"
        @selectCouponItem="selectCouponItem"
      />
    </uni-popup>
    <tipModal :value="showGoFaceTip" type="appToFace" @change="changeTipStatus($event, true)" />
    <uni-popup ref="cardPopup">
      <uni-popup-dialog
        type="base"
        content="使用享花卡支付需要您绑定银行卡便于后续的还款哦~"
        message=""
        title=" "
        :duration="2000"
        :before-close="true"
        cancel-txt="切换支付方式"
        confirm-txt="去绑卡"
        @cancel="switchPayType"
        @confirm="openCard"
      />
    </uni-popup>
  </view>
</template>

<script>
import authApi from "@/api/address.api";
import { h5Mixin } from "@/utils/h5Mixin";
import payCard from "@/components/payCard";
import tipModal from "@/components/tip-modal";
import pwdModal from "@/components/pwd-modal";
import couponList from "./components/couponList";
import smsModal from "@/components/sms-modal";
import { uniCountdown } from "@dcloudio/uni-ui";
import { encryptByDESModeEBC } from "@/utils/encrypt";
import { saTrackEvent } from "@/utils/sa";
import { status, codeArr, payTypeE, payTypeText, creditStatus, creditPayStatusType } from "./data";
import { kaFlow } from "@/api/ka.api.js";
import config from "@/config";
import {
  pay,
  prepay,
  sendSms,
  queryPayInfo,
  queryPayStatus,
  getCoupon,
  reissueContract,
  getOrderType
} from "../../api/pay.api.js";
import UniPopup from "@/components/uni-popup/uni-popup.vue";
import uniPopupDialog from "@/components/uni-popup/uni-popup-dialog";
export default {
  components: {
    payCard,
    tipModal,
    pwdModal,
    smsModal,
    uniCountdown,
    couponList,
    UniPopup,
    uniPopupDialog
  },
  mixins: [h5Mixin()],
  provide() {
    return {
      pay: this
    };
  },
  data() {
    return {
      showTip: false,
      payType: null,
      orderInfo: {},
      overtime: false,
      orderNo: "",
      displayInfo: {},
      creditPayInfo: {},
      pwdModal: false,
      smsModal: false,
      flowOrderNo: null,
      error: "",
      forgetPwdJumpUrl: "",
      downModal: true,
      accountS: {
        text: "确认支付",
        fn: this.pay
      },
      openId: "",
      text: "推荐支付方式",
      payCouponList: [],
      selectedCoupon: {},
      showCoupon: false,
      isReady: false,
      showGoFaceTip: false,
      random: "",
      protocolChecked: 0,
      payContractInfo: {
        contractInfos: []
      },
      bindBankCardInfo: {}
    };
  },
  onShow() {
    this.setDatas();
    this.queryPayInfo();
  },
  onLoad({ orderNo, showTip }) {
    if (showTip === "true") {
      // 从h5授信跳转回来的需要提示下载app
      this.tip();
    }
    this.orderNo = orderNo || uni.getStorageSync("orderNo");
    uni.setStorageSync("orderNo", this.orderNo);
    // this.queryPayInfo();
    this.getCouponList(this.orderNo);
  },
  computed: {
    riskLimit() {
      return this.isRiskLimit();
    },
    showProtocol() {
      return (
        this.payContractInfo?.payContractIsSign &&
        this.payType === 1 &&
        this.creditPayInfo.accountStatus === 5
      );
    }
  },
  watch: {
    payType() {
      this.getBtnStatus(this.isRiskLimit());
    }
  },
  methods: {
    // 切换支付方式
    switchPayType() {
      console.log("切换支付方式");
      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["cardPopup"].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["cardPopup"].close();
        return;
      }
    },
    setDatas() {
      if (uni.getStorageSync("channlFlag") === "ka") {
        this.kaFlowState();
      }
      this.openId =
        (this.$store.state.userAuthInfo && this.$store.state.userAuthInfo.openid) ||
        uni.getStorageSync("openid");
      if (!this.openId) {
        this.text = "推荐支付方式：";
      }
    },
    // 是否授信
    async kaFlowState() {
      const [data] = await kaFlow();
      if (data.value) {
        uni.setStorageSync("vccChannel", "159913");
        uni.setStorageSync("sonVccChannel", "");
      }
    },
    isRiskLimit() {
      const { accountStatus, riskManagementAmt } = this.creditPayInfo;
      const { orderAmt } = this.displayInfo;
      if (accountStatus === 5) {
        const coupon = +this.selectedCoupon.faceValueNew || 0;
        return +riskManagementAmt + coupon < +orderAmt;
      } else {
        return false;
      }
    },
    async getCouponList(orderNo) {
      const [data] = await getCoupon({ orderNo: orderNo });
      if (data && data.coupons) {
        this.payCouponList = data.coupons.filter(item => item.couponCategory === 21);
      }
    },
    openCouponModal() {
      saTrackEvent("PD_YXMMACP_UserClickCouponBanner");
      this.random = Math.random();
      this.$refs.commonPopup.open();
    },

    // 选取优惠券
    handleSelectCoupon(selectedCoupon) {
      saTrackEvent("PD_YXMMACP_UserClickCouponPopupWindowComfirmBtn");
      this.selectedCoupon = selectedCoupon.length ? selectedCoupon.pop() : {};
      if (!("faceValueNew" in this.selectedCoupon)) {
        this.selectedCoupon.faceValueNew = this.selectedCoupon.faceValue;
      }
      if (!("limitAmountNew" in this.selectedCoupon)) {
        this.selectedCoupon.limitAmountNew = this.selectedCoupon.limitAmount;
      }
      const status = this.checkStatus(this.creditPayInfo, this.displayInfo);
      if (status) {
        this.displayInfo.creditPayInfo.disabled = true;
        this.payType = 2;
      } else {
        this.displayInfo.creditPayInfo.disabled = false;
      }

      this.getBtnStatus(this.isRiskLimit());
      this.$refs.commonPopup.close();
    },
    //选择支付方式
    changePayType(type) {
      if (this.payType == 6) {
        uni.showToast({ title: "请选择现金券支付！", icon: "none" });
        type = 6;
      }
      this.payType = type;
    },
    getOpenid() {
      // 获取openid
      return new Promise(reslove => {
        uni.login({
          provider: "weixin",
          success: async function(res) {
            const [getData] = await authApi.login({
              code: res.code
            });
            if (getData) {
              reslove(getData.openid);
            } else {
              reslove();
            }
          }
        });
      });
    },
    //预支付
    async pay(params) {
      this.error = "";
      if (!this.openId) {
        this.openId = await this.getOpenid();
      }
      if (
        !this.bindBankCardInfo?.isBindBankCard &&
        this.bindBankCardInfo?.bindBankCardUrl &&
        this.payType == 1
      ) {
        this.$refs["cardPopup"].open();
        return;
      }
      if (this.payType === 1 && !this.creditPayInfo.hasPwd) {
        const url = `${this.creditPayInfo.pwdSetJumpUrl}&vccChannel={vccChannel}`;
        this.goH5(url);
        return;
      }
      const paramsData = {
        ...params,
        orderNo: this.orderNo,
        payMethod: !params ? this.payType : null,
        openId: this.openId,
        payCouponId: this.selectedCoupon.pickupId || "",
        appMiniId: wx.getAccountInfoSync().miniProgram.appId || ""
      };
      const [data, error] = params ? await pay(paramsData) : await prepay(paramsData);
      if (error) {
        if (codeArr.indexOf(error.response.businessCode) < 0) {
          this.payResult("Fail", error.msg);
          return;
        }
        this.error = error.msg;
        return;
      }
      const { creditPayInfo = {}, wxPayInfo, flowOrderNo } = data;
      const creditPayStatus = creditPayInfo.creditPayStatus;
      this.flowOrderNo = flowOrderNo;
      if (!params && this.payType === 2) {
        // 微信支付
        console.log("微信支付");
        this.wxPay(wxPayInfo);
        return;
      }
      if (creditPayStatus === 3) {
        //支付成功；
        this.payResult("Success");
        return;
      }
      if (creditPayStatus === 1 || creditPayStatus === 2) {
        // 密码或者短信鉴权
        this.close();
        this[`${creditPayStatusType[creditPayStatus]}Modal`] = true;
      }
      if (this.payType === 6) {
        !params && this.pay({ flowOrderNo: this.flowOrderNo });
        params && this.payResult("Success");
      }
    },
    async payResult(type, error) {
      if (error && !this.openId) {
        // 测试openId是否存在
        error += "!";
      }
      const finalAmt =
        this.payType === 2 || !this.showCoupon
          ? this.displayInfo.orderAmt || "0.00"
          : (this.displayInfo.orderAmt - (this.selectedCoupon.faceValueNew || 0)).toFixed(2);
      const freeAmount =
        this.payType === 1 && this.showCoupon ? this.selectedCoupon.faceValueNew || "0.00" : "0.00";
      const [res] = await getOrderType(this.orderNo);
      const isHundredGroupOrder = res.hundredGroupOrder || false;
      if (isHundredGroupOrder) {
        // 拼团0元购要返回H5支付结果页
        const token = uni.getStorageSync("token") || "";
        const payStatus = error ? "payFail" : "paySuccess";
        const url = `${config.groupBuyHost}/${payStatus}?vccToken=${token}&amount=${finalAmt}&reason=${error}&orderNo=${this.orderNo}&freeAmount=${freeAmount}&payType=${this.payType}`;
        uni.redirectTo({
          url: `/pages/groupbuy/webview?url=${encodeURIComponent(JSON.stringify(url))}`
        });
        return;
      }
      // 原有逻辑
      uni.redirectTo({
        url: `/pages/pay/pay${type}?amount=${finalAmt}&reason=${error}&orderNo=${this.orderNo}&freeAmount=${freeAmount}&payType=${this.payType}`
      });
    },
    wxPay(params) {
      uni.requestPayment({
        ...params,
        complete: () => {
          this.queryPayStatus();
        }
      });
    },
    close() {
      this.pwdModal = false;
      this.smsModal = false;
    },
    async queryPayInfo() {
      const [data, error] = await queryPayInfo({ orderNo: this.orderNo });
      if (error) return;
      const { displayInfo = {}, payMethods, bindBankCardInfo } = data || {};
      if (displayInfo.payCouponInfo && displayInfo.payCouponInfo.optimalPayCoupon) {
        this.selectedCoupon = displayInfo.payCouponInfo.optimalPayCoupon;
        this.showCoupon = displayInfo.payCouponInfo.optimalType === 3;
      }
      this.payContractInfo = displayInfo.payContractInfo;
      this.bindBankCardInfo = bindBankCardInfo;
      this.isReady = !!payMethods;
      for (const key in displayInfo) {
        const payType = displayInfo[key].payType;
        if (payType) {
          for (const p of payMethods) {
            if (p.isDefault) {
              this.payType = p.method;
            }
            if (p.method === payType) {
              displayInfo[key] = {
                ...displayInfo[key],
                ...p,
                show: true
              };
              break;
            }
          }
        }
        if (key === "creditPayInfo" && this.checkStatus(displayInfo[key], displayInfo)) {
          displayInfo[key].disabled = true;
        }
      }
      if (this.payType === 1 && displayInfo.creditPayInfo.disabled) {
        this.payType = null;
      }
      this.payType &&
        saTrackEvent(payTypeE[this.payType - 1], {
          order_id: this.orderNo
        });
      this.displayInfo = displayInfo || {};
      this.creditPayInfo = displayInfo.creditPayInfo || {};
      // const { accountStatus, riskManagementAmt } = this.creditPayInfo;
      // const { orderAmt } = this.displayInfo;
      // if (accountStatus === 5 && riskManagementAmt && +riskManagementAmt < +orderAmt) {
      //   // 订单金额大于风控返回的可用额度，需引导进行活体认证并展示提示与
      //   this.displayInfo.creditPayInfo.isRiskLimit = true;
      // }
      this.overtime = displayInfo.periodSeconds <= 0;
      this.getBtnStatus(this.isRiskLimit());
    },
    checkStatus({ accountStatus, canAmt }, { orderAmt }) {
      // 开户成功已有额度小于订单额度和审核被拒
      if (!this.selectedCoupon.faceValueNew) {
        return (accountStatus === 5 && +orderAmt > +canAmt) || accountStatus === 3;
      }
      return (
        (accountStatus === 5 && +orderAmt > +canAmt + +this.selectedCoupon.faceValueNew) ||
        accountStatus === 3
      );
    },
    timeup() {
      this.overtime = true;
      this.payType = null;
      this.close();
    },
    async getPwd(e) {
      this.pay({ flowOrderNo: this.flowOrderNo, password: await encryptByDESModeEBC(e) });
    },
    async sendSms(fn) {
      const [, error] = await sendSms({ orderNo: this.orderNo, flowOrderNo: this.flowOrderNo });
      if (!error) {
        fn();
      }
    },
    getSms(e) {
      this.pay({ flowOrderNo: this.flowOrderNo, smsAuthorizationCode: e });
    },
    apply() {
      this.goApply("pay");
    },
    tip() {
      this.showGoFaceTip = true;
    },
    getBtnStatus(isRiskLimit) {
      const { accountStatus } = this.creditPayInfo;
      if (!accountStatus) return;
      if (this.payType === 1) {
        // payType=1--享花卡支付，payType=2微信支付
        if (accountStatus === 4) {
          this.accountS = {
            text: "立即激活",
            fn: this.apply
          };
        } else if (creditStatus.indexOf(accountStatus) > -1) {
          this.accountS = {
            text: "立即开通",
            fn: this.apply
          };
        } else if (isRiskLimit) {
          // 展示限额提示
          this.accountS = {
            text: "认证提额",
            fn: () => {
              this.tip("appToFace");
            }
          };
        } else if (accountStatus === 5) {
          const finalCount = this.showCoupon
            ? (this.displayInfo.orderAmt - (this.selectedCoupon.faceValueNew || 0)).toFixed(2)
            : this.displayInfo.orderAmt;
          const txt = `实际支付${finalCount || "0.00"}`;
          this.accountS = {
            text: txt,
            fn: this.pay
          };
        }
      } else {
        const txt = `确认支付`;
        this.accountS = {
          text: txt,
          fn: this.pay
        };
      }
    },
    async nextAction() {
      try {
        const [res] = await getOrderType(this.orderNo);
        const isHundredGroupOrder = res.hundredGroupOrder || false;
        if (isHundredGroupOrder) {
          saTrackEvent("MINI_CheckOutCounterConfirmPayBtnClick", {
            order_type: "0元购"
          });
        }
      } catch (e) {
        console.log(e);
      }
      saTrackEvent("PD_YXMMACP_UserClickCashierConfirmPaymentBtn", {
        order_id: this.orderNo,
        pay_method: payTypeText[this.payType - 1],
        vcc_state: status[this.creditPayInfo.accountStatus - 1],
        buttons_name: this.accountS.text
      });
      uni.reportAnalytics("c_cashierconfirmpaymentbtn", {
        order_id: this.orderNo,
        pay_method: payTypeText[this.payType - 1],
        vcc_state: status[this.creditPayInfo.accountStatus - 1],
        buttons_name: this.accountS.text
      });
      if (this.showProtocol) {
        if (this.protocolChecked === 1) {
          this.reissueContract();
          this.accountS.fn();
        } else {
          this.$api.msg("请阅读并同意协议");
        }
      } else {
        this.accountS.fn();
      }
    },
    async queryPayStatus() {
      const [{ payStatus }, error] = await queryPayStatus({ orderNo: this.orderNo });
      if (error) {
        this.payResult("Fail", error.msg);
        return;
      }
      if (+payStatus === 3) {
        this.payResult("Success");
      }
    },
    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;
      }
    },
    selectCouponItem(isSelected, couponInfo) {
      saTrackEvent("PD_YXMMACP_UserClickCouponPopupWindowCoupon", {
        check_or_not: isSelected ? "勾选" : "取消",
        coupon_id: couponInfo.pickupId
      });
    },
    changePop(pop) {
      if (pop?.show === false) {
        saTrackEvent("PD_YXMMACP_UserClickCouponPopupWindowCloseBtn");
      }
    },
    confirmProtocol() {
      this.protocolChecked = this.protocolChecked ? 0 : 1;
    },
    viewProtocol(url) {
      uni.redirectTo({
        url: `/pages/webview/webview?url=${encodeURIComponent(JSON.stringify(url))}`
      });
    },
    async reissueContract() {
      await reissueContract({
        templateIdList: this.payContractInfo.contractInfos.map(item => item.contractId)
      });
    }
  }
};
</script>

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