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: {},
      openId: localStorage.get("openId"),
      tradeType: "",
      payTimer: null,
      isPayWait: false
      // customTradeType: ""
    };
  },
  created() {
    this.tradeType = this.customTradeType ?? (isXyqb ? "MWEB" : isWeixinBrower ? "JSAPI" : "MWEB");
  },
  methods: {
    ...mapActions(["setIsLoading", "setIsShowOpenBrower"]),
    async generateOrder(detailType) {
      this.setIsLoading(true);
      const res = await placeOrder.create({
        ...this.subFormData
      });
      if (res) {
        this.orderInfo = res;
        detailType && localStorage.remove(detailType + "DetailFormData");
        this.goPay();
      }
    },
    async goPay() {
      this.setIsLoading(false);
      const { tradeType, orderInfo, openId } = this;
      const { payOrderNo, payType } = orderInfo;
      if (!payOrderNo) {
        this.$toast("请先生成订单");
        return;
      }
      const params = {
        payOrderNo,
        payOrderType: payType,
        tradeType
      };
      if (openId && tradeType === "JSAPI") {
        params.openId = 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支付");
            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) {
            if (!payRes?.result) {
              setTimeout(() => {
                this.getPayResult(true);
              }, 3000);
              return;
            }
            this.$router.replace(`/policy`);
            return;
          }
          // 根据状态跳转页面
          const status = await this.getPolicyStatus(orderNo);
          if (["6.2-3", "6.1-3"].includes(status)) {
            this.$router.replace(`/policy/success/${orderNo}`);
            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 policy?.payState
        ? `${policy?.policyState}-${policy?.payState}`
        : String(policy?.policyState);
    }
  }
};
