import { http } from '@/utils/http/axios';
import type { QueryPageRequest, QueryPageResponse } from '@/types/basic-query';

/**
 * 生产安全体系文件基础接口
 */
export interface ProductionSafetyFile {
  id?: number;
  bizType?: string; // 业务模块类型：academy/dual/industry/law/safety
  fileCode: string; // 文件编号
  fileName: string; // 文件名称
  classifyName: string; // 分类名称
  fileVersion: string; // 文件版本号
  fileFormat: string; // 文件格式：PDF/WORD
  releaseDate: string; // 发布日期（格式：yyyy-MM-dd）
  fileUrl?: string; // 文件存储路径
  content?: string; // 文档内容（富文本）
  status?: number; // 启用状态：1-启用，0-禁用
  createdAt?: string; // 创建时间
  updatedAt?: string; // 更新时间
  uploadTime?: string; // 上传时间
}

/**
 * 查询参数
 */
export interface ProductionSafetyFileQuery {
  keyword?: string; // 文件名称/编号（模糊查询）
  status?: number; // 状态：1-启用，0-禁用
  classifyName?: string; // 分类名称
  startDate?: string; // 上传日期范围-开始日期
  endDate?: string; // 上传日期范围-结束日期
}

/**
 * 分页查询参数（Pageable<T> 格式）
 */
export interface ProductionSafetyFilePageQuery {
  pageNumber: number; // 页码，从1开始
  pageSize: number; // 每页数量
  queryParam?: ProductionSafetyFileQuery; // 查询条件对象
}

/**
 * 导出参数
 */
export interface ProductionSafetyFileExportQuery extends ProductionSafetyFileQuery {}

/**
 * 导入响应
 */
export interface ImportRes {
  successCount: number; // 成功数量
  failCount: number; // 失败数量
  failMessages: string[]; // 失败信息列表
}

// ==================== 院级文件管理 (academyFile) ====================

/**
 * 新增院级文件
 */
export function saveAcademyFile(data: ProductionSafetyFile) {
  return http.request<number>({
    url: '/admin/prod/academyFile/saveAcademyFile',
    method: 'post',
    data,
  });
}

/**
 * 编辑院级文件
 */
export function updateAcademyFile(data: ProductionSafetyFile & { id: number }) {
  return http.request({
    url: '/admin/prod/academyFile/updateAcademyFile',
    method: 'put',
    data,
  });
}

/**
 * 删除院级文件
 */
export function deleteAcademyFile(id: number) {
  return http.request({
    url: `/admin/prod/academyFile/deleteAcademyFile?id=${id}`,
    method: 'delete',
  });
}

/**
 * 根据ID查询院级文件详情
 */
export function queryAcademyFileById(id: number) {
  return http.request<ProductionSafetyFile>({
    url: `/admin/prod/academyFile/queryAcademyFileById?id=${id}`,
    method: 'get',
  });
}

/**
 * 根据文件编号查询院级文件详情
 */
export function queryAcademyFileByCode(fileCode: string) {
  return http.request<ProductionSafetyFile>({
    url: `/admin/prod/academyFile/queryAcademyFileByCode?fileCode=${fileCode}`,
    method: 'get',
  });
}

/**
 * 查询院级文件列表（不分页）
 */
export function queryAcademyFileList(params?: ProductionSafetyFileQuery, classifyName?: string) {
  return http.request<ProductionSafetyFile[]>({
    url: '/admin/prod/academyFile/queryAcademyFileList',
    method: 'post',
    data: params,
    params: classifyName ? { classifyName } : undefined,
  });
}

/**
 * 分页查询院级文件
 */
export function queryAcademyFilePage(query: ProductionSafetyFilePageQuery, classifyName?: string) {
  return http.request<QueryPageResponse<ProductionSafetyFile>>({
    url: '/admin/prod/academyFile/queryAcademyFilePage',
    method: 'post',
    data: query,
    params: classifyName ? { classifyName } : undefined,
  });
}

/**
 * 导出院级文件
 */
export function exportAcademyFile(params?: ProductionSafetyFileExportQuery, classifyName?: string) {
  return http.request({
    url: '/admin/prod/academyFile/exportAcademyFile',
    method: 'post',
    data: params,
    params: classifyName ? { classifyName } : undefined,
    responseType: 'blob',
  }, {
    isTransformResponse: false,
  });
}

/**
 * 导入院级文件
 */
export function importAcademyFile(file: File) {
  const formData = new FormData();
  formData.append('file', file);
  return http.request<ImportRes>({
    url: '/admin/prod/academyFile/importAcademyFile',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
}

// ==================== 双体系建设管理 (dualSystem) ====================

/**
 * 新增双体系建设
 */
export function saveDualSystem(data: ProductionSafetyFile) {
  return http.request<number>({
    url: '/admin/prod/dualSystem/saveDualSystem',
    method: 'post',
    data,
  });
}

/**
 * 编辑双体系建设
 */
export function updateDualSystem(data: ProductionSafetyFile & { id: number }) {
  return http.request({
    url: '/admin/prod/dualSystem/updateDualSystem',
    method: 'put',
    data,
  });
}

/**
 * 删除双体系建设
 */
export function deleteDualSystem(id: number) {
  return http.request({
    url: `/admin/prod/dualSystem/deleteDualSystem?id=${id}`,
    method: 'delete',
  });
}

/**
 * 根据ID查询双体系建设详情
 */
export function queryDualSystemById(id: number) {
  return http.request<ProductionSafetyFile>({
    url: `/admin/prod/dualSystem/queryDualSystemById?id=${id}`,
    method: 'get',
  });
}

/**
 * 根据文件编号查询双体系建设详情
 */
export function queryDualSystemByCode(fileCode: string) {
  return http.request<ProductionSafetyFile>({
    url: `/admin/prod/dualSystem/queryDualSystemByCode?fileCode=${fileCode}`,
    method: 'get',
  });
}

/**
 * 查询双体系建设列表（不分页）
 */
export function queryDualSystemList(params?: ProductionSafetyFileQuery, classifyName?: string) {
  return http.request<ProductionSafetyFile[]>({
    url: '/admin/prod/dualSystem/queryDualSystemList',
    method: 'post',
    data: params,
    params: classifyName ? { classifyName } : undefined,
  });
}

/**
 * 分页查询双体系建设
 */
export function queryDualSystemPage(query: ProductionSafetyFilePageQuery, classifyName?: string) {
  return http.request<QueryPageResponse<ProductionSafetyFile>>({
    url: '/admin/prod/dualSystem/queryDualSystemPage',
    method: 'post',
    data: query,
    params: classifyName ? { classifyName } : undefined,
  });
}

/**
 * 导出双体系建设
 */
export function exportDualSystem(params?: ProductionSafetyFileExportQuery, classifyName?: string) {
  return http.request({
    url: '/admin/prod/dualSystem/exportDualSystem',
    method: 'post',
    data: params,
    params: classifyName ? { classifyName } : undefined,
    responseType: 'blob',
  }, {
    isTransformResponse: false,
  });
}

/**
 * 导入双体系建设
 */
export function importDualSystem(file: File) {
  const formData = new FormData();
  formData.append('file', file);
  return http.request<ImportRes>({
    url: '/admin/prod/dualSystem/importDualSystem',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
}

// ==================== 行业标准管理 (industryStandard) ====================

/**
 * 新增行业标准
 */
export function saveIndustryStandard(data: ProductionSafetyFile) {
  return http.request<number>({
    url: '/admin/prod/industryStandard/saveIndustryStandard',
    method: 'post',
    data,
  });
}

/**
 * 编辑行业标准
 */
export function updateIndustryStandard(data: ProductionSafetyFile & { id: number }) {
  return http.request({
    url: '/admin/prod/industryStandard/updateIndustryStandard',
    method: 'put',
    data,
  });
}

/**
 * 删除行业标准
 */
export function deleteIndustryStandard(id: number) {
  return http.request({
    url: `/admin/prod/industryStandard/deleteIndustryStandard?id=${id}`,
    method: 'delete',
  });
}

/**
 * 根据ID查询行业标准详情
 */
export function queryIndustryStandardById(id: number) {
  return http.request<ProductionSafetyFile>({
    url: `/admin/prod/industryStandard/queryIndustryStandardById?id=${id}`,
    method: 'get',
  });
}

/**
 * 根据文件编号查询行业标准详情
 */
export function queryIndustryStandardByCode(fileCode: string) {
  return http.request<ProductionSafetyFile>({
    url: `/admin/prod/industryStandard/queryIndustryStandardByCode?fileCode=${fileCode}`,
    method: 'get',
  });
}

/**
 * 查询行业标准列表（不分页）
 */
export function queryIndustryStandardList(params?: ProductionSafetyFileQuery, classifyName?: string) {
  return http.request<ProductionSafetyFile[]>({
    url: '/admin/prod/industryStandard/queryIndustryStandardList',
    method: 'post',
    data: params,
    params: classifyName ? { classifyName } : undefined,
  });
}

/**
 * 分页查询行业标准
 */
export function queryIndustryStandardPage(query: ProductionSafetyFilePageQuery, classifyName?: string) {
  return http.request<QueryPageResponse<ProductionSafetyFile>>({
    url: '/admin/prod/industryStandard/queryIndustryStandardPage',
    method: 'post',
    data: query,
    params: classifyName ? { classifyName } : undefined,
  });
}

/**
 * 导出行业标准
 */
export function exportIndustryStandard(params?: ProductionSafetyFileExportQuery, classifyName?: string) {
  return http.request({
    url: '/admin/prod/industryStandard/exportIndustryStandard',
    method: 'post',
    data: params,
    params: classifyName ? { classifyName } : undefined,
    responseType: 'blob',
  }, {
    isTransformResponse: false,
  });
}

/**
 * 导入行业标准
 */
export function importIndustryStandard(file: File) {
  const formData = new FormData();
  formData.append('file', file);
  return http.request<ImportRes>({
    url: '/admin/prod/industryStandard/importIndustryStandard',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
}

// ==================== 法律法规管理 (lawRegulation) ====================

/**
 * 新增法律法规
 */
export function saveLawRegulation(data: ProductionSafetyFile) {
  return http.request<number>({
    url: '/admin/prod/lawRegulation/saveLawRegulation',
    method: 'post',
    data,
  });
}

/**
 * 编辑法律法规
 */
export function updateLawRegulation(data: ProductionSafetyFile & { id: number }) {
  return http.request({
    url: '/admin/prod/lawRegulation/updateLawRegulation',
    method: 'put',
    data,
  });
}

/**
 * 删除法律法规
 */
export function deleteLawRegulation(id: number) {
  return http.request({
    url: `/admin/prod/lawRegulation/deleteLawRegulation?id=${id}`,
    method: 'delete',
  });
}

/**
 * 根据ID查询法律法规详情
 */
export function queryLawRegulationById(id: number) {
  return http.request<ProductionSafetyFile>({
    url: `/admin/prod/lawRegulation/queryLawRegulationById?id=${id}`,
    method: 'get',
  });
}

/**
 * 根据文件编号查询法律法规详情
 */
export function queryLawRegulationByCode(fileCode: string) {
  return http.request<ProductionSafetyFile>({
    url: `/admin/prod/lawRegulation/queryLawRegulationByCode?fileCode=${fileCode}`,
    method: 'get',
  });
}

/**
 * 查询法律法规列表（不分页）
 */
export function queryLawRegulationList(params?: ProductionSafetyFileQuery, classifyName?: string) {
  return http.request<ProductionSafetyFile[]>({
    url: '/admin/prod/lawRegulation/queryLawRegulationList',
    method: 'post',
    data: params,
    params: classifyName ? { classifyName } : undefined,
  });
}

/**
 * 分页查询法律法规
 */
export function queryLawRegulationPage(query: ProductionSafetyFilePageQuery, classifyName?: string) {
  return http.request<QueryPageResponse<ProductionSafetyFile>>({
    url: '/admin/prod/lawRegulation/queryLawRegulationPage',
    method: 'post',
    data: query,
    params: classifyName ? { classifyName } : undefined,
  });
}

/**
 * 导出法律法规
 */
export function exportLawRegulation(params?: ProductionSafetyFileExportQuery, classifyName?: string) {
  return http.request({
    url: '/admin/prod/lawRegulation/exportLawRegulation',
    method: 'post',
    data: params,
    params: classifyName ? { classifyName } : undefined,
    responseType: 'blob',
  }, {
    isTransformResponse: false,
  });
}

/**
 * 导入法律法规
 */
export function importLawRegulation(file: File) {
  const formData = new FormData();
  formData.append('file', file);
  return http.request<ImportRes>({
    url: '/admin/prod/lawRegulation/importLawRegulation',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
}

// ==================== 安全标准化体系建设管理 (safetyStandardization) ====================

/**
 * 新增安全标准化体系建设
 */
export function saveSafetyStandardization(data: ProductionSafetyFile) {
  return http.request<number>({
    url: '/admin/prod/safetyStandardization/saveSafetyStandardization',
    method: 'post',
    data,
  });
}

/**
 * 编辑安全标准化体系建设
 */
export function updateSafetyStandardization(data: ProductionSafetyFile & { id: number }) {
  return http.request({
    url: '/admin/prod/safetyStandardization/updateSafetyStandardization',
    method: 'put',
    data,
  });
}

/**
 * 删除安全标准化体系建设
 */
export function deleteSafetyStandardization(id: number) {
  return http.request({
    url: `/admin/prod/safetyStandardization/deleteSafetyStandardization?id=${id}`,
    method: 'delete',
  });
}

/**
 * 根据ID查询安全标准化体系建设详情
 */
export function querySafetyStandardizationById(id: number) {
  return http.request<ProductionSafetyFile>({
    url: `/admin/prod/safetyStandardization/querySafetyStandardizationById?id=${id}`,
    method: 'get',
  });
}

/**
 * 根据文件编号查询安全标准化体系建设详情
 */
export function querySafetyStandardizationByCode(fileCode: string) {
  return http.request<ProductionSafetyFile>({
    url: `/admin/prod/safetyStandardization/querySafetyStandardizationByCode?fileCode=${fileCode}`,
    method: 'get',
  });
}

/**
 * 查询安全标准化体系建设列表（不分页）
 */
export function querySafetyStandardizationList(params?: ProductionSafetyFileQuery, classifyName?: string) {
  return http.request<ProductionSafetyFile[]>({
    url: '/admin/prod/safetyStandardization/querySafetyStandardizationList',
    method: 'post',
    data: params,
    params: classifyName ? { classifyName } : undefined,
  });
}

/**
 * 分页查询安全标准化体系建设
 */
export function querySafetyStandardizationPage(query: ProductionSafetyFilePageQuery, classifyName?: string) {
  return http.request<QueryPageResponse<ProductionSafetyFile>>({
    url: '/admin/prod/safetyStandardization/querySafetyStandardizationPage',
    method: 'post',
    data: query,
    params: classifyName ? { classifyName } : undefined,
  });
}

/**
 * 导出安全标准化体系建设
 */
export function exportSafetyStandardization(params?: ProductionSafetyFileExportQuery, classifyName?: string) {
  return http.request({
    url: '/admin/prod/safetyStandardization/exportSafetyStandardization',
    method: 'post',
    data: params,
    params: classifyName ? { classifyName } : undefined,
    responseType: 'blob',
  }, {
    isTransformResponse: false,
  });
}

/**
 * 导入安全标准化体系建设
 */
export function importSafetyStandardization(file: File) {
  const formData = new FormData();
  formData.append('file', file);
  return http.request<ImportRes>({
    url: '/admin/prod/safetyStandardization/importSafetyStandardization',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
}

// ==================== 检查单模版管理 (checklistTemplate) 接口基础路径: /api/checklistTemplate ====================

/** 检查单模板明细子表 */
export interface ChecklistTemplateItem {
  id?: number;
  templateId?: number;
  checkContent?: string; // 检查内容
  checkStandard?: string; // 检查标准
  checkResult?: string; // 检查结果：合格/不合格/待检
  checkProblem?: string; // 检查发现问题
  isDeleted?: number; // 删除标识（0-未删除，>0-已删除）
  createdAt?: string;
  updatedAt?: string;
}

/** 检查单模版列表项 (ChecklistTemplatePageRes) */
export interface ChecklistTemplatePageItem {
  id?: number;
  templateName?: string;
  moduleName?: string;
  status?: number; // 0-禁用，1-启用，2-草稿
  categoryName?: string;
  categoryCode?: string;
  useCount?: number;
  remark?: string;
  updateUserName?: string;
  businessWork?: string;
  fillInstruction?: string;
}

/** 检查单模版查询条件 */
export interface ChecklistTemplateQuery {
  templateName?: string; // 搜索检查单模版名称
  status?: boolean; // true=启用，false=禁用（接口文档为Boolean，实际可传number兼容）
  startDate?: string; // 上传日期范围-开始
  endDate?: string; // 上传日期范围-结束
}

/** 检查单模版保存/编辑请求 (SaveChecklistTemplateReq) */
export interface SaveChecklistTemplateReq {
  id?: number;
  templateName: string;
  categoryName?: string;
  categoryCode?: string;
  businessWork: string;
  fillInstruction: string;
  ChecklistTemplateItem?: ChecklistTemplateItem[];
  status?: number; // 0-禁用，1-启用，2-草稿
}

/** 分页查询请求 - 响应含 pageNumber/pageSize/total/totalPage/records */
interface ChecklistTemplatePageQuery {
  pageNumber?: number;
  pageSize?: number;
  queryParam?: ChecklistTemplateQuery;
}

interface ChecklistTemplatePageRes {
  pageNumber: number;
  pageSize: number;
  total: number;
  totalPage: number;
  records: ChecklistTemplatePageItem[];
}

/** 检查单模版实体（用于名称下拉等场景，后端返回 WebResult<List<ChecklistTemplate>>） */
export type ChecklistTemplate = ChecklistTemplatePageItem;

/** 一、查询检查单模版管理列表 */
export function queryChecklistTemplateList(query: ChecklistTemplatePageQuery) {
  return http.request<ChecklistTemplatePageRes>({
    url: '/checklistTemplate/queryChecklistTemplateList',
    method: 'post',
    data: query,
  });
}

/** 查询检查单模版名称列表（区域检查计划管理-管理员-详情检查单模版名称下拉） */
export function queryCheckListTemplateNameList() {
  // 后端说明：请求体空对象，请求方式 POST，返回 WebResult<List<ChecklistTemplate>>
  // 经过 http 拦截器转换后，这里拿到的就是 List<ChecklistTemplate>
  return http.request<ChecklistTemplate[]>({
    url: `${ADMIN_BASE}/queryCheckListTemplateNameList`,
    method: 'post',
    data: {},
  });
}

/** 二、删除检查单模版管理 */
export function deleteChecklistTemplate(id: number) {
  return http.request({
    url: `/checklistTemplate/deleteChecklistTemplate?id=${id}`,
    method: 'delete',
  });
}

/** 三、删除检查单模版明细 */
export function deleteChecklistTemplateItem(id: number) {
  return http.request({
    url: `/checklistTemplate/deleteChecklistTemplateItem?id=${id}`,
    method: 'delete',
  });
}

/** 四、编辑检查单模版管理 */
export function updateChecklistTemplate(data: SaveChecklistTemplateReq) {
  return http.request<number>({
    url: '/checklistTemplate/updateChecklistTemplate',
    method: 'put',
    data,
  });
}

/** 五、新增检查单模版管理 */
export function saveChecklistTemplate(data: Omit<SaveChecklistTemplateReq, 'id'>) {
  return http.request({
    url: '/checklistTemplate/saveChecklistTemplate',
    method: 'post',
    data,
  });
}

/** 六、查询检查单模版管理详情 */
export function queryChecklistTemplateDetail(id: number) {
  return http.request<SaveChecklistTemplateReq>({
    url: `/checklistTemplate/queryChecklistTemplateDetail?id=${id}`,
    method: 'post',
  });
}

/** 七、批量导入检查单模板明细子表 */
export function importChecklistTemplateItem(file: File, id: string | number) {
  const formData = new FormData();
  formData.append('file', file);
  formData.append('id', String(id));
  return http.request({
    url: '/checklistTemplate/importChecklistTemplateItem',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
}

// ==================== 区域检查计划管理 areaCheckPlanManage ====================
// 接口基础路径：Admin /api/areaCheckPlanManageAdmin | Dept /api/areaCheckPlanManageDept

/** 区域检查计划状态：0=未开始 1=进行中 2=已完成 3=已终止 */
export type AreaCheckPlanStatus = 0 | 1 | 2 | 3;

/** 检查频次映射：0=每日 1=每周 2=每月 3=每季度 4=每半年 5=每年 */
const FREQUENCY_TO_LABEL: Record<number, string> = {
  0: '每日',
  1: '每周',
  2: '每月',
  3: '每季度',
  4: '每半年',
  5: '每年',
};
const LABEL_TO_FREQUENCY: Record<string, number> = {
  每日: 0,
  每周: 1,
  每月: 2,
  每季度: 3,
  每半年: 4,
  每年: 5,
};

/** 后端 API 返回的区域检查计划记录格式（与接口文档 DTO 对齐：*Name/*Code） */
interface AreaCheckPlanManageApiRecord {
  id?: number; // 主键ID
  areaCheckPlanName?: string; // 区域检查计划名称
  checkPlace?: string; // 检查场所
  checkPlaceCategory?: string; // 检查场所所属类别
  checkCategory?: string; // 检查类别
  status?: number | string; // 状态：0=未开始 1=进行中 2=已完成 3=已终止
  /** save/update 请求体使用：主责部门名称 */
  primaryResponsibleDeptName?: string;
  /** save/update 请求体使用：主责部门 code */
  primaryResponsibleDeptCode?: string;
  responsibleDeptName?: string; // 主责部门名称（兼容后端返回）
  responsibleDeptCode?: string; // 主责部门code（兼容后端返回）
  selfCheckFrequency?: number | string; // 自查频次：0=每日 1=每周 2=每月 3=每季度 4=每半年 5=每年
  responsibleDeptExecGroupName?: string; // 主责部门执行人所属分组名称
  responsibleDeptExecGroupCode?: string; // 主责部门执行人所属分组code
  responsibleDeptPersonName?: string; // 主责部门责任人名称
  responsibleDeptPersonCode?: string; // 主责部门责任人code
  safetyEmergencyDeptName?: string; // 安全应急部门名称
  safetyEmergencyDeptCode?: string; // 安全应急部门code
  safetyEmergencyCheckFrequency?: number | string; // 安全应急部检查频次
  safetyEmergencyExecGroupName?: string; // 安全应急部执行人所属分组名称
  safetyEmergencyExecGroupCode?: string; // 安全应急部执行人所属分组code
  safetyEmergencyPersonName?: string; // 安全应急部责任人名称
  safetyEmergencyPersonCode?: string; // 安全应急部责任人code
  hospitalLeaderDeptName?: string; // 院领导部门名称
  hospitalLeaderDeptCode?: string; // 院领导部门code
  hospitalLeaderCheckFrequency?: number | string; // 院领导检查频次
  hospitalLeaderExecGroupName?: string; // 院领导执行人所属分组名称
  hospitalLeaderExecGroupCode?: string; // 院领导执行人所属分组code
  hospitalLeaderPersonName?: string; // 院领导责任人名称
  hospitalLeaderPersonCode?: string; // 院领导责任人code
  categoryName?: string; // 检查单模版类别名称
  categoryCode?: string; // 检查单模版类别 code
  checklistTemplateName?: string; // 检查单模版名称
  checkKeyContent?: string; // 检查重点内容
  needOverallDesc?: number | string; // 是否需要整体检查情况描述：0=否 1=是
  needSigneeSign?: number | string; // 是否需要被检查人签字：0=否 1=是
  planStartTime?: string; // 计划开始时间
  planEndTime?: string; // 计划结束时间
  isDeleted?: number | string; // 软删除：0=未删除，大于0(时间戳)=已删除
  createdAt?: string; // 创建时间
  updatedAt?: string; // 更新时间
  /** 兼容旧字段名 */
  responsibleDept?: string;
  responsibleDeptExecGroup?: string;
  responsibleDeptPerson?: string;
  safetyEmergencyDept?: string;
  safetyEmergencyExecGroup?: string;
  safetyEmergencyPerson?: string;
  hospitalLeaderDept?: string;
  hospitalLeaderExecGroup?: string;
  hospitalLeaderPerson?: string;
  [key: string]: unknown;
}

/** UI 使用的区域检查计划记录格式（与表格、表单一致） */
export interface AreaCheckPlanRecord {
  id?: number;
  checkVenue?: string;
  status?: AreaCheckPlanStatus;
  venueCategoryName?: string;
  planName?: string;
  primaryResponsibleDeptName?: string;
  primaryResponsibleDeptCode?: string;
  selfCheckFrequency?: string;
  mainDeptExecutorGroupName?: string;
  mainDeptExecGroupCode?: string;
  mainDeptResponsiblePerson?: string;
  mainDeptResponsiblePersonCode?: string;
  safetyEmergencyDeptName?: string;
  safetyEmergencyDeptCode?: string;
  safetyEmergencyCheckFrequency?: string;
  safetyEmergencyExecutorGroupName?: string;
  safetyEmergencyExecGroupCode?: string;
  safetyEmergencyResponsiblePerson?: string;
  safetyEmergencyPersonCode?: string;
  hospitalLeaderDeptName?: string;
  hospitalLeaderDeptCode?: string;
  hospitalLeaderCheckFrequency?: string;
  hospitalLeaderExecutorGroupName?: string;
  hospitalLeaderExecGroupCode?: string;
  hospitalLeaderResponsiblePerson?: string;
  hospitalLeaderPersonCode?: string;
  checkKeyContent?: string;
  categoryName?: string;
  categoryCode?: string;
  checklistTemplateName?: string;
  needOverallDesc?: boolean;
  needSigneeSign?: boolean;
  planStartTime?: string;
  planEndTime?: string;
  isDeleted?: number | string;
  createdAt?: string;
  updatedAt?: string;
  [key: string]: unknown;
}

/** 后端返回格式转 UI 格式，供调用方使用（优先 *Name，兼容旧 *Dept/*Person） */
export function mapAreaCheckPlanApiRecordToUi(api: AreaCheckPlanManageApiRecord | null | undefined): AreaCheckPlanRecord {
  if (!api) return {};
  const toBool = (v: number | string | undefined) => (v === 1 || v === '1' ? true : v === 0 || v === '0' ? false : undefined);
  const toFreq = (v: number | string | undefined) => {
    if (v === undefined || v === null || v === '') return undefined;
    const n = typeof v === 'number' ? v : parseInt(String(v), 10);
    return FREQUENCY_TO_LABEL[n] ?? String(v);
  };
  return {
    id: api.id,
    planName: api.areaCheckPlanName,
    checkVenue: api.checkPlace,
    createdPersonName: api.createdPersonName,
    venueCategoryName: api.checkPlaceCategory ?? api.checkCategory,
    status: api.status as AreaCheckPlanStatus | undefined,
    primaryResponsibleDeptName: api.primaryResponsibleDeptName ?? api.responsibleDeptName ?? api.responsibleDept,
    primaryResponsibleDeptCode: api.primaryResponsibleDeptCode ?? api.responsibleDeptCode,
    selfCheckFrequency: toFreq(api.selfCheckFrequency),
    mainDeptExecutorGroupName: api.responsibleDeptExecGroupName ?? api.responsibleDeptExecGroup,
    mainDeptExecGroupCode: api.responsibleDeptExecGroupCode,
    mainDeptResponsiblePerson: api.responsibleDeptPersonName ?? api.responsibleDeptPerson,
    mainDeptResponsiblePersonCode: api.responsibleDeptPersonCode,
    safetyEmergencyDeptName: api.safetyEmergencyDeptName ?? api.safetyEmergencyDept,
    safetyEmergencyDeptCode: api.safetyEmergencyDeptCode,
    safetyEmergencyCheckFrequency: toFreq(api.safetyEmergencyCheckFrequency),
    safetyEmergencyExecutorGroupName: api.safetyEmergencyExecGroupName ?? api.safetyEmergencyExecGroup,
    safetyEmergencyResponsiblePerson: api.safetyEmergencyPersonName ?? api.safetyEmergencyPerson,
    safetyEmergencyExecGroupCode: api.safetyEmergencyExecGroupCode,
    safetyEmergencyPersonCode: api.safetyEmergencyPersonCode,
    hospitalLeaderDeptName: api.hospitalLeaderDeptName ?? api.hospitalLeaderDept,
    hospitalLeaderDeptCode: api.hospitalLeaderDeptCode,
    hospitalLeaderCheckFrequency: toFreq(api.hospitalLeaderCheckFrequency),
    hospitalLeaderExecutorGroupName: api.hospitalLeaderExecGroupName ?? api.hospitalLeaderExecGroup,
    hospitalLeaderResponsiblePerson: api.hospitalLeaderPersonName ?? api.hospitalLeaderPerson,
    hospitalLeaderExecGroupCode: api.hospitalLeaderExecGroupCode,
    hospitalLeaderPersonCode: api.hospitalLeaderPersonCode,
    categoryName: api.categoryName,
    categoryCode: api.categoryCode,
    checklistTemplateName: api.checklistTemplateName,
    checkKeyContent: api.checkKeyContent,
    needOverallDesc: toBool(api.needOverallDesc),
    needSigneeSign: toBool(api.needSigneeSign),
    planStartTime: api.planStartTime,
    planEndTime: api.planEndTime,
    isDeleted: api.isDeleted,
    createdAt: api.createdAt,
    updatedAt: api.updatedAt,
    primaryResponsibleDeptExecGroupName: api.primaryResponsibleDeptExecGroupName,
    primaryResponsibleDeptPersonName: api.primaryResponsibleDeptPersonName,
    safetyEmergencyExecGroupName: api.safetyEmergencyExecGroupName,
    safetyEmergencyPersonName: api.safetyEmergencyPersonName,
    hospitalLeaderExecGroupName: api.hospitalLeaderExecGroupName,
    hospitalLeaderPersonName: api.hospitalLeaderPersonName,
    businessWork: api.businessWork,
  };
}

function uiRecordToApi(ui: AreaCheckPlanRecord & { id?: number }): AreaCheckPlanManageApiRecord {
  const toFreqNum = (v: string | undefined) => (v ? LABEL_TO_FREQUENCY[v] ?? undefined : undefined);
  const toNum = (v: boolean | undefined) => (v === true ? 1 : v === false ? 0 : undefined);
  const code = (ui as Record<string, unknown>);
  const primaryResponsibleDeptCode = (code.primaryResponsibleDeptCode as string | undefined)
    ?? (code.primaryResponsibleDeptId != null ? String(code.primaryResponsibleDeptId) : undefined);
  return {
    id: ui.id,
    areaCheckPlanName: ui.planName,
    checkPlace: ui.checkVenue,
    checkPlaceCategory: ui.venueCategoryName,
    primaryResponsibleDeptName: ui.primaryResponsibleDeptName,
    primaryResponsibleDeptCode,
    selfCheckFrequency: toFreqNum(ui.selfCheckFrequency),
    responsibleDeptExecGroupName: ui.mainDeptExecutorGroupName,
    responsibleDeptExecGroupCode: code.mainDeptExecGroupCode as string | undefined,
    responsibleDeptPersonName: ui.mainDeptResponsiblePerson,
    responsibleDeptPersonCode: code.mainDeptResponsiblePersonCode as string | undefined,
    safetyEmergencyDeptName: ui.safetyEmergencyDeptName,
    // 若 safetyEmergencyDeptCode 为空，则回退使用 safetyEmergencyDeptId 作为 code
    safetyEmergencyDeptCode: (code.safetyEmergencyDeptCode as string | undefined)
      ?? (code.safetyEmergencyDeptId != null ? String(code.safetyEmergencyDeptId) : undefined),
    safetyEmergencyCheckFrequency: toFreqNum(ui.safetyEmergencyCheckFrequency),
    safetyEmergencyExecGroupName: ui.safetyEmergencyExecutorGroupName,
    safetyEmergencyExecGroupCode: code.safetyEmergencyExecGroupCode as string | undefined,
    safetyEmergencyPersonName: ui.safetyEmergencyResponsiblePerson,
    safetyEmergencyPersonCode: code.safetyEmergencyPersonCode as string | undefined,
    hospitalLeaderDeptName: ui.hospitalLeaderDeptName,
    // 若 hospitalLeaderDeptCode 为空，则回退使用 hospitalLeaderDeptId 作为 code
    hospitalLeaderDeptCode: (code.hospitalLeaderDeptCode as string | undefined)
      ?? (code.hospitalLeaderDeptId != null ? String(code.hospitalLeaderDeptId) : undefined),
    hospitalLeaderCheckFrequency: toFreqNum(ui.hospitalLeaderCheckFrequency),
    hospitalLeaderExecGroupName: ui.hospitalLeaderExecutorGroupName,
    hospitalLeaderExecGroupCode: code.hospitalLeaderExecGroupCode as string | undefined,
    hospitalLeaderPersonName: ui.hospitalLeaderResponsiblePerson,
    hospitalLeaderPersonCode: code.hospitalLeaderPersonCode as string | undefined,
    categoryName: ui.categoryName,
    categoryCode: code.categoryCode as string | undefined,
    checklistTemplateName: ui.checklistTemplateName,
    checkKeyContent: ui.checkKeyContent,
    needOverallDesc: toNum(ui.needOverallDesc),
    needSigneeSign: toNum(ui.needSigneeSign),
    planStartTime: ui.planStartTime,
    planEndTime: ui.planEndTime,
    status: ui.status as number | undefined,
  };
}

export interface AreaCheckPlanQuery {
  keyword?: string;
  /** 与 queryParam.searchKey 一致，搜索检查场所/计划名称 */
  searchKey?: string;
  areaCheckPlanName?: string;
  status?: AreaCheckPlanStatus | '';
  venueCategory?: string;
  planStartTime?: string;
  planEndTime?: string;
  /** 计划日期范围-开始，与 queryParam.startDate 一致 */
  startDate?: string;
  /** 计划日期范围-结束，与 queryParam.endDate 一致 */
  endDate?: string;
}

/** 分页查询请求体（后端 queryParam 格式） */
interface AreaCheckPlanManagePageReq {
  searchKey?: string;
  areaCheckPlanName?: string;
  status?: string | number;
  checkPlaceCategory?: string;
  startDate?: string;
  endDate?: string;
}

interface AreaCheckPlanManagePageQuery {
  pageNumber: number;
  pageSize: number;
  queryParam?: AreaCheckPlanManagePageReq;
}

interface AreaCheckPlanManagePageRes {
  records?: AreaCheckPlanManageApiRecord[]; // 当前页记录列表
  pageNumber?: number; // 页号，默认值为1
  pageSize?: number; // 每页数量
  maxPageSize?: number; // 最大每页数量
  totalPage?: number; // 总页数
  totalRow?: number; // 总行数
  optimizeCountQuery?: boolean; // 是否优化计数查询
}

function buildPageQuery(uiQuery: { pageNumber: number; pageSize: number; queryParam?: AreaCheckPlanQuery }): AreaCheckPlanManagePageQuery {
  const q = uiQuery.queryParam ?? {};
  return {
    pageNumber: uiQuery.pageNumber ?? 1,
    pageSize: uiQuery.pageSize ?? 10,
    queryParam: {
      searchKey: q.searchKey ?? q.keyword ?? undefined,
      areaCheckPlanName: q.areaCheckPlanName ?? undefined,
      status: q.status === '' ? undefined : (q.status as number),
      checkPlaceCategory: q.venueCategory ?? undefined,
      startDate: q.startDate ?? q.planStartTime ?? undefined,
      endDate: q.endDate ?? q.planEndTime ?? undefined,
      id: q.id ?? undefined,
    },
  };
}

const ADMIN_BASE = 'areaCheckPlanManageAdmin';
const DEPT_BASE = 'areaCheckPlanManageDept';

/** 分页查询区域检查计划列表（管理员） */
export function queryAreaCheckPlanManagePage(query: { pageNumber: number; pageSize: number; queryParam?: AreaCheckPlanQuery }) {
  return http.request<AreaCheckPlanManagePageRes>({
    url: `${ADMIN_BASE}/queryAreaCheckPlanManagePage`,
    method: 'post',
    data: buildPageQuery(query),
  });
}

/** 分页查询区域检查计划列表（部门） */
export function queryAreaCheckPlanManageDeptPage(query: Parameters<typeof queryAreaCheckPlanManagePage>[0]) {
  return http.request<AreaCheckPlanManagePageRes>({
    url: `${DEPT_BASE}/queryAreaCheckPlanManagePage`,
    method: 'post',
    data: buildPageQuery(query),
  });
}

/** 删除区域检查计划（管理员） */
export function deleteAreaCheckPlanManage(id: number) {
  return http.request({
    url: `${ADMIN_BASE}/deleteAreaCheckPlanManage?id=${id}`,
    method: 'delete',
  });
}

/** 删除区域检查计划（部门）- 若部门无此接口则复用管理员 */
export function deleteAreaCheckPlanManageDept(id: number) {
  return http.request({
    url: `${DEPT_BASE}/deleteAreaCheckPlanManage?id=${id}`,
    method: 'delete',
  });
}

/** 新增区域检查计划（管理员） */
export function saveAreaCheckPlanManage(data: AreaCheckPlanRecord) {
  return http.request({
    url: `${ADMIN_BASE}/saveAreaCheckPlanManage`,
    method: 'post',
    data: uiRecordToApi(data),
  });
}

/** 更新区域检查计划（管理员） */
export function updateAreaCheckPlanManage(data: AreaCheckPlanRecord & { id: number }) {
  return http.request({
    url: `${ADMIN_BASE}/updateAreaCheckPlanManage`,
    method: 'put',
    data: uiRecordToApi(data),
  });
}

/** 新增区域检查计划（部门） */
export function saveAreaCheckPlanManageDept(data: AreaCheckPlanRecord) {
  return http.request({
    url: `${DEPT_BASE}/saveAreaCheckPlanManage`,
    method: 'post',
    data: uiRecordToApi(data),
  });
}

/** 更新区域检查计划（部门） */
export function updateAreaCheckPlanManageDept(data: AreaCheckPlanRecord & { id: number }) {
  return http.request({
    url: `${DEPT_BASE}/updateAreaCheckPlanManage`,
    method: 'put',
    data: uiRecordToApi(data),
  });
}

/** 根据ID查询区域检查计划详情（管理员） */
export function queryAreaCheckPlanManageDetail(id: number) {
  return http.request<AreaCheckPlanManageApiRecord>({
    url: `${ADMIN_BASE}/queryAreaCheckPlanManageDetail?id=${id}`,
    method: 'post',
    // params: { id },
  });
}

/** 根据ID查询区域检查计划详情（部门） */
export function queryAreaCheckPlanManageDeptDetail(id: number) {
  return http.request<AreaCheckPlanManageApiRecord>({
    url: `${DEPT_BASE}/queryAreaCheckPlanManageDetail?id=${id}`,
    method: 'post',
    // params: { id },
  });
}

/** 下发区域检查计划至部门（sandAreaCheckPlanToDep）请求体：责任部门、责任部门人员分组使用指定字段名 */
export interface SendAreaCheckPlanToDepReq {
  id: number;
  /** 责任部门名称（多选逗号拼接） */
  responsibleDeptName?: string;
  /** 责任部门 code（多选逗号拼接） */
  responsibleDeptCode?: string;
  /** 责任部门人员分组名称 */
  responsibleDeptPersonnelGroupName?: string;
  /** 责任部门人员分组 code */
  responsibleDeptPersonnelGroupCode?: string;
  safetyEmergencyDeptName?: string;
  safetyEmergencyDeptId?: number;
  safetyEmergencyExecutorGroupName?: string;
  safetyEmergencyExecGroupCode?: string;
  hospitalLeaderDeptName?: string;
  hospitalLeaderDeptId?: number;
  hospitalLeaderExecutorGroupName?: string;
  hospitalLeaderExecGroupCode?: string;
  planStartTime?: string;
  planEndTime?: string;
  needOverallDesc?: boolean;
  needInspectedSign?: boolean;
  [key: string]: unknown;
}

/** 下发区域检查计划至部门（管理员） */
export function sendAreaCheckPlanToDep(data: SendAreaCheckPlanToDepReq) {
  return http.request({
    url: `areaCheckPlanManageAdmin/sandAreaCheckPlanToDep`,
    method: 'post',
    data,
  });
}

/** 区域检查计划管理(管理员) - 检查记录下入账至隐患台账 */
export interface SandAreaCheckRecordToHiddenDangerReq {
  /** 主键ID，自增 */
  id?: number;
  /** 区域检查记录ID（与 sourceRefId 一致，用于显式标记来源记录） */
  areaCheckRecordId: number;
  /** 数据来源：1员工上报 2台账新增 3台账导入 4区域检查 */
  sourceType: number;
  /** 来源记录ID，例如员工上报ID/导入批次ID/检查记录ID */
  sourceRefId: number;
  /** 隐患编号 */
  dangerCode?: string;
  /** 隐患问题类别ID */
  typeId?: number;
  /** 部门ID列表（扣分部门选择），逗号分隔 */
  departmentIds?: string;
  /** 隐患问题 */
  dangerProblem: string;
  /** 隐患原因ID */
  reasonId?: number;
  /** 任务来源 */
  taskSource?: string;
  /** 整改要求 */
  rectificationRequirement?: string;
  /** 整改期限（yyyy-MM-dd） */
  rectificationDeadline?: string;
  /** 整改责任部门ID列表，逗号分隔 */
  rectificationDepartmentIds?: string;
  /** 整改负责人 */
  rectificationResponsiblePerson?: string;
  /** 整改负责人ID，逗号分隔 */
  rectificationResponsibleIds?: string;
  /** 复查人员所属部门ID */
  reviewDepartmentId?: number;
  /** 复查人员ID */
  reviewPersonId?: number;
  /** 复查人员姓名 */
  reviewPersonName?: string;
  /** 举一反三是否推送，1-是，0-否 */
  isDrawLessonsPush?: number;
  /** 举一反三内容 */
  drawLessonsContent?: string;
  /** 举一反三责任部门ID列表，逗号分隔 */
  drawLessonsDepartmentIds?: string;
  /** 举一反三时限（yyyy-MM-dd） */
  drawLessonsDeadline?: string;
  /** 举一反三记录ID */
  associationOtId?: number;
  /** 隐患状态ID */
  statusId?: number;
  /** 当前流程节点 */
  currentNode?: string;
  /** 创建人ID */
  creatorId?: number;
  /** 创建人名称 */
  creatorName?: string;
  /** 创建时间（yyyy-MM-dd HH:mm:ss） */
  createdAt?: string;
  /** 更新时间（yyyy-MM-dd HH:mm:ss） */
  updatedAt?: string;
  /** 整改完成情况 */
  rectificationCompletionStatus?: string;
  /** 整改完成时间（yyyy-MM-dd） */
  rectificationCompletionTime?: string;
  /** 附件，通常为URL/ID列表，逗号分隔 */
  attachments?: string;
  /** 软删除：0-未删除，大于0(时间戳)-已删除 */
  isDeleted?: number;
}

export function sandAreaCheckRecordToProductionHiddenDanger(data: SandAreaCheckRecordToHiddenDangerReq) {
  return http.request({
    url: `${ADMIN_BASE}/sandAreaCheckRecordToProductionHiddenDanger`,
    method: 'post',
    data,
  });
}

/** 作废接口（管理员）：/areaCheckPlanManageAdmin/updateStatusAreaCheckPlanManage POST，仅需传 id */
export function cancelAreaCheckPlanManage(id: number) {
  return http.request({
    url: `${ADMIN_BASE}/updateStatusAreaCheckPlanManage?id=${id}`,
    method: 'delete',
  });
}

/** 查询区域检查计划关联的检查记录分页（管理员）- 与接口文档 DTO 对齐 */
export interface AreaCheckPlanDetailRecord {
  id?: number;
  areaPlanId?: number;
  checkTime?: string;
  checkPersonName?: string;
  checkPersonCode?: string;
  checkPerson?: string;
  checkPlaceCategory?: string;
  checkPlaceCategoryCode?: string;
  checkPlace?: string;
  checkAddress?: string;
  checkItemTotal?: number;
  qualifiedItemNum?: number;
  unqualifiedItemNum?: number;
  checkedCompanyName?: string;
  checkedCompanyCode?: string;
  checkedCompany?: string;
  overallCheckDesc?: string;
  checkedPersonSign?: string;
}

export function queryAreaCheckPlanDetailPage(planId: number, query: { pageNumber: number; pageSize: number; queryParam?: AreaCheckPlanQuery }) {
  const body = buildPageQuery(query);
  return http.request<AreaCheckPlanManagePageRes & { records?: AreaCheckPlanDetailRecord[] }>({
    url: `${ADMIN_BASE}/queryAreaCheckPlanDetailPage`,
    method: 'post',
    params: { id: planId },
    data: body,
  });
}

/** 查询区域检查计划关联的检查记录分页（部门） */
export function queryAreaCheckPlanDetailDeptPage(planId: number, query: Parameters<typeof queryAreaCheckPlanDetailPage>[1]) {
  const body = buildPageQuery(query);
  return http.request({
    url: `${DEPT_BASE}/queryAreaCheckPlanDetailPage`,
    method: 'post',
    params: { id: planId },
    data: body,
  });
}

/** 删除区域检查计划记录（管理员） */
export function deleteAreaCheckPlanDetail(id: number) {
  return http.request({
    url: `${ADMIN_BASE}/deleteAreaCheckPlanDetail?id=${id}`,
    method: 'delete',
  });
}

/** 删除区域检查计划记录（部门） */
export function deleteAreaCheckPlanDetailDept(id: number) {
  return http.request({
    url: `${DEPT_BASE}/deleteAreaCheckPlanDetail?id=${id}`,
    method: 'delete',
  });
}

/** 查看区域检查计划记录详情（含 areaCheckRecords 子项，与接口文档 AreaCheckPlanDetailRes 对齐） */
export interface AreaCheckRecordDetail {
  id?: number;
  areaPlanId?: number;
  checkTime?: string;
  checkPersonName?: string;
  checkPersonCode?: string;
  checkPerson?: string;
  checkPlaceCategory?: string;
  checkPlaceCategoryCode?: string;
  checkPlace?: string;
  checkAddress?: string;
  checkItemTotal?: number;
  qualifiedItemNum?: number;
  unqualifiedItemNum?: number;
  checkedCompanyName?: string;
  checkedCompanyCode?: string;
  checkedCompany?: string;
  overallCheckDesc?: string;
  checkedPersonSign?: string;
  areaCheckRecords?: Array<{
    id?: number;
    checkPlanId?: number;
    checkContent?: string;
    checkStandard?: string;
    checkResult?: string;
    checkProblem?: string;
    isDeleted?: number;
    createdAt?: string;
    updatedAt?: string;
  }>;
  isDeleted?: number;
  createdAt?: string;
  updatedAt?: string;
}

export function queryAreaCheckRecord(id: number) {
  return http.request<AreaCheckRecordDetail>({
    url: `${ADMIN_BASE}/queryAreaCheckRecord?id=${id}`,
    method: 'post',
    // params: { id },
  });
}

/** 查看区域检查计划记录详情（部门） */
export function queryAreaCheckRecordDept(id: number) {
  return http.request<AreaCheckRecordDetail>({
    url: `${DEPT_BASE}/queryAreaCheckRecord?id=${id}`,
    method: 'post',
    // params: { id },
  });
}

/** 区域检查计划管理(部门) - 新增检查日志时的检查明细模板 item */
export interface AreaCheckRecordTemplateItem {
  id?: number; // 主键ID，自增
  checkPlanId?: number; // 关联检查计划ID（外键，对应 area_check_plan_detail.id）
  checkContent?: string; // 检查内容
  checkStandard?: string; // 检查标准
  checkResult?: string; // 检查结果：合格/不合格
  checkProblem?: string; // 检查发现问题：目前不存在问题/隐患问题未整改到位
  isSand?: number; // 0-未入账，1-已入账
  isDeleted?: number; // 0-未删除，大于0(时间戳)-已删除
  createdAt?: string; // 创建时间
  updatedAt?: string; // 更新时间
}

/** 区域检查计划管理(部门) - 新增检查日志的检查明细模板列表 */
export function queryAreaCheckRecordTemplateDept(id: number) {
  return http.request<AreaCheckRecordTemplateItem[]>({
    url: `${DEPT_BASE}/queryAreaCheckRecordTemplate?id=${id}`,
    method: 'post',
  });
}

/** 区域检查计划管理(部门) - 新增检查日志提交体 */
export interface SaveAreaCheckPlanDetailDeptReq {
  areaPlanId: number; // 关联区域计划ID（外键对应 area_check_plan_manage.id）
  checkTime: string; // 检查时间
  checkPersonName: string; // 检查人员名称
  checkPersonCode?: string; // 检查人员code
  checkAddress: string; // 检查地点
  overallCheckDesc: string; // 整体检查情况描述（300字）
  checkedPersonSign?: string; // 被检查人签字（PDF文件地址/KEY）
  areaCheckRecords: Array<{
    id?: number;
    checkPlanId?: number;
    checkContent?: string;
    checkStandard?: string;
    checkResult?: string;
    checkProblem?: string;
    isSand?: number;
    isDeleted?: number;
    createdAt?: string;
    updatedAt?: string;
  }>;
}

/** 区域检查计划管理(部门) - 新增检查日志提交 */
export function saveAreaCheckPlanDetailDept(data: SaveAreaCheckPlanDetailDeptReq) {
  return http.request({
    url: `${DEPT_BASE}/saveAreaCheckPlanDetailDept`,
    method: 'post',
    data,
  });
}

/** 不合格项分页查询请求 queryParam（与接口文档 UnqualifiedItemNumPageReq 对齐） */
export interface UnqualifiedItemNumPageQuery {
  id?: number;
  checkPlace?: string;
  checkProblem?: string;
  checkTime?: string;
}

/** 不合格项分页查询单条记录 */
export interface UnqualifiedItemNumRecord {
  id?: number;
  checkPlace?: string;
  checkProblem?: string;
  checkTime?: string;
  isSand?: number; // 0-未入账 1-已入账
}

/** 分页查询记录不合格数据（管理员） */
export function queryUnqualifiedItemNumPage(query: {
  pageNumber: number;
  pageSize: number;
  queryParam?: UnqualifiedItemNumPageQuery;
}) {
  return http.request<{
    records?: UnqualifiedItemNumRecord[];
    totalRow?: number;
    totalPage?: number;
    pageNumber?: number;
    pageSize?: number;
  }>({
    url: `${ADMIN_BASE}/queryUnqualifiedItemNumPage`,
    method: 'post',
    data: {
      pageNumber: query.pageNumber ?? 1,
      pageSize: query.pageSize ?? 10,
      queryParam: query.queryParam ?? {},
    },
  });
}

/** 分页查询记录不合格数据（部门） */
export function queryUnqualifiedItemNumDeptPage(query: Parameters<typeof queryUnqualifiedItemNumPage>[0]) {
  return http.request<{
    records?: UnqualifiedItemNumRecord[];
    totalRow?: number;
    totalPage?: number;
    pageNumber?: number;
    pageSize?: number;
  }>({
    url: `${DEPT_BASE}/queryUnqualifiedItemNumPage`,
    method: 'post',
    data: {
      pageNumber: query.pageNumber ?? 1,
      pageSize: query.pageSize ?? 10,
      queryParam: query.queryParam ?? {},
    },
  });
}

/** 兼容旧命名 - 分页查询 */
export function queryAreaCheckPlanPage(query: Parameters<typeof queryAreaCheckPlanManagePage>[0]) {
  return queryAreaCheckPlanManagePage(query);
}

/** 兼容旧命名 */
export function deleteAreaCheckPlan(id: number) {
  return deleteAreaCheckPlanManage(id);
}

/** 兼容旧命名 - 下发（新接口为 sendAreaCheckPlanToDep，需传入完整计划数据） */
export function issueAreaCheckPlan(data: { planId?: number; id?: number } & Partial<AreaCheckPlanRecord>) {
  const id = data.id ?? data.planId;
  if (!id) throw new Error('计划ID必填');
  return sendAreaCheckPlanToDep({ ...data, id } as AreaCheckPlanRecord & { id: number });
}

/** 兼容旧命名：内部直接调用新的作废接口 */
export function cancelAreaCheckPlan(id: number) {
  return cancelAreaCheckPlanManage(id);
}

/** 兼容旧命名 */
export function queryAreaCheckPlanById(id: number) {
  return queryAreaCheckPlanManageDetail(id);
}

/** 兼容旧命名 */
export function saveAreaCheckPlan(data: AreaCheckPlanRecord) {
  return saveAreaCheckPlanManage(data);
}

/** 兼容旧命名 */
export function updateAreaCheckPlan(data: AreaCheckPlanRecord & { id: number }) {
  return updateAreaCheckPlanManage(data);
}

/**
 * 导出区域检查计划清单
 * @returns Promise<any> 导出的区域检查计划清单数据
 */
export function exportAreaCheckPlanList (params: AreaCheckPlanQuery) {
  return http.request({
    url: '/areaCheckPlanManageDept/exportAreaCheckPlan',
    method: 'post',
    responseType: 'blob',
    data: params,
  }, {
    isTransformResponse: false,
  });
}

/**
 * 导出区域检查计划清单
 * @returns Promise<any> 导出的区域检查计划清单数据
 */
export function exportAreaCheckInspectionRecord (params: AreaCheckPlanQuery) {
  return http.request({
    url: '/areaCheckPlanManageDept/exportAreaCheckPlanDetail',
    method: 'post',
    responseType: 'blob',
    data: params,
  }, {
    isTransformResponse: false,
  });
}

/**
 * 导出区域检查计划管理
 * @returns Promise<any> 导出的区域检查计划管理数据
 */
export function exportAreaCheckPlanAdministration (params: AreaCheckPlanQuery) {
  return http.request({
    url: '/areaCheckPlanManageAdmin/exportAreaCheckPlan',
    method: 'post',
    responseType: 'blob',
    data: params,
  }, {
    isTransformResponse: false,
  });
}

/**
 * 导出区域检查计划管理
 * @returns Promise<any> 导出的区域检查计划管理数据
 */
export function exportInspectionRecordTow (params: AreaCheckPlanQuery) {
  return http.request({
    url: '/areaCheckPlanManageAdmin/exportAreaCheckPlanLog',
    method: 'post',
    responseType: 'blob',
    data: params,
  }, {
    isTransformResponse: false,
  });
}

/** 检查模板下载 */
export function checklistTemplateDownload () {
  return http.request({
    url: '/areaCheckPlanManageAdmin/exportimportCheckListTemplate',
    method: 'get',
    responseType: 'blob',
  }, {
    isTransformResponse: false,
  });
}


/** 检查模板导出 */
export function checklistHandleeTemplateDownload (id: number) {
  return http.request({
    url: '/areaCheckPlanManageAdmin/exportCheckList?id=' + id,
    method: 'get',
    responseType: 'blob',
  }, {
    isTransformResponse: false,
  });
}
