// AI_CHANGELOG
// - 2026-03-20 | Prompt: R3 项目类型筛选接口重建 | fetchSkillTypes() fallback 数据
//   value 从 all/chinese/snooker 改为 ALL/BILLIARD/SNOOKER；API 响应映射从
//   data.skills 改为直接 map data 数组（后端返回 [{key,label,emoji,cls}]）。
// - 2026-03-20 | Prompt: RNS1.4 T12.1 移除 mock 数据残留 | 移除所有 mock 导入、
//   USE_REAL_API 开关、delay() 辅助函数和 mock fallback 分支，全部直连真实 API。

/**
 * Service 层 — 统一数据请求入口
 *
 * 页面只调用 service 函数，不直接引用 mock 数据或 wx.request。
 * 所有函数均直连真实后端 API。
 */

import { request } from '../utils/request'
import type {
  Task,
  TaskDetail,
  Note,
  PerformanceData,
  PerformanceRecord,
  BoardFinanceData,
  CustomerCard,
  CoachCard,
  CustomerDetail,
} from '../utils/mock-data'

// ============================================
// 认证模块
// ============================================

/** 查询当前用户信息 */
export async function fetchMe(): Promise<ApiUserInfo> {
  return request({ url: '/api/xcx/me', method: 'GET', needAuth: true })
}

// ============================================
// 任务模块
// ============================================

export interface FetchTasksParams {
  status?: 'pending' | 'completed' | 'abandoned'
  page?: number
  pageSize?: number
}

/** 获取任务列表 + 绩效概览 */
export async function fetchTasks(params: FetchTasksParams = {}): Promise<{
  tasks: Task[]
  performance: PerformanceData
  total: number
  hasMore: boolean
}> {
  return request({
    url: '/api/xcx/tasks',
    method: 'GET',
    data: params,
    needAuth: true,
  })
}

/** 获取任务详情 */
export async function fetchTaskDetail(taskId: string): Promise<TaskDetail | null> {
  return request({
    url: `/api/xcx/tasks/${taskId}`,
    method: 'GET',
    needAuth: true,
  })
}

/** 放弃任务 */
export async function abandonTask(taskId: string, reason: string): Promise<void> {
  await request({
    url: `/api/xcx/tasks/${taskId}/abandon`,
    method: 'POST',
    data: { reason },
    needAuth: true,
  })
}

/** 取消放弃（恢复任务） */
export async function restoreTask(taskId: string): Promise<void> {
  await request({
    url: `/api/xcx/tasks/${taskId}/restore`,
    method: 'POST',
    needAuth: true,
  })
}

/** 置顶任务 */
export async function pinTask(taskId: string): Promise<{ isPinned: boolean }> {
  return request({
    url: `/api/xcx/tasks/${taskId}/pin`,
    method: 'POST',
    needAuth: true,
  })
}

/** 取消置顶任务 */
export async function unpinTask(taskId: string): Promise<{ isPinned: boolean }> {
  return request({
    url: `/api/xcx/tasks/${taskId}/unpin`,
    method: 'POST',
    needAuth: true,
  })
}

// ============================================
// 备注模块
// ============================================

/** 获取备注列表 */
export async function fetchNotes(params: { page?: number; pageSize?: number } = {}): Promise<{
  notes: Note[]
  total: number
  hasMore: boolean
}> {
  return request({ url: '/api/xcx/notes', method: 'GET', data: params, needAuth: true })
}

/** 新增备注 */
export async function createNote(data: {
  content: string
  taskId?: string
  customerId?: string
  ratingServiceWillingness?: number
  ratingRevisitLikelihood?: number
}): Promise<{ id: string; createdAt: string }> {
  return request({ url: '/api/xcx/notes', method: 'POST', data, needAuth: true })
}

/** 删除备注 */
export async function deleteNote(noteId: string): Promise<void> {
  await request({ url: `/api/xcx/notes/${noteId}`, method: 'DELETE', needAuth: true })
}

// ============================================
// 绩效模块
// ============================================

/** 绩效概览 */
export async function fetchPerformanceOverview(params: {
  year: number
  month: number
}): Promise<PerformanceData> {
  return request({ url: '/api/xcx/performance', method: 'GET', data: params, needAuth: true })
}

/** 绩效明细（按月） */
export async function fetchPerformanceRecords(params: {
  year: number
  month: number
  page?: number
  pageSize?: number
}): Promise<{ records: PerformanceRecord[]; hasMore: boolean }> {
  return request({
    url: '/api/xcx/performance/records',
    method: 'GET',
    data: params,
    needAuth: true,
  })
}

// ============================================
// 客户模块
// ============================================

/** 客户详情 */
export async function fetchCustomerDetail(customerId: string): Promise<CustomerDetail | null> {
  return request({
    url: `/api/xcx/customers/${customerId}`,
    method: 'GET',
    needAuth: true,
  })
}

/** 客户服务记录 */
export async function fetchCustomerRecords(params: {
  customerId: string
  year?: number
  month?: number
  table?: string
}): Promise<{ records: any[]; hasMore: boolean }> {
  const { customerId, ...rest } = params
  return request({
    url: `/api/xcx/customers/${customerId}/records`,
    method: 'GET',
    data: rest,
    needAuth: true,
  })
}

// ============================================
// 看板模块
// ============================================

/** 助教看板 */
export async function fetchBoardCoaches(params: {
  skill?: string
  sort?: string
  time?: string
} = {}): Promise<CoachCard[]> {
  const data = await request({
    url: '/api/xcx/board/coaches',
    method: 'GET',
    data: params,
    needAuth: true,
  })
  return data.items
}

// CHANGE 2026-03-19 | RNS1.3 T13: 增加 page/pageSize 参数支持分页
/** 客户看板 */
export async function fetchBoardCustomers(params: {
  dimension?: string
  project?: string
  page?: number
  pageSize?: number
} = {}): Promise<CustomerCard[]> {
  const data = await request({
    url: '/api/xcx/board/customers',
    method: 'GET',
    data: params,
    needAuth: true,
  })
  return data.items
}

// CHANGE 2026-03-19 | RNS1.3 T14: 扩展参数为 time/area/compare
/** 财务看板 */
export async function fetchBoardFinance(params: {
  time?: string
  area?: string
  compare?: number
} = {}): Promise<BoardFinanceData> {
  return request({
    url: '/api/xcx/board/finance',
    method: 'GET',
    data: params,
    needAuth: true,
  })
}

// ============================================
// 助教模块
// ============================================

/** 助教详情 */
export async function fetchCoachDetail(coachId: string): Promise<CoachCard | null> {
  return request({
    url: `/api/xcx/coaches/${coachId}`,
    method: 'GET',
    needAuth: true,
  })
}

// ============================================
// 对话模块
// ============================================

/** 对话历史列表 */
export async function fetchChatHistory(params: {
  page?: number
  pageSize?: number
} = {}): Promise<{ items: any[]; total: number; page: number; pageSize: number }> {
  return request({
    url: '/api/xcx/chat/history',
    method: 'GET',
    data: params,
    needAuth: true,
  })
}

/** 对话消息列表（通过 chatId） */
export async function fetchChatMessages(chatId: string, params: {
  page?: number
  pageSize?: number
} = {}): Promise<{ chatId: number; items: any[]; total: number; page: number; pageSize: number }> {
  return request({
    url: `/api/xcx/chat/${chatId}/messages`,
    method: 'GET',
    data: params,
    needAuth: true,
  })
}

/** 对话消息列表（通过上下文类型和 ID，自动查找/创建对话） */
export async function fetchChatMessagesByContext(
  contextType: string,
  contextId: string,
  params: { page?: number; pageSize?: number } = {},
): Promise<{ chatId: number; items: any[]; total: number; page: number; pageSize: number }> {
  return request({
    url: '/api/xcx/chat/messages',
    method: 'GET',
    data: { contextType, contextId, ...params },
    needAuth: true,
  })
}

/** 发送消息 */
export async function sendChatMessage(chatId: string, content: string): Promise<{
  userMessage: { id: number; content: string; createdAt: string }
  aiReply: { id: number; content: string; createdAt: string }
}> {
  return request({
    url: `/api/xcx/chat/${chatId}/messages`,
    method: 'POST',
    data: { content },
    needAuth: true,
  })
}

// ============================================
// 配置模块
// ============================================

/** 项目类型筛选器列表（CONFIG-1） */
// CHANGE 2026-03-20 | R3 修复：value 改为数据库 category_code，fallback 与后端一致
export async function fetchSkillTypes(): Promise<Array<{ value: string; text: string; icon?: string }>> {
  const data = await request({
    url: '/api/xcx/config/skill-types',
    method: 'GET',
    needAuth: true,
  })
  // 后端返回 [{key, label, emoji, cls}, ...]，映射为前端 {value, text, icon}
  return (data as Array<{key: string; label: string; emoji: string; cls: string}>).map(
    (item: {key: string; label: string; emoji: string}) => ({
      value: item.key,
      text: item.label,
      icon: item.emoji || undefined,
    })
  )
}
