import type { IncomeItem, VipAndCourseMonthStatistics } from './types';

// 处理收款汇总数据以及实物和培训班数据
export function handleSumAndNoNeedAmortizateMonthData(
  responseData: any[],
  options: {
    childDictArr: { title: string; type: string }[];
    typeDictArr: string[];
    typeKey: string;
  },
) {
  let sumMonthTotal = 0;
  const resultData = [] as any[];
  const { childDictArr, typeDictArr, typeKey } = options;
  typeDictArr.forEach((type) => {
    // 查找接口返回数据中是否有当前支付平台的数据
    const index = responseData.findIndex((item) => item[typeKey] === type);
    // 取得当前支付平台的数据项，若不存在则用空对象代替
    const resItem = index === -1 ? {} : responseData[index];
    // 组装页面渲染需要的数据格式
    resultData.push({
      type,
      sumFee: resItem.sumFee || 0,
      children: childDictArr.map((childType) => ({
        title: childType.title,
        fee: resItem[childType.type] || 0,
      })),
    });
    // 累加总金额
    // 使用 toFixed 避免精度丢失
    sumMonthTotal = Number.parseFloat((sumMonthTotal + (resItem.sumFee || 0)).toFixed(3));
  });
  return {
    sumMonthTotal,
    resultData,
  };
}

// 获取当前月份和上一个月份的数据
async function getTwoMonthData(
  requestMethod: (params: { month: string; year: number | string }) => Promise<any>,
  date: string,
) {
  // 处理日期格式，将YYYY-MM转换为year: YYYY, month: MM
  const [year = '', month = ''] = date.split('-');
  const params = {
    year,
    month,
  };
  // 处理跨年情况
  const lastMonthParams = {
    year: params.month === '01' ? Number(params.year) - 1 : params.year,
    month: params.month === '01' ? '12' : (Number(params.month) - 1).toString().padStart(2, '0'),
  };
  // 调用接口 查询当前月份数据和上一个月数据
  // 同时发送两次请求
  const [currentMonthData, lastMonthData] = await Promise.all([
    requestMethod(params),
    requestMethod(lastMonthParams),
  ]);
  return {
    currentMonthData,
    lastMonthData,
  };
}

// 处理VIP、课程数据的公共方法
export async function handleVipAndCourseMonthData(
  requestMethod: (params: {
    month: string;
    year: number | string;
  }) => Promise<VipAndCourseMonthStatistics>,
  date: string,
  incomeTypes: string[],
) {
  const { currentMonthData, lastMonthData } = await getTwoMonthData(requestMethod, date);
  return {
    ...currentMonthData,
    incomes: incomeTypes.map((type) => ({
      type,
      fee: currentMonthData.incomes.find((item: IncomeItem) => item.type === type)?.fee || 0,
    })),
    lastNotyet: lastMonthData?.notyet || 0,
    incomesTotal: Number.parseFloat(
      currentMonthData.incomes
        .reduce((acc: number, cur: IncomeItem) => acc + cur.fee, 0)
        .toFixed(3),
    ),
  };
}

// 处理天医币明细数据
export async function handleTianyibiDetailData(
  requestMethod: (params: {
    month: string;
    year: number | string;
  }) => Promise<VipAndCourseMonthStatistics>,
  date: string,
  incomeTypes: string[],
  consumesTypes: string[],
) {
  const { currentMonthData, lastMonthData } = await getTwoMonthData(requestMethod, date);
  return {
    ...currentMonthData.map,
    incomes: incomeTypes.map((type) => ({
      type,
      fee: currentMonthData.map.incomes.find((item: IncomeItem) => item?.type === type)?.fee || 0,
      point:
        currentMonthData.map.incomes.find((item: IncomeItem) => item?.type === type)?.point || 0,
    })),
    consumes: consumesTypes.map((type) => ({
      type,
      fee: currentMonthData.map.consumes.find((item: IncomeItem) => item?.type === type)?.fee || 0,
    })),
    lastSurplus: lastMonthData?.map.surplus || 0,
    incomesTotal: Number.parseFloat(
      currentMonthData.map.incomes
        .reduce((acc: number, cur: IncomeItem) => acc + cur.fee, 0)
        .toFixed(3),
    ),
    consumesTotal: Number.parseFloat(
      currentMonthData.map.consumes
        .reduce((acc: number, cur: IncomeItem) => acc + cur.fee, 0)
        .toFixed(3),
    ),
  };
}
