import { payByWay } from "@/service/pay";
import { isXyqb, isWeixinBrower } from "@/service/validation";
import { placeOrder } from "@/api/product";
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"]),
    async generateOrder() {
      const res = await placeOrder.create({
        ...this.subFormData
      });
      if (res) {
        this.orderInfo = res;
        this.goPay();
      }
    },
    async goPay() {
      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;
      }
      const res = await placeOrder.pay(params);
      if (res) {
        let payInfo = {
          mock: true,
          url: res.payUrl,
          params: {
            ...orderInfo,
            tradeType,
            state: 1
          }
        };
        if (tradeType === "JSAPI") {
          payInfo = res.payInfo;
        }
        payByWay(tradeType, payInfo).then(() => {
          this.getPayResult();
        });
      }
    },
    getPayResult() {
      const { payOrderNo, orderNo } = this.orderInfo;
      this.setIsLoading(true);
      placeOrder.polling({ payOrderNo, payOrderType: 1 }).then(payRes => {
        if (!payRes.result && payRes.payState === 2) {
          this.payTimer = setTimeout(() => {
            this.getPayResult();
          }, 3000);
        } else {
          this.setIsLoading(false);
          this.$router.push({ path: "/policy/detail/" + orderNo });
        }
      });
    }
  }
};
