import { payByWay } from "@/service/pay";
import { isXyqb, isWeixinBrower } from "@/service/validation";
import { placeOrder } from "@/api/product";
import { getPolicyDetail } from "@/api/policy";
import localStorage from "@/service/localStorage";
import { mapActions } from "vuex";
import PayWaitLayer from "@/components/PayWaitLayer";
export default {
  components: {
    PayWaitLayer
  },
  data() {
    return {
      subFormData: {}, // 组装好的数据
      orderInfo: {},
      tradeType: "",
      payTimer: null,
      isPayWait: false
      // customTradeType: ""
    };
  },
  created() {
    this.tradeType = this.customTradeType ?? (isXyqb ? "MWEB" : isWeixinBrower ? "JSAPI" : "MWEB");
  },
  methods: {
    ...mapActions(["setIsShowOpenBrower", "setIsLoading"]),
    async generateOrder(detailType) {
      const res = await placeOrder.create({
        ...this.subFormData
      });
      if (res) {
        if (detailType) {
          const _key = detailType === "li" ? "PolicyFormData" : detailType + "DetailFormData";
          localStorage.remove(_key);
        }
        this.orderInfo = res;
        this.goPay();
      }
    },
    async goPay() {
      const { tradeType, orderInfo } = this;
      const { payOrderNo, payType } = orderInfo;
      if (!payOrderNo) {
        this.$toast("请先生成订单");
        return;
      }
      const params = {
        payOrderNo,
        payOrderType: payType,
        tradeType
      };
      if (localStorage.get("openId") && tradeType === "JSAPI") {
        params.openId = localStorage.get("openId");
      }
      this.isPayWait = true;
      const res = await placeOrder.pay(params);
      if (res) {
        let payInfo = "";
        if (res.payInfo && res.payInfo.payUrl) {
          payInfo = {
            url: res.payInfo.payUrl,
            params: {
              ...orderInfo,
              tradeType,
              state: 1
            }
          };
        } else if (tradeType === "JSAPI" && !res.payUrl && res.payInfo && !res.payInfo.payUrl) {
          payInfo = res.payInfo;
        } else {
          payInfo = {
            url: res.payUrl,
            params: {
              ...orderInfo,
              tradeType,
              state: 1
            }
          };
        }
        payByWay(tradeType, payInfo)
          .then(() => {
            this.getPayResult();
          })
          .catch(() => {
            console.log("h5支付");
            // tradeType === "JSAPI" && this.$notify({ type: "warning", message: "支付异常" });
            setTimeout(() => {
              this.$router.replace({
                path: "/policy"
              });
            }, 3000);
            return;
          });
      } else {
        this.isPayWait = false;
      }
    },
    getPayResult() {
      const { payOrderNo, payType, orderNo } = this.orderInfo;
      placeOrder.polling({ payOrderNo, payOrderType: payType || 1 }).then(async payRes => {
        if (!payRes.result && payRes.payState === 2) {
          this.payTimer = setTimeout(() => {
            this.getPayResult();
          }, 3000);
        } else {
          // payOrderNo为月计划订单时跳转保单列表
          if (+payType === 2) {
            this.$router.replace(`/policy`);
            return;
          }
          // 根据状态跳转页面
          const { status, productNo } = await this.getPolicyStatus(orderNo);
          if (["6.2-3", "6.1-3"].includes(status)) {
            this.$router.replace(`/policy/success/${orderNo}/${productNo}`);
            return;
          }
          // 保单详情页支付需重新调用保单接口
          if (this.$route.name === "PolicyDetail") {
            this.getPolicy();
            return;
          }

          this.$router.replace({
            path: "/policy/detail/" + orderNo + "?isWxH5=" + (this.orderInfo.isWxH5 || "")
          });
          this.isPayWait = false;
          this.setIsLoading(false);
        }
      });
    },
    async getPolicyStatus(orderNo) {
      const policy = await getPolicyDetail(orderNo);
      return {
        status: policy?.payState
          ? `${policy?.policyState}-${policy?.payState}`
          : String(policy?.policyState),
        productNo: policy?.productNo
      };
    }
  }
};
