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

/**
 * 举一反三单条记录（与接口文档 DrawLessonsPageRes 一致）
 */
export interface DrawLessonsItem {
  id: number;
  dangerId: number;
  problem: string;
  associationOneThree: string;
  associationOtObligationDeptIds: string;
  associationOtObligationDeptName: string;
  associationOtTimeLimit: string;
  planStartDate?: string;
  attachments?: string;
  statusId: number;
  statusName: string;
  issueCount?: number;
  feedbackCount?: number;
  feedbackRate?: number;
  creatorName?: string;
  createdAt: string;
  updatedAt: string;
  canEdit?: boolean;
  canDelete?: boolean;
  canNotify?: boolean;
  canSend?: boolean;
  canAudit?: boolean;
  canVoid?: boolean;
  canFeedback?: boolean;
}

/**
 * 分页查询 queryParam（与接口文档一致）
 */
export interface DrawLessonsQueryParam {
  dangerId?: number;
  statusId?: number;
  obligationDeptId?: number;
  startTime?: string;
  endTime?: string;
  keyword?: string;
  /** 隐患问题（搜索） */
  problem?: string;
  associationOtId?: number;
  obligationDeptName?: string;
  planStartDate?: string;
  planEndDate?: string;
  searchStatus?: number;
}

/**
 * 2.1 分页查询举一反三
 * POST /api/drawLessons/admin/queryPage
 */
export function queryDrawLessonsAdminPage(
  query: QueryPageRequest<DrawLessonsQueryParam>,
) {
  return http.request<QueryPageResponse<DrawLessonsItem>>({
    url: '/drawLessons/admin/queryPage',
    method: 'post',
    data: query,
  });
}

/**
 * 2.1 分页查询举一反三
 * POST /api/drawLessons/admin/queryPage
 */
export function queryDrawLessonsAdminDeptPage(
  query: QueryPageRequest<DrawLessonsQueryParam>,
) {
  return http.request<QueryPageResponse<DrawLessonsItem>>({
    url: '/drawLessons/dept/queryPage',
    method: 'post',
    data: query,
  });
}

/**
 * 2.2 查询举一反三详情
 * GET /api/drawLessons/admin/queryMainDetail?id=xxx
 */
export function getDrawLessonsAdminDetail(id: number) {
  return http.request<DrawLessonsItem>({
    url: '/drawLessons/admin/queryMainDetail',
    method: 'get',
    params: { id },
  });
}

/**
 * 2.2 查询举一反三详情
 * GET /api/drawLessons/admin/queryMainDetail?id=xxx
 */
export function getDrawLessonsAdminTowDetail(id: number) {
  return http.request<DrawLessonsItem>({
    url: '/drawLessons/admin/queryDetail',
    method: 'get',
    params: { id },
  });
}

/**
 * 2.2 查询举一反三详情
 * GET /api/drawLessons/admin/queryMainDetail?id=xxx
 */
export function getDrawLessonsAdminDeptDetail(id: number) {
  return http.request<DrawLessonsItem>({
    url: '/drawLessons/dept/queryDetail',
    method: 'get',
    params: { id },
  });
}

/**
 * 2.3 新增举一反三
 * POST /api/drawLessons/admin/save
 */
export interface SaveDrawLessonsRequest {
  dangerId: number; // 隐患ID（选择隐患名称）
  associationOneThree: string; // 举一反三要求
  associationOtObligationDeptIds: string; // 举一反三责任部门ID列表，逗号分隔
  associationOtTimeLimit: string; // 举一反三时限
  planStartDate?: string; // 计划开始日期 yyyy-MM-dd
  /** 兼容：隐患问题名称，后端可能根据 dangerId 带出 */
  problem?: string;
}

export function saveDrawLessons(data: SaveDrawLessonsRequest) {
  return http.request({
    url: '/drawLessons/admin/save',
    method: 'post',
    data,
  });
}

/**
 * 2.4 修改举一反三
 * PUT /api/drawLessons/admin/update
 */
export interface UpdateDrawLessonsRequest {
  id: number;
  associationOneThree?: string;
  associationOtObligationDeptIds?: string;
  associationOtTimeLimit?: string;
  planStartDate?: string;
  statusId?: number;
  statusName?: string;
  /** 兼容视图 spread 传参 */
  dangerId?: number;
  problem?: string;
}

export function updateDrawLessons(data: UpdateDrawLessonsRequest) {
  return http.request({
    url: '/drawLessons/admin/update',
    method: 'put',
    data,
  });
}

/**
 * 2.5 删除举一反三
 * DELETE /api/drawLessons/admin/delete?id=xxx
 */
export function deleteDrawLessons(id: number) {
  return http.request({
    url: '/drawLessons/admin/delete?id=' + id,
    method: 'delete',
  });
}

/**
 * 2.6 下发举一反三
 * POST /api/drawLessons/admin/issue
 */
export interface IssueDrawLessonsRequest {
  associationOtId: number;
  dangerId?: number;
  associationOtObligationDeptId?: number;
  associationOtObligationDeptName?: string;
  associationOtObligationDeptIds?: string;
  associationOtObligationDeptUserId?: number;
  associationOtObligationDeptUserName?: string;
  associationOneThree?: string;
  associationOtTimeLimit?: string;
  attachments?: string; 
  executGroupIds?: any; // 兼容批量下发传参
  /** 计划开始日期（下发弹窗） */
  planStartDate?: string;
  /** 计划结束时间（下发弹窗） */
  planEndDate?: string;
}

export function issueDrawLessons(data: IssueDrawLessonsRequest) {
  return http.request({
    url: '/drawLessons/admin/issue',
    method: 'post',
    data,
  });
}

/**
 * 2.7 反馈
 * POST /api/drawLessons/admin/feedback
 * id：下发记录 ID（举一反三下发表 id）
 * feedbackHasIssue：是否存在问题，1 是 / 0 否
 * feedbackResult：反馈结果/整改情况说明
 * feedbackTime：反馈时间（Date，传字符串如 YYYY-MM-DD HH:mm:ss）
 * attachments：反馈附件（JSON 或逗号分隔 URL，允许为空）
 */
export interface DrawLessonsFeedbackRequest {
  /** 下发记录 ID（举一反三下发表 id） */
  id: number;
  /** 是否存在问题：1-是 0-否 */
  feedbackHasIssue: number;
  /** 反馈结果/整改情况说明 */
  feedbackResult?: string;
  /** 反馈时间 */
  feedbackTime?: string;
  /** 反馈附件（JSON 或逗号分隔 URL，允许为空） */
  attachments?: string;
}

export function submitDrawLessonsAdminFeedback(data: DrawLessonsFeedbackRequest) {
  return http.request({
    url: '/drawLessons/admin/feedback',
    method: 'post',
    data: {
      id: data.id,
      feedbackHasIssue: data.feedbackHasIssue,
      feedbackResult: data.feedbackResult,
      feedbackTime: data.feedbackTime,
      attachments: data.attachments ?? '',
    },
  });
}

/**
 * 2.8 审核/变更状态
 * PUT /api/drawLessons/admin/approve?id=xxx&statusId=xxx&statusName=xxx&reviewReason=xxx(不通过时)
 */
export interface ApproveDrawLessonsRequest {
  id: number;
  statusId: number;
  statusName?: string;
  /** 不通过原因（审核不通过时必填） */
  reviewReason?: string;
}

export function approveDrawLessons(data: ApproveDrawLessonsRequest) {
  return http.request({
    url: '/drawLessons/admin/approve',
    method: 'put',
    params: {
      id: data.id,
      statusId: data.statusId,
      statusName: data.statusName,
      ...(data.reviewReason != null && data.reviewReason !== '' ? { reviewReason: data.reviewReason } : {}),
    },
  });
}

/**
 * 2.9 作废举一反三主记录
 * PUT /api/drawLessons/admin/void?id=xxx
 */
export function voidDrawLessons(id: number) {
  return http.request({
    url: '/drawLessons/admin/void',
    method: 'put',
    params: { id },
  });
}

/**
 * 部门端：分页查询
 * POST /api/drawLessons/dept/queryPage
 */
export function queryDrawLessonsDeptPage(
  query: QueryPageRequest<DrawLessonsQueryParam>,
) {
  return http.request<QueryPageResponse<DrawLessonsItem>>({
    url: '/drawLessons/dept/queryPage',
    method: 'post',
    data: query,
  });
}

/**
 * 部门端：详情
 * GET /api/drawLessons/dept/queryDetail?id=xxx
 */
export function getDrawLessonsDeptDetail(id: number) {
  return http.request<DrawLessonsItem>({
    url: '/drawLessons/dept/queryDetail',
    method: 'get',
    params: { id },
  });
}

/**
 * 部门端：反馈（与 admin/feedback 参数一致，若后端统一则可用 submitDrawLessonsAdminFeedback）
 * POST /api/drawLessons/dept/feedback
 */
export function submitDrawLessonsDeptFeedback(data: DrawLessonsFeedbackRequest) {
  return http.request({
    url: '/drawLessons/dept/feedback',
    method: 'post',
    data: {
      id: data.id,
      feedbackHasIssue: data.feedbackHasIssue,
      feedbackResult: data.feedbackResult,
      feedbackTime: data.feedbackTime,
      attachments: data.attachments ?? '',
    },
  });
}

/** 部门反馈请求（与 DrawLessonsFeedbackRequest 一致） */
export type DeptFeedbackRequest = DrawLessonsFeedbackRequest;

/**
 * 兼容旧调用：下发时按「主记录 id + 多个部门」封装，内部按文档拆成单条 issue 请求
 * 文档 2.6 为单条：associationOtId + 一个部门等；此处保留 id + deptIssues 入参
 */
export interface DrawLessonsDeptIssue {
  associationOtObligationDeptId?: number;
  associationOtObligationDeptName?: string;
  associationOtObligationDeptUserId?: number;
  associationOtObligationDeptUserName?: string;
  associationOneThree?: string;
  associationOtTimeLimit?: string;
}

export function issueDrawLessonsBatch(data: {
  id: number;
  deptIssues: DrawLessonsDeptIssue[];
}) {
  if (!data.deptIssues?.length) {
    return Promise.reject(new Error('请至少选择一个部门'));
  }
  const payloads: IssueDrawLessonsRequest[] = data.deptIssues.map((dept) => ({
    associationOtId: data.id,
    associationOtObligationDeptId: dept.associationOtObligationDeptId,
    associationOtObligationDeptName: dept.associationOtObligationDeptName,
    associationOtObligationDeptUserId: dept.associationOtObligationDeptUserId,
    associationOtObligationDeptUserName: dept.associationOtObligationDeptUserName,
    associationOneThree: dept.associationOneThree,
    associationOtTimeLimit: dept.associationOtTimeLimit,
  }));
  return Promise.all(payloads.map((p) => http.request({ url: '/drawLessons/admin/issue', method: 'post', data: p }))).then(
    () => ({}),
  );
}


export function queryDrawLessonsAdminDetailPage(query: QueryPageRequest<DrawLessonsQueryParam>) {
  return http.request({
    url: `/drawLessons/admin/notify`,
    method: 'post',
    data: query,
  });
}

/**
 * 废举一反三子记录
 */
export function cancellationMessagePost(id: number) {
  return http.request({
    url: `/drawLessons/admin/invalid?id=${id}`,
    method: 'post',
  });
}


/**
 * 导出法律法规
 */
export function exportTheDocumentPost() {
  return http.request({
    url: `/specialEquipment/exportInventory`,
    method: 'post',
    data: {},
    params: {
      classifyName: 'drawLessons',
    },
  });
}

/**
 * 管理导出举一反三子记录
 */
export function exportDrawLessonsAdminPage() {
  return http.request({
    url: '/drawLessons/admin/export',
    method: 'post',
    responseType: 'blob',
  }, {
    isTransformResponse: false,
  });
}

/**
 * 部门导出举一反三子记录
 */
export function exportDrawLessonsAdminPageDept() {
  return http.request({
    url: '/drawLessons/dept/export',
    method: 'post',
    responseType: 'blob',
  }, {
    isTransformResponse: false,
  });
}

