import { createOrderApi } from "../../api/order.api";
import { throttle } from "../../utils/helper";
import { getSystemInfo } from "../../utils/wechat";


/**
 * @description: 内部支付函数
 * @param {*} payParams
 * @return {*}
 */
const _payment = async (payParams) => {

    try {
        const orderInfo = {
            cp_order_id: payParams.cp_order_id,
            money: payParams.money, // 元单位
            role_id: payParams.role_id,
            role_name: payParams.role_name,
            server_id: payParams.server_id,
            server_name: payParams.server_name,
            ext: payParams.ext ? payParams.ext : "",
            role_level: payParams.role_level,
            product_id: payParams.product_id,
            product_name: payParams.product_name,
        };

        tt.showLoading({
            title: "支付中...",
            mask: true,
        });

        // 下单
        const createOrderResult = await createOrderApi(orderInfo);

        tt.hideLoading({});
        let dyPayConfig = typeof createOrderResult.dy_pay_config !== "undefined" ? createOrderResult.dy_pay_config : {}
        await requestDyPayment(orderInfo, dyPayConfig);
        return Promise.resolve(null);
    } catch (error) {
        return Promise.reject(error);
    }
};
/**
 * @description: 安卓虚拟支付
 * @param {object}
 * @return {*}
 */
export const requestGamePayment = (data) => {
  return new Promise((resolve, reject) => {
    console.log("虚拟支付开始：", data);
    tt.requestGamePayment({
      ...data,
      success: (res) => {
        resolve(res);
      },
      fail: (error) => {
        console.log("虚拟支付失败：", error);
        reject(error);
      },
    });
  });
};


/**
 * @description: iOS 虚拟支付 发起钻石支付
 * @param {object}
 * @return {*}
 */
export const openAwemeCustomerService = (data) => {
  return new Promise((resolve, reject) => {
    console.log("发起钻石支付：", data);
    tt.openAwemeCustomerService({
      ...data,
      success: (res) => {
        resolve(res);
      },
      fail: (error) => {
        console.log("钻石支付失败：", error);
        reject(error);
      },
    });
  });
};



/**
 * 拉起抖音支付
 */
const requestDyPayment = async (orderInfo, dyPayConfig) => {
     let platform = await getSystemInfo("platform");
      try {
        var setGoodType = 0;
        let res;
        // 小额支付描述 https://developer.open-douyin.com/docs/resource/zh-CN/mini-game/develop/guide/open-ability/payment/micropayment-guide
        // 安卓 requestGamePayment
        if(platform==="android"){
        // 判断是否小额支付
        if (tt.canIUse('requestGamePayment.object.goodType')) {
            setGoodType = 2;
            res = await requestGamePayment({
            goodType: setGoodType, // 道具直购
            orderAmount:orderInfo.money * 100, // 单位分
            goodName: orderInfo.product_name,
            currencyType: "CNY",
            zoneId: String(dyPayConfig.zoneId),
            customId: orderInfo.cp_order_id,
            mode: "game",
            env: 0,
            platform: platform, // 目前仅为"android"
            extraInfo: String(setGoodType)
            });
        }else{
            res = await requestGamePayment({
            mode: "game",
            env: 0,
            platform: platform, // 目前仅为"android"
            currencyType: "CNY",
            buyQuantity: dyPayConfig.buyQuantity,
            zoneId: String(dyPayConfig.zoneId),
            customId: orderInfo.cp_order_id,
            });
        }

    }else{
      // 判断是否小额支付
      if (tt.canIUse('openAwemeCustomerService.object.goodType')) {
        setGoodType = 2;
        // iOS openAwemeCustomerService
        res = await openAwemeCustomerService({
          goodType: setGoodType, // 道具直购
          orderAmount: orderInfo.money * 100, // 单位分
          goodName: orderInfo.product_name,
          currencyType: "DIAMOND",
          zoneId: String(dyPayConfig.zoneId),
          customId: orderInfo.cp_order_id,
          extraInfo: String(setGoodType)
        });
      }else{
        // iOS openAwemeCustomerService
        res = await openAwemeCustomerService({
          zoneId: String(dyPayConfig.zoneId),
          customId: orderInfo.cp_order_id,
          currencyType: "DIAMOND",
          buyQuantity: dyPayConfig.buyQuantity,
        });
      }
    }
    return Promise.resolve();
  } catch (error) {
    return Promise.reject(error);
  }
}


/**
 * @description:拉起支付（节流版本，避免短时间内重复点击）
 * @param {*} payParams
 * @return {*}
 */
export const payment = throttle(_payment, 2000);



