import Http from "../utils/http";
import { host, isDebug } from "../utils/constant";

const userHttp = new Http(host);

export function fetchProfile() {
  return userHttp.get("/user/me").then((res) => {
    res.balance = (Number(res.balance) / 100).toFixed(2);
    res.discountAmount = (Number(res.discountAmount) / 100).toFixed(2);
    res.refundableAmount = (Number(res.refundableAmount) / 100).toFixed(2);
    // if (isDebug) {
    //   res.userRechargeRightsList = [
    //     {
    //       discount: 90,
    //     },
    //   ];
    // }
    getApp<any>().globalData.user = res;
    return res;
  });
}

/**
 * 查询我的权益和优惠券
 */
export function fetchRightsAndCoupons() {
  return userHttp.get("/account/listRightsAndCoupons").then((res) => {
    return res;
  });
}

export function fetchCollectList() {
  if (getApp<any>().globalData.collectIds) {
    return Promise.resolve(getApp<any>().globalData.collectIds);
  }
  return userHttp
    .get<
      {
        status: number;
        stationId: number;
      }[]
    >("/user/collectList?page=1&page_size=999")
    .then((res) => {
      getApp<any>().globalData.collectIds = res
        ? res
            .filter((item) => Number(item.status) === 1)
            .map((item) => {
              return Number(item.stationId);
            })
        : [];
      return getApp<any>().globalData.collectIds;
    });
}

export function addCollectList(sid: number) {
  let ids = getApp<any>().globalData.collectIds
    ? (getApp<any>().globalData.collectIds as number[])
    : [];
  const status = ids.includes(sid) ? 0 : 1;
  return userHttp
    .post("/user/collect", {
      data: {
        stationId: sid,
        status,
      },
    })
    .then(() => {
      if (status === 1) {
        ids.push(sid);
      } else {
        ids = ids.filter((id) => id !== sid);
      }
      getApp<any>().globalData.collectIds = ids;
      return status === 1;
    });
}

export function updateProfile(data: any) {
  return userHttp.put("/user", {
    data,
  });
}

declare const wx: any;

export function insertMoney(amount: number) {
  if (isDebug) {
    return Promise.resolve();
  }
  return userHttp
    .post("/payment/wxPay", {
      data: {
        amount: parseInt(`${amount * 100}`),
        openid: getApp<any>().globalData.user.openid,
      },
    })
    .then((res: any) => {
      return new Promise((resolve, reject) => {
        // #ifdef MP-WEIXIN
        wx.requestPayment({
          timeStamp: `${res.timeStamp}`,
          nonceStr: res.nonceStr,
          package: res.packageVal,
          signType: res.signType,
          paySign: res.paySign,
          success(res: any) {
            resolve(res);
          },
          fail: reject,
        });
        // #endif
        // #ifndef MP-WEIXIN
        reject({
          errMsg: "目前仅支持微信支付",
        });
        // #endif
      });
    });
}

export function logout() {
  return userHttp.get("/user/logout");
}

export function fetchWallet(
  type: number,
  page: number,
  pageSize: number,
  query?: string
) {
  return userHttp.get(
    `/account/walletDetail?page=${page}&page_size=${pageSize}&type=${type}${
      query ? "&" + query : ""
    }`
  );
}

export function fetchOrder(orderid: string) {
  return userHttp.get(`/charge/orderDetail/${orderid}`);
}

export function fetchOrders(page: number, pageSize: number, query?: string) {
  return userHttp.get(
    `/charge/listUserChargeOrders?pageNum=${page}&pageSize=${pageSize}${
      query ? "&" + query : ""
    }`
  );
}

export function applyRefund(reason: string) {
  return userHttp.post(`/payment/wxApplyRefund`, {
    data: {
      reason,
    },
  });
}


export function listRefund(param: any) {
  return userHttp.post(`/account/listRefund`, {
    data: {
      ...param,
    },
  });
}


/**
 * 获取站点可以领取的优惠券
 * @param stationId
 */
export function listAvailableCoupons(stationId: any) {
  return userHttp.get(`/coupon/listAvailableCoupons?stationId=${stationId}`, {
  });
}


/**
 * 领取优惠券
 * @param couponId
 */
export function collectCoupon (couponId: number) {
  return userHttp.get(`/coupon/collectCoupon?couponId=${couponId}`, {
  });
}





/**
 * 获取当前用户当前站点有效的权益和优惠券
 * @param stationId
 */
export function listStationAvailableRightsAndCoupons (stationId: string) {
  return userHttp.get(`/account/listStationAvailableRightsAndCoupons?stationId=${stationId}`, {
  });
}



