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", "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.payUrl) {
          payInfo = {
            url: res.payUrl,
            params: {
              ...orderInfo,
              tradeType,
              state: 1
            }
          };
        } else if (tradeType === "JSAPI") {
          payInfo = res.payInfo;
        } else {
          payInfo = {
            url: res.payUrl,
            params: {
              ...orderInfo,
              tradeType,
              state: 1
            }
          };
        }
        payByWay(tradeType, payInfo).then(() => {
          this.getPayResult();
        });
      } else {
        this.setIsPayWait(false);
      }
    },
    getPayResult() {
      const { payOrderNo, orderNo } = this.orderInfo;
      placeOrder.polling({ payOrderNo, payOrderType: 1 }).then(payRes => {
        if (!payRes.result && payRes.payState === 2) {
          this.payTimer = setTimeout(() => {
            this.getPayResult();
          }, 3000);
        } else {
          this.setIsPayWait(false);
          this.setIsLoading(false);
          this.$router.replace({ path: "/policy/detail/" + orderNo });
        }
      });
    }
  }
};
