<template>
  <view class="pay">
    <view class="pay__time">
      <text class="pay__time__price" @click="openPopupEvent(1)">{{ orderAmt }}</text>
      <view v-if="overTime" class="pay__time__hour">
        支付剩余时间：
        <uni-countdown
          class="countdown"
          :second="displayInfo.periodSeconds"
          :show-day="false"
          @timeup="timeupOut"
        />
      </view>
      <text v-else @click="openPopupEvent(2)">支付超时，订单关闭</text>
    </view>

    <payGroupCard
      v-if="objectIsEmpy(creditPayList)"
      v-model="creditPayList"
      title="推荐信用支付"
      @changePayType="changePayType"
    />

    <payCard
      v-if="objectIsEmpy(thirdPayList)"
      v-model="thirdPayList"
      title="其他支付方式"
      @changePayType="changePayType"
    />
    <view class="pay__button" @click="openPopupEvent(3)">
      <button
        v-for="(btnItem, btnIndex) in buttonList"
        :key="btnIndex"
        :type="btnItem.type"
        :class="btnItem.className"
        :loading="isPaying"
        @click="onButtonClick(btnItem)"
      >
        {{ btnItem.name }}
      </button>
    </view>
    <view class="placeholder" />
    <uni-popup ref="configPopup">
      <uni-popup-dialog
        type="base"
        :title="popupConfig.title"
        :show-title="Boolean(popupConfig.title)"
        :content="popupConfig.content"
        :duration="popupConfig.duration"
        :before-close="popupConfig.beforeClose"
        :cancel-txt="popupConfig.cancelTxt"
        :confirm-txt="popupConfig.confirmTxt"
        :hide-cancel-btn="popupConfig.hideCancelBtn"
        @cancel="popupCancelEvent"
        @confirm="popupConfirmEvent"
      />
    </uni-popup>
    <tougdunCanvas />
  </view>
</template>

<script>
import authApi from "@/api/address.api";
import { uniCountdown } from "@dcloudio/uni-ui";
import { saTrackEvent } from "@/utils/sa";
import tougdunCanvas from "@/components/tougdunCanvas.vue";
import { param, debounce } from "@/utils/index";
import { queryPayInfo, prepay, queryPayStatus } from "@/api/pay.api.js";
import { codeArr } from "@/pages/pay/STATIC_DATA.js";
import * as cfg from "./config";
import { paymentConfig, mpConfig } from "@/utils/mpConfig/types";
import UniPopup from "@/components/uni-popup/uni-popup.vue";
import uniPopupDialog from "@/components/uni-popup/uni-popup-dialog";
import payCard from "./components/payCard.vue";
import payGroupCard from "./components/payGroupCard.vue";
const DATA = {
  payMethods: [
    {
      isRecommend: false,
      isDefault: false,
      method: 1
    },
    {
      isRecommend: false,
      isDefault: false,
      method: 2
    },
    {
      isRecommend: false,
      isDefault: true,
      method: 4
    },
    {
      isRecommend: false,
      isDefault: false,
      method: 7
    }
  ],
  bindBankCardInfo: {
    bindBankDesc: "检测到您享花卡未绑定银行卡, 请您先绑定银行卡再使用吧~",
    isBindBankCard: false
  },
  orderNo: "1523909359669637120",
  creditQuotaInfo: {
    isFreezeCreditInOtherOrder: false,
    orderCanUseAmt: "0"
  },
  displayInfo: {
    bdPayInfo: {
      isRecommend: false,
      payType: 7,
      icon: "https://kdspstatic.q-gp.com/kdsp/pay-service/vm-pay-icon2x.png",
      name: "百度支付",
      priority: "3"
    },
    vmPayInfo: {
      isRecommend: false,
      payType: 6,
      icon: "https://kdspstatic.q-gp.com/kdsp/pay-service/vm-pay-icon2x.png",
      name: "现金券支付",
      priority: "3"
    },
    payCouponInfo: {
      optimalType: 1,
      payCouponCouldBeUsed: true
    },
    wxPayInfo: {
      isRecommend: false,
      payType: 2,
      icon: "https://talos-image.xyqb.com/vcc/xyqb/pay-page/wechat_pay.png",
      name: "微信支付",
      priority: "1"
    },
    periodSeconds: 0,
    aliPayInfo: {
      isRecommend: false,
      payType: 3,
      icon: "https://kdspstatic.q-gp.com/alipay.png",
      name: "支付宝支付",
      priority: "2"
    },
    orderAmt: "25.90",
    creditPayInfo: {
      pwdSetJumpUrl:
        "https://mall-test.tjzimu.com/smsCode?phoneNo=13031115726&vccToken={token}&type=0",
      isRecommend: false,
      canAmt: "0.00",
      riskManagementAmt: "0",
      accountStatusDesc: "您有消费额度待领取，最高40天购物免息",
      forgetPwdJumpUrl:
        "https://mall-test.tjzimu.com/smsCode?phoneNo=13031115726&vccToken={token}&type=0",
      hasPwd: false,
      icon: "https://talos-image.xyqb.com/vcc/xyqb/pay-page/credit_pay%403x.png",
      isExistMergePay: false,
      priority: "0",
      tagName: "最高享40天免息",
      accountStatus: 1,
      creditPayOpenDesc: "您有一笔免费额度可以使用，40天免息等你拿！",
      payType: 1,
      totalAmt: "",
      riskManagementDesc:
        "因风险原因，本笔订单最高可用额度为0元，您可先完成本人活体认证后释放剩余额度",
      name: "享花卡支付",
      miniFace: 1
    },
    payContractInfo: {
      payContractIsSign: false
    },
    installmentInfo: {
      cancelInterestExplainImgUrl: "https://activitystatic.lkbang.net/max-tag-01-3x.ae6e41fd.png",
      instalmentCancelInterestImgUrl:
        "https://activitystatic.lkbang.net/max-tag-02-3x.fd7791a9.png",
      rateExplain:
        "综合服务费：包括依据用户与资金提供方以及相关担保方、保险方的约定，按期向资金提供方缴纳的利息、分期服务费等，以及向担保方缴纳的担保费在内的全部资金成本。除还本金以及该金额外用户无需就贷款事项支付其他任何费用。",
      isInstallment: 0
    }
  }
};
export default {
  components: {
    payCard,
    payGroupCard,
    UniPopup,
    uniPopupDialog,
    uniCountdown,
    tougdunCanvas
  },
  data() {
    return {
      popType: null,
      orderNo: null, // 订单编号
      isPaying: false, // 是否支付中的状态
      payType: null, // 默认的支付方式
      openId: "", // 支付依赖的openId
      btnType: null, // 初始化按钮状态

      payMethods: [],
      displayInfo: {
        orderAmt: null,
        periodSeconds: 0
      },
      creditPayList: {}, // 推荐信用支付, 享花卡，或者是组合支付
      thirdPayList: {} // 其他支付方式，微信，支付宝，虚拟支付等
    };
  },
  computed: {
    popupConfig() {
      const popItem = cfg.POPUPCONFIG[this.popType];
      return { ...cfg.POPUPCONFIG.default, ...popItem };
    },

    buttonList() {
      return cfg.BUTTON_CONFIG[this.btnType];
    },
    overTime() {
      return this.btnType !== null && this.btnType !== cfg.TMOT_BTN;
    },
    // 留着入口，实际支付金额
    orderAmt() {
      return this.displayInfo.orderAmt;
    }
  },
  watch: {},
  onLoad({ orderNo }) {
    this.orderNo = orderNo || uni.getStorageSync("orderNo");
    uni.setStorageSync("orderNo", this.orderNo);
    this.queryPayInfo();
  },
  methods: {
    okEvent() {
      console.log("确定按钮");
    },
    quxiao() {
      console.log("专门取消的事件");
    },
    /**
     * 弹窗取消按钮事件
     * @param popItem 弹窗信息
     */
    popupCancelEvent() {
      const { cancelEvent } = this.popupConfig;
      cancelEvent && this[cancelEvent]();
    },
    /**
     * 弹窗确认按钮事件
     * @param popItem 弹窗信息
     */
    popupConfirmEvent() {
      const { confirmEvent } = this.popupConfig;
      confirmEvent && this[confirmEvent]();
    },
    openPopupEvent(popType) {
      this.popType = popType;
      this.$refs.configPopup.open();
    },
    /***
     * 查询页面展示信息,暂时只有，金额，支付时间等
     * return null
     */
    async queryPayInfo() {
      console.log(queryPayInfo);
      uni.showLoading({ title: "加载中..." });
      // const [data, error] = await queryPayInfo({
      //   orderNo: this.orderNo,
      //   isUsedMergePayMethod: false // 是否开启组合支付
      // });
      const error = null;
      const data = DATA;

      if (error && codeArr.indexOf(error?.response?.businessCode) < 0) {
        uni.hideLoading();
        return this.payResult("Fail", error?.msg);
      }
      this.displayInfo = this.beforeFilterData(data?.displayInfo);
      this.payMethods = data?.payMethods;
      this.filterPayMethods(data?.displayInfo, data?.payMethods);
      uni.hideLoading();
    },
    beforeChangePayType(payItem) {
      return !payItem.disabled;
    },
    changePayType(payItem) {
      const isNext = this.beforeChangePayType(payItem);
      if (isNext) {
        const payMethods = this.payMethods;
        const newPayMethodsList = payMethods.map(item => {
          item.isDefault = payItem.method === item.method;
          return item;
        });
        this.filterPayMethods(this.displayInfo, newPayMethodsList);
        console.log(newPayMethodsList);
      }
    },
    filterPayMethods(displayInfo, payMethods) {
      for (const payItem of payMethods) {
        if (payItem.isDefault) this.payType = payItem.method;
        // 是否是微信组合支付
        if (cfg.IS_GROUP_PAY(payItem.method)) {
          const weChatKey = "wxPayInfo";
          this.$set(this.creditPayList, weChatKey, displayInfo[weChatKey]);
          continue;
        }
        for (const infoIndex in displayInfo) {
          const infoItem = displayInfo[infoIndex];
          const infoPayType = infoItem.payType;
          if (!infoPayType || payItem.method !== infoItem.payType) continue;
          const value = { ...infoItem, ...payItem, disabled: false };
          // 是否是享花卡支付
          if (infoItem.payType === cfg.CREDIT_PAY) {
            this.$set(this.creditPayList, infoIndex, value);
            break;
          }
          this.$set(this.thirdPayList, infoIndex, value);
        }
      }
      console.log("===============>creditPayList", this.creditPayList);
      console.log("===============>thirdPayList", this.thirdPayList);
      // for (const payIndex in displayInfo) {
      //   const payItem = displayInfo[payIndex];
      //   if (payItem.payType) {
      //     console.log(payItem.payType);
      //   }
      // }

      // const payMethodsObject = payMethods.reduce((payObj, payItem) => {
      //   if (payItem.isDefault) {
      //     this.payType = payItem.method; // 默认支付方式
      //   }
      //   payObj[payItem.method] = payItem;
      //   return payObj;
      // }, {});
      // console.log(payMethodsObject);
      // for (const p of payMethods) {
      //   if (p.isDefault) {
      //     this.payType = p.method; // 默认支付方式
      //   }
      //   for (const key in displayInfo) {
      //     const payType = displayInfo[key].payType;
      //     if (!payType) continue; // 如果没有支付值则跳过
      //     // 设置其他支付方式
      //     this.$set(this.thirdPayList, key, {
      //       ...displayInfo[key],
      //       ...p,
      //       show: true,
      //       isCheck: p.isDefault || false
      //     });
      //     break;
      //     // /* 三方支付 */
      //     // /* 过滤出微信数据 */
      //     // if (IS_THIRD_PAY(p.method) && p.method === payType) {
      //     // }
      //     // /* 信用支付 */
      //     // if (
      //     //   IS_CREDIT_PAY(p.method) &&
      //     //   (p.method === payType || (p.method > 3 && p.method - 2 === payType))
      //     // ) {
      //     //   console.log("key========>", key, p.method);
      //     //   this.creditPayList.isGroupPay = IS_GROUP_PAY(p.method);
      //     //   if (p.isDefault) {
      //     //     this.mergePayPretreatmentInfo = p.mergePayPretreatmentInfo;
      //     //   }
      //     //   if (key === "creditPayInfo" && this.checkStatus(displayInfo[key], displayInfo)) {
      //     //     displayInfo[key].disabled = true;
      //     //   }
      //     //   this.$set(this.creditPayList.payList, key, {
      //     //     ...displayInfo[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", {
      //     //       ...displayInfo["creditPayInfo"],
      //     //       show: true,
      //     //       isCheck: false
      //     //     });
      //     //   }
      //     //   break;
      //     // }
      //   }
      // }
      // const { method } = payMethods.find(payItem => payItem.isDefault);
      // this.payType = method;
    },
    /**
     * 过滤展示信息，触发一些初始化操作
     * 处理之后返回参数
     * return info:object
     */
    beforeFilterData(info = {}) {
      // 初始化-支付时间小于0，支付已经过期
      this.btnType = info?.periodSeconds <= 0 ? cfg.TMOT_BTN : cfg.SURE_BTN;
      return info;
    },
    onButtonClick(btnItem) {
      this[btnItem.event](btnItem);
    },
    // 支付事件触发
    nextAction: debounce(function(btnItem) {
      this.sendNextAction(btnItem);
      this.paymentEvent();
    }, 500),
    async paymentEvent() {
      this.isPaying = true;
      const { isNext } = await this.beforePayCheck();
      if (isNext) {
        try {
          const paramsData = await this.getPayParams(); // 获取预支付参数
          const { orderInfo } = await this.prepay(paramsData); // 获取支付参数
          const { status } = await this.requestPayment(orderInfo);
          status && this.queryPayStatus(); // 支付成功之后的回调用
          this.isPaying = false;
        } catch (err) {
          console.log("错误信息================>", err);
          this.isPaying = false;
          if (err?.toast) return this.$api.msg(err.message);
          this.payResult("Fail", err.message);
        }
      } else {
        this.isPaying = false;
      }
    },
    async prepay(paramsData) {
      console.log("支付参数===============>", paramsData);
      const [data, error] = await prepay(paramsData);
      if (!error) {
        let orderInfo = null;
        /* #ifdef MP-ALIPAY */
        orderInfo = data.aliPayInfo?.order_string;
        /* #endif */
        /* #ifdef MP-BAIDU */
        orderInfo = data?.baiduPayInfo;
        /* #endif */
        return { orderInfo };
      }
      return Promise.reject({ message: error.msg });
    },
    async getPayParams() {
      const openId = await this.getOpenId();
      return {
        openId,
        ocrAuth: { isH5: false },
        orderNo: this.orderNo,
        payMethod: this.payType,
        payCouponId: "", // 下单使用优惠卷id
        mergePayPretreatmentId: "",
        appMiniId: ""
      };
    },
    /***
     * 支付之前校验是否可以进行支付
     * @params null
     * @return { isNext: 校验是否通过 }
     */
    beforePayCheck() {
      return new Promise(resolve => {
        if (!this.overTime) {
          this.$api.msg("订单已超时！");
          return resolve({ isNext: false });
        } // 检测订单是否超时
        return resolve({ isNext: true });
      });
    },
    /***
     * 拉起支付
     * @params orderInfo: 支付所需要的参数信息, type: string|object
     * @retrun type: promise
     */
    async requestPayment(orderInfo) {
      return new Promise((resolve, reject) => {
        uni.requestPayment({
          provider: mpConfig.provider,
          orderInfo,
          success: result => {
            console.log("=======================>支付result", result);
            /* #ifdef MP-ALIPAY */
            const status = result?.errMsg === "requestPayment:ok";
            if (result?.resultCode === "9000") {
              return resolve({ status, message: "支付成功", ...result });
            }
            /* #endif */

            /* #ifdef MP-BAIDU */
            if (result) {
              return resolve({ status: true, message: "支付成功", ...result });
            }
            // if (result.statusCode === 0) {
            //   try {
            //     const [, succeeObj] = result.statusMsg.split("：");
            //     console.log("result.statusMsg=============>", JSON.parse(succeeObj));
            //     return resolve({ status: true, message: "支付成功", ...result });
            //   } catch (error) {
            //     console.log("try error==============>", error);
            //   }
            // }
            /* #endif */
            return reject({ status: false, toast: true, message: result.memo, ...result });
          },
          fail: error => {
            console.log("=======================>支付error", error);
            /* #ifdef MP-ALIPAY */
            reject({ status: false, message: "支付失败", ...error });
            /* #endif */
            /* #ifdef MP-BAIDU */
            reject({ status: false, message: error.errMsg });
            /* #endif */
          }
        });
      });
    },
    /***
     * 查询支付状态，支付成功到支付成功页
     * 支付助状态如果有延迟需要跳转到支付中的页面
     */
    async queryPayStatus() {
      const [{ payStatus }, error] = await queryPayStatus({ orderNo: this.orderNo });
      if (error) return this.payResult("Fail", error.msg); // 如果有错误信息直接跳转到错误页
      if (+payStatus === 3) return this.payResult("Success"); // 支付成功跳转到支付成功页
      this.payResult("Loading"); // 如果支付状态有延迟，直接到支付中的页面
    },
    /***
     * @params null
     * @return promise(openId: string)
     */
    getOpenId() {
      return new Promise((resolve, reject) => {
        const vm = this;
        const openId = uni.getStorageSync(paymentConfig.openIdKey);
        if (openId) return resolve(openId);
        // #ifdef MP-BAIDU
        uni.getLoginCode({
          success: async function(res) {
            const result = await vm.getLoginCode(res);
            if (result) {
              return resolve(result);
            }
            reject({ message: "获取openId错误！" });
          },
          fail: err => {
            console.log("getLoginCode====================> fail", err);
          }
        });
        // #endif

        // #ifdef MP-ALIPAY
        uni.login({
          provider: mpConfig.provider,
          scopes: "auth_base",
          success: async function(res) {
            const result = await vm.getLoginCode(res);
            if (result) {
              return resolve(result);
            }
            reject({ message: "获取openId错误！" });
          },
          fail: err => {
            console.log("login====================> fail", err);
          }
        });
        // #endif
      });
    },
    /**
     * 获取最新openId
     * 以防在支付时清除缓存之后无法支付
     * @params res uni.login返回code码
     */
    async getLoginCode(res) {
      const [data, error] = await authApi.login({ code: res.code });
      if (!error) {
        const result = data[paymentConfig.openIdKey];
        uni.setStorageSync(paymentConfig.openIdKey, result);
        return result;
      }
      return null;
    },
    timeupOut() {
      this.btnType = cfg.TMOT_BTN;
    },
    /**
     * 支付成功｜失败中转页
     * @params type: Fail | Success
     * @params error: Fail时的错误信息
     */
    async payResult(type, error) {
      const queryParams = {
        orderNo: this.orderNo,
        amount: this.orderAmt,
        reason: error,
        payType: this.payType,
        freeAmount: 0
      };
      uni.redirectTo({ url: `/pages/pay/pay${type}${param(queryParams, true)}` });
    },
    objectIsEmpy(obj) {
      return Object.keys(obj).length;
    },
    goHome() {
      uni.switchTab({
        url: "/pages/index/index"
      });
    },
    goOrderDetail() {
      uni.redirectTo({
        url: `/pages/order/orderDetail?orderNo=${this.orderNo}`
      });
    },
    /******************************************************************************************/
    /******************************************************************************************/
    /***********************************神策埋点-START*******************************************/
    /******************************************************************************************/
    // 确认支付埋点
    sendNextAction(btnItem) {
      console.log(btnItem, "=================>=================>=================>");
      saTrackEvent("PD_YXMMACP_UserClickCashierConfirmPaymentBtn", {
        order_id: this.orderNo,
        pay_method: cfg.TACK_PAY_BUTTON_CLICK[this.payType],
        vcc_state: "",
        buttons_name: btnItem.name
      });
      uni.reportAnalytics("c_cashierconfirmpaymentbtn", {
        order_id: this.orderNo,
        pay_method: cfg.TACK_PAY_BUTTON_CLICK[this.payType],
        vcc_state: "",
        buttons_name: btnItem.name
      });
    }
    /******************************************************************************************/
    /*************************************神策埋点-END******************************************/
    /******************************************************************************************/
  }
};
</script>

<style lang="scss" scoped src="./index.scss"></style>
