import apiClient from './index';
import type { Page, AssigneeInfoDTO, UserInfoDTO, TaskInfoDTO, AttachmentDTO } from './types';
import { PollutionType } from './types';

// 导出必要的类型
export { PollutionType };

// API URL
const API_URL = '/feedback';

// --- Start: Copied from TaskDetailView.vue for now ---
// This is technical debt and should be refactored into a central types file.
interface FeedbackDTO {
  feedbackId: number;
  eventId: string;
  title: string;
}
interface AssigneeDTO {
  id: number;
  name: string;
  phone: string;
}
interface TaskHistoryDTO {
  id: number;
  oldStatus: string | null;
  newStatus: string;
  comments: string;
  changedAt: string;
  changedBy: {
    id: number;
    name:string;
  };
}
interface SubmissionInfoDTO {
  comments: string;
  attachments: AttachmentDTO[];
}
export interface TaskDetail {
  id: number;
  feedback: FeedbackDTO;
  title: string;
  description: string;
  status: string;
  assignee?: AssigneeDTO;
  assignedAt: string | null;
  completedAt: string | null;
  history: TaskHistoryDTO[];
  submissionInfo: SubmissionInfoDTO | null;
  gridX?: number | null;
  gridY?: number | null;
  assignment?: {
    assignmentTime?: string;
    remarks?: string;
  };
}
// --- End: Copied from TaskDetailView.vue ---

/**
 * 反馈状态枚举
 */
export enum FeedbackStatus {
  AI_REVIEWING = 'AI_REVIEWING', // AI审核中
  PENDING_REVIEW = 'PENDING_REVIEW', // 待人工审核
  REJECTED = 'REJECTED', // 已拒绝
  CONFIRMED = 'CONFIRMED', // 已确认
  ASSIGNED = 'ASSIGNED', // 已分配
  IN_PROGRESS = 'IN_PROGRESS', // 处理中
  RESOLVED = 'RESOLVED', // 已解决
  CLOSED = 'CLOSED', // 已关闭
  PENDING_ASSIGNMENT = 'PENDING_ASSIGNMENT', // 待分配
  PROCESSED = 'PROCESSED' // 已处理
}

/**
 * 严重程度枚举
 */
export enum SeverityLevel {
  LOW = 'LOW', // 低
  MEDIUM = 'MEDIUM', // 中
  HIGH = 'HIGH' // 高
}

/**
 * 反馈列表项接口 (现在匹配后端的 FeedbackResponseDTO)
 */
export interface FeedbackResponse {
  id: number;
  eventId: string;
  title: string;
  description: string;
  pollutionType: PollutionType;
  severityLevel: SeverityLevel;
  status: FeedbackStatus;
  textAddress: string;
  gridX: number;
  gridY: number;
  latitude: number;
  longitude: number;
  createdAt: string; // ISO date string
  updatedAt: string; // ISO date string
  submitterId: number;
  user: UserInfoDTO;
  task: TaskDetail | null; // Task can be null if not assigned
  attachments: AttachmentDTO[];
  reporterPhone?: string;
}

/**
 * 反馈详情接口 (为了简化，我们可以让它继承自 FeedbackResponse)
 */
export interface FeedbackDetail extends FeedbackResponse {
  aiAnalysis?: string;
  reviewNotes?: string;
  assignmentId?: number;
  assignmentMethod?: string;
  assignmentTime?: string;
  assignedWorkerId?: number;
  resolutionNotes?: string;
  resolutionTime?: string;
  // `images` is now `attachments`, which is already in FeedbackResponse
}

/**
 * 反馈筛选参数接口
 */
export interface FeedbackFilters {
  status?: FeedbackStatus;
  pollutionType?: PollutionType;
  severityLevel?: SeverityLevel;
  cityName?: string;
  districtName?: string;
  startDate?: string;
  endDate?: string;
  keyword?: string;
  submitterId?: number;
  page?: number;
  size?: number;
}

/**
 * 反馈处理请求接口
 */
export interface ProcessFeedbackRequest {
  status: FeedbackStatus;
  notes?: string;
}

/**
 * 反馈分配请求接口
 */
export interface AssignFeedbackRequest {
  gridWorkerId: number;
  notes?: string;
}

/**
 * 反馈拒绝请求接口
 */
export interface RejectFeedbackRequest {
  notes: string;
}

export interface LocationInfo {
  latitude: number;
  longitude: number;
  textAddress: string;
  gridX: number;
  gridY: number;
}

export interface FeedbackSubmissionRequest {
  title: string;
  description: string;
  pollutionType: PollutionType;
  severityLevel: SeverityLevel;
  location: LocationInfo;
}

/**
 * 获取反馈列表
 * @param params 筛选参数
 * @returns 分页反馈列表
 */
export function getFeedbackList(params?: FeedbackFilters): Promise<Page<FeedbackResponse>> {
  return apiClient.get(API_URL, { params });
}

/**
 * 获取反馈详情
 * @param id 反馈ID
 * @returns 反馈详情
 */
export function getFeedbackDetail(id: number): Promise<FeedbackDetail> {
  return apiClient.get(`/feedback/${id}`);
}

/**
 * 处理反馈
 * @param id 反馈ID
 * @param data 处理数据
 * @returns 处理结果
 */
export function processFeedback(id: number, request: { status: string; notes?: string }): Promise<FeedbackDetail> {
  return apiClient.post(`/feedback/${id}/process`, request);
}

/**
 * 分配反馈给网格员
 * @param id 反馈ID
 * @param data 分配数据
 * @returns 分配结果
 */
export function assignFeedback(id: number, data: AssignFeedbackRequest): Promise<any> {
  return apiClient.post(`${API_URL}/${id}/assign`, data);
}

/**
 * 标记反馈为已解决
 * @param id 反馈ID
 * @param notes 解决说明
 * @returns 操作结果
 */
export function resolveFeedback(id: number, notes?: string): Promise<any> {
  return apiClient.post(`${API_URL}/${id}/resolve`, { notes });
}

/**
 * 关闭反馈
 * @param id 反馈ID
 * @param notes 关闭说明
 * @returns 操作结果
 */
export function closeFeedback(id: number, notes?: string): Promise<any> {
  return apiClient.post(`${API_URL}/${id}/close`, { notes });
}

/**
 * 拒绝反馈
 * @param id 反馈ID
 * @param data 拒绝数据
 * @returns 操作结果
 */
export function rejectFeedback(id: number, data: RejectFeedbackRequest): Promise<any> {
  return apiClient.post(`/supervisor/reviews/${id}/reject`, data);
}

/**
 * 确认反馈
 * @param id 反馈ID
 * @returns 响应体
 */
export function confirmFeedback(id: number): Promise<any> {
  return apiClient.post(`${API_URL}/${id}/confirm`);
}

/**
 * 提交新的反馈
 * @param formData 包含反馈数据和文件的表单
 * @returns 提交结果
 */
export function submitFeedback(formData: FormData): Promise<any> {
  return apiClient.post(`${API_URL}/submit`, formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
}

/**
 * 获取反馈统计数据
 * @returns 反馈统计数据
 */
export const getFeedbackStats = async () => {
  try {
    const response = await apiClient.get(`${API_URL}/stats`);
    return response || {}; // 如果响应为空，返回一个空对象
  } catch (error) {
    console.error('获取反馈统计数据API错误:', error);
    // 即使API失败也返回一个默认的统计对象结构，防止UI崩溃
    return {
      total: 0,
      pending: 0,
      confirmed: 0,
      assigned: 0,
      inProgress: 0,
      resolved: 0,
      closed: 0,
      rejected: 0,
    };
  }
};

/**
 * 获取待处理的反馈列表
 * @returns 待处理的反馈列表
 */
export function getPendingFeedback(): Promise<FeedbackResponse[]> {
  return apiClient.get('/feedback/pending');
}
