import {
  status,
  payTypeE,
  payTypeText,
  CREDIT_PAY,
  IS_THIRD_PAY,
  IS_CREDIT_PAY,
  IS_GROUP_PAY
} from "./STATIC_DATA";
import { getOrderType, reissueContract } from "@/api/pay.api.js";
import { saTrackEvent } from "@/utils/sa";
import { isHundredGroup } from "./payRedirect.js";
import config from "@/config";

export default {
  data() {
    return {
      configPopup: {},
      popupConfig: {
        // 未开通享花卡时，推荐开通享花卡
        freeQuota: {
          content: "您有一笔免费额度可以使用，40天免息等你拿",
          cancelTxt: "继续支付",
          confirmTxt: "立即开通",
          cancel: "pay",
          confirm: "apply"
        },
        // 已经开通享花卡时，使用其他方式支付时推荐组合支付
        detention: {
          content: "使用组合支付部分金额可免息使用40天哦！",
          cancelTxt: "继续支付",
          confirmTxt: "组合支付",
          cancel: "pay",
          confirm: "detentionConfirm"
        },
        // 已经开通享花卡，但没有组合支付时推荐使用享花卡支付
        jcardPay: {
          content: "使用享花卡支付可免息使用40天哦",
          cancelTxt: "继续支付",
          confirmTxt: "享花卡支付",
          cancel: "pay",
          confirm: "jcardPayConfirm"
        },
        // 用享花卡支付额度不足
        insufficient: {
          content: "您的消费额度不足，请更换支付方式！",
          confirmTxt: "其他方式支付",
          hideCancelBtn: true
        },
        cardPopup: {
          content: "使用享花卡支付需要您绑定银行卡便于后续的还款哦~",
          cancelTxt: "其他支付方式",
          confirmTxt: "立即绑卡",
          cancel: "switchPayType",
          confirm: "openCard"
        },
        canUseAmt: {
          conent: "抱歉，您的本笔订单暂不支持享花卡支付，请您使用其他支付方式～",
          confirmTxt: "知道了",
          hideCancelBtn: true
        },
        freezeCred: {
          content: "您有未完成支付的订单占用额度，需要先支付完成该笔订单哦！",
          cancelTxt: "继续支付",
          confirmTxt: "查看订单",
          confirm: "viewOrder"
        },
        isPaySuccess: {
          content: "请确认订单已完成支付！",
          cancelTxt: "重新支付",
          confirmTxt: "已完成支付",
          confirm: "isPayOrderSuccess"
        }
      }
    };
  },
  methods: {
    closeConfigModal() {
      this.$refs["configPopup"].close();
    },
    openConfigModal(conkey, modalContent) {
      const defaultValue = this.popupConfig[conkey];
      const configPopup = {
        ...defaultValue
      };
      configPopup.content = modalContent ? modalContent : configPopup.content;
      this.configPopup = configPopup;
      this.$refs["configPopup"].open();
    },
    configEvent(eventKey) {
      this[eventKey] && this[eventKey]();
    },
    // 推荐使用组合支付
    detentionConfirm() {
      for (let key in this.creditPayList.payList) {
        if (this.creditPayList.payList[key].isRecommend) {
          const type = this.creditPayList.payList[key].payType;
          this.changePayType(type, this.creditPayList.payList[key].mergePayPretreatmentInfo);
          this.protocolChecked = 1;
          this.pay();
          return;
        }
      }
    },
    jcardPayConfirm() {
      // 切换享花卡支付
      console.log("================>切换享花卡支付");
      this.changePayType(CREDIT_PAY);
      this.protocolChecked = 1;
    },
    async viewOrder() {
      if (await isHundredGroup(this.orderNo)) {
        // 判断是否是百人团
        const url = `${config.groupBuyHost}/orderList/0?vccToken={token}`;
        uni.redirectTo({
          url: `/pages/groupbuy/webview?url=${encodeURIComponent(JSON.stringify(url))}`
        });
        return;
      }
      uni.redirectTo({
        url: "/pages/order/orderList"
      });
    },
    isPayOrderSuccess() {
      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;
      }
      uni.redirectTo({
        url: `/pages/pay/payLoading?amount=${finalAmt}&orderNo=${this.orderNo}&freeAmount=${freeAmount}&payType=${this.payType}`
      });
    },
    filterPayMethods(payMethods, displayInfo) {
      // const miniFace = displayInfo?.creditPayInfo?.miniFace;
      // 是否需要认证提额，如果需要认证提额 默认选中享花卡选项
      // if (miniFace) {
      //   payMethods = payMethods.map(item => {
      //     item.isDefault = item.method === CREDIT_PAY;
      //     return item;
      //   });
      // }
      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;
          }
          /* 三方支付 */
          /* 过滤出微信数据 */
          if (IS_THIRD_PAY(p.method) && p.method === payType) {
            this.$set(this.thirdPayList.payList, key, {
              ...displayInfo[key],
              ...p,
              show: true,
              isCheck: p.isDefault || false
            });
            break;
          }
          /* 信用支付 */
          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;
          }
        }
      }
    },
    sendPayTrack() {
      this.payType &&
        saTrackEvent(payTypeE[this.payType - 1], {
          order_id: this.orderNo
        });
    },
    async sendNextAction() {
      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
      });
    },
    selectCouponItem(isSelected, couponInfo) {
      saTrackEvent("PD_YXMMACP_UserClickCouponPopupWindowCoupon", {
        check_or_not: isSelected ? "勾选" : "取消",
        coupon_id: couponInfo.pickupId
      });
    },
    changePop(pop) {
      pop?.show === false && saTrackEvent("PD_YXMMACP_UserClickCouponPopupWindowCloseBtn");
    },
    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)
      });
    }
  }
};
