import request from '@/utils/request';
import { withCreditUserScope } from '@/api/credit/utils/data-scope';

import type { ApiResult, PageResult } from '@/api';
import type { CreditNearbyCompany, CreditNearbyCompanyParam } from './model';

/**
 * 分页查询附近企业
 */
export async function pageCreditNearbyCompany(
  params: CreditNearbyCompanyParam
) {
  const res = await request.get<ApiResult<PageResult<CreditNearbyCompany>>>(
    '/credit/credit-nearby-company/page', withCreditUserScope(params));
  if (res.code === 0) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 查询附近企业列表
 */
export async function listCreditNearbyCompany(
  params?: CreditNearbyCompanyParam
) {
  const res = await request.get<ApiResult<CreditNearbyCompany[]>>(
    '/credit/credit-nearby-company', withCreditUserScope(params));
  if (res.code === 0 && res.data) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 添加附近企业
 */
export async function addCreditNearbyCompany(data: CreditNearbyCompany) {
  const res = await request.post<ApiResult<unknown>>(
    '/credit/credit-nearby-company',
    data
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 修改附近企业
 */
export async function updateCreditNearbyCompany(data: CreditNearbyCompany) {
  const res = await request.put<ApiResult<unknown>>(
    '/credit/credit-nearby-company',
    data
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 删除附近企业
 */
export async function removeCreditNearbyCompany(id?: number) {
  const res = await request.del<ApiResult<unknown>>(
    '/credit/credit-nearby-company/' + id
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 批量删除附近企业
 */
export async function removeBatchCreditNearbyCompany(
  data: (number | undefined)[]
) {
  const res = await request.del<ApiResult<unknown>>(
    '/credit/credit-nearby-company/batch',
    data);
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 根据id查询附近企业
 */
export async function getCreditNearbyCompany(id: number) {
  const res = await request.get<ApiResult<CreditNearbyCompany>>(
    '/credit/credit-nearby-company/' + id
  );
  if (res.code === 0 && res.data) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 导入附近企业
 */
export async function importCreditNearbyCompany(
  file: File,
  companyId?: number
) {
  const formData = buildImportFormData(file, companyId);
  const res = await request.post<ApiResult<unknown>>(
    '/credit/credit-nearby-company/import',
    formData,
    {
      header: {
        'Content-Type': 'multipart/form-data'
      }
    }
  );
  if (res.code === 0) {
    return res.message || '导入成功';
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 导入附近企业（多文件，同一次请求）
 *
 * 约定：后端需支持 multipart 同名字段 `file` 多次出现（常见于 MultipartFile[] file）
 */
export async function importCreditNearbyCompanyMulti(
  files: File[] | FileList,
  companyId?: number
) {
  const formData = buildImportFormData(files, companyId);
  const res = await request.post<ApiResult<unknown>>(
    '/credit/credit-nearby-company/import',
    formData,
    {
      header: {
        'Content-Type': 'multipart/form-data'
      }
    }
  );
  if (res.code === 0) {
    return res.message || '导入成功';
  }
  return Promise.reject(new Error(res.message));
}

function buildImportFormData(
  fileOrFiles: File | File[] | FileList,
  companyId?: number
) {
  const formData = new FormData();
  if (Array.isArray(fileOrFiles)) {
    fileOrFiles.forEach((f) => formData.append('file', f));
  } else if (fileOrFiles instanceof FileList) {
    Array.from(fileOrFiles).forEach((f) => formData.append('file', f));
  } else {
    formData.append('file', fileOrFiles);
  }
  if (companyId != null) {
    formData.append('companyId', String(companyId));
  }
  return formData;
}

export interface ImportBatchCreditNearbyCompanyItem {
  fileName: string;
  success: boolean;
  message: string;
}

export interface ImportBatchCreditNearbyCompanyResult {
  total: number;
  success: number;
  failure: number;
  items: ImportBatchCreditNearbyCompanyItem[];
}

/**
 * 导入附近企业（多文件）
 *
 * 说明：
 * - 目前复用单文件导入接口，前端循环调用实现“多文件导入”
 * - 不会在有失败时 reject（便于上层展示部分成功/失败明细）
 */
export async function importBatchCreditNearbyCompany(
  files: File[] | FileList,
  companyId?: number,
  options?: {
    /** 遇到失败是否立即停止，默认 false（继续导入后续文件） */
    stopOnError?: boolean;
  }
): Promise<ImportBatchCreditNearbyCompanyResult> {
  const list = Array.isArray(files) ? files : Array.from(files);
  const items: ImportBatchCreditNearbyCompanyItem[] = [];
  const stopOnError = options?.stopOnError ?? false;

  for (const file of list) {
    try {
      const msg = await importCreditNearbyCompany(file, companyId);
      items.push({ fileName: file.name, success: true, message: msg });
    } catch (e: unknown) {
      items.push({
        fileName: file.name,
        success: false,
        message: e instanceof Error ? e.message : String(e)
      });
      if (stopOnError) {
        break;
      }
    }
  }

  const success = items.filter((d) => d.success).length;
  const failure = items.length - success;
  return {
    total: list.length,
    success,
    failure,
    items
  };
}
