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";

export default {
  data() {
    return {
      subFormData: {}, // 组装好的数据
      orderInfo: {},
      openId: localStorage.get("openId"),
      tradeType: "",
      payTimer: null
      // customTradeType: ""
    };
  },
  created() {
    this.tradeType = this.customTradeType ?? (isXyqb ? "MWEB" : isWeixinBrower ? "JSAPI" : "MWEB");
  },
  methods: {
    ...mapActions(["setIsLoading", "setIsPayWait"]),
    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.setIsPayWait(true);
      const res = await placeOrder.pay(params);
      if (res) {
        let payInfo = "";
        if (res.payInfo.payUrl) {
          payInfo = {
            url: res.payInfo.payUrl,
            params: {
              ...orderInfo,
              tradeType,
              state: 1
            }
          };
        } else if (tradeType === "JSAPI" && !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支付");
          });
      } else {
        this.setIsPayWait(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 {
          this.setIsPayWait(false);
          this.setIsLoading(false);
          // 保单详情页支付需重新调用保单接口
          if (this.$route.name === "PolicyDetail") {
            this.getPolicy();
            return;
          }
          // 根据状态跳转页面
          const status = await this.getPolicyStatus(orderNo);
          if (["6.2-3", "6.1-3"].includes(status)) {
            this.$router.replace(`/policy/success/${orderNo}`);
            return;
          }

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