import request from '@/utils/request';
import type {ApiResult} from '@/api';
import type {ShopDealerOrder, ShopDealerOrderParam} from './model';
import {utils, writeFile} from 'xlsx';
import {message} from 'ant-design-vue';
import {getTenantId} from '@/utils/domain';
import {listShopDealerOrder} from "@/api/shop/shopDealerOrder";
import {MODULES_API_URL} from "@/config/setting";

/**
 * 导入分销商订单
 */
export async function importSdyDealerOrder(file: File) {
  const formData = new FormData();
  formData.append('file', file);
  const res = await request.post<ApiResult<unknown>>(
    MODULES_API_URL + '/sdy/sdy-dealer-order/import',
    formData
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 导出分销商订单
 */
export async function exportSdyDealerOrder(params?: ShopDealerOrderParam) {
  // 显示导出加载提示
  message.loading('正在准备导出数据...', 0);

  try {
    // 获取数据
    const list = await listShopDealerOrder(params);

    if (!list || list.length === 0) {
      message.destroy();
      message.warning('没有数据可以导出');
      return;
    }

    // 构建导出数据
    const array: (string | number)[][] = [
      [
        '订单ID',
        '买家用户ID',
        '订单总金额',
        '一级分销商ID',
        '一级佣金',
        '二级分销商ID',
        '二级佣金',
        '三级分销商ID',
        '三级佣金',
        '订单状态',
        '结算状态',
        '结算时间',
        '创建时间'
      ]
    ];

    list.forEach((order: ShopDealerOrder) => {
      array.push([
        order.orderNo || '',
        order.userId || '',
        order.orderPrice || '0',
        order.firstUserId || '',
        order.firstMoney || '0',
        order.secondUserId || '',
        order.secondMoney || '0',
        order.thirdUserId || '',
        order.thirdMoney || '0',
        order.isInvalid === 0 ? '有效' : '失效',
        order.isSettled === 0 ? '未结算' : '已结算',
        order.settleTime ? new Date(order.settleTime).toLocaleString() : '',
        order.createTime || ''
      ]);
    });

    // 创建工作簿
    const sheetName = `shop_dealer_order_${getTenantId()}`;
    const workbook = {
      SheetNames: [sheetName],
      Sheets: {}
    };

    const sheet = utils.aoa_to_sheet(array);
    workbook.Sheets[sheetName] = sheet;

    // 设置列宽
    sheet['!cols'] = [
      {wch: 15}, // 订单ID
      {wch: 12}, // 买家用户ID
      {wch: 12}, // 订单总金额
      {wch: 15}, // 一级分销商ID
      {wch: 12}, // 一级佣金
      {wch: 15}, // 二级分销商ID
      {wch: 12}, // 二级佣金
      {wch: 15}, // 三级分销商ID
      {wch: 12}, // 三级佣金
      {wch: 10}, // 订单状态
      {wch: 10}, // 结算状态
      {wch: 20}, // 结算时间
      {wch: 20}  // 创建时间
    ];

    message.destroy();
    message.loading('正在生成Excel文件...', 0);

    // 延迟写入文件，确保消息提示显示
    setTimeout(() => {
      writeFile(workbook, `${sheetName}.xlsx`);
      message.destroy();
      message.success(`成功导出 ${list.length} 条记录`);
    }, 1000);

  } catch (error: any) {
    message.destroy();
    message.error(error.message || '导出失败，请重试');
  }
}

/**
 * 结算订单
 */
export async function updateSdyDealerOrder(data: ShopDealerOrder) {
  const res = await request.put<ApiResult<unknown>>(
    '/sdy/sdy-dealer-order',
    data
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}
