/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2025-09-30 00:00:00
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-09-30 00:00:00
 * @FilePath: /KC-MiddlePlatform/src/pages/platform/setting/serviceEvaluate/service.ts
 * @Description: 服务评价管理 - 服务层封装（默认使用 mock 接口）
 */

// 本地模拟返回：使用前端内存数据替代实际请求，方便在后端未就绪时开发、联调
import { request } from 'umi';

// 分类树节点
export type CategoryNode = {
  id: string;
  name: string;
  children?: CategoryNode[];
};

// 评价项目
export type ProjectItem = {
  projectId: string;
  projectCode: string;
  projectName: string;
  weight: number; // 0-100
};

// 选项
export type OptionItem = {
  optionId: string;
  optionCode: string;
  optionName: string;
  score: number;
};

// 分页响应（为兼容 KCTable 的 request，保持 list 字段）
export type ListResp<T> = {
  list: T[];
};

// ------------------ 真实接口：系统树获取 ------------------
// 注意：页面内仍使用本地 mock 的分类树/项目/选项。
// 本方法用于“添加系统”弹窗的数据源，请求服务端返回的 systemList 结构。
export type SystemTreeNode = {
  code: string;
  name: string;
  sort?: number;
  type?: number;
  children?: SystemTreeNode[];
};

export type GetSystemListResp = { systemList: SystemTreeNode[]; selectSystemList: (string | number)[] };

export const getSystemListForModal = async (): Promise<GetSystemListResp> => {
  const resp = await request<any>(
    '/centerSys/evaluation/getSystemList',
    { method: 'GET' },
  );
  // 后端返回形如 { status, msg, data: { systemList, selectSystemList } }
  const data = resp?.data || resp || {};
  const selectedRaw = data.selectSystemList || [];
  const normalizeKey = (x: any) => String((x && (x.systemId || x.code)) || x);
  const selected = Array.isArray(selectedRaw) ? selectedRaw.map((x: any) => normalizeKey(x)) : [];
  return {
    systemList: data.systemList || [],
    selectSystemList: selected,
  };
};

// 保存所选系统
export const addSystems = async (
  data: { systemId: string | number; systemName: string }[],
) => {
  return request('/centerSys/evaluation/addSystem', {
    method: 'POST',
    data,
  });
};

// 获取左侧“已选系统”列表
export type SelectedSystemItem = { id: string | number; hospId: string | number; systemId: string | number; systemName: string };
export const getSelectedSystemList = async (): Promise<SelectedSystemItem[]> => {
  const resp = await request<any>('/centerSys/evaluation/getSelectSystemList', { method: 'GET' });
  // 兼容后端返回 { data: [...] }
  return resp?.data || resp || [];
};

// 在系统下添加服务类型
export const addServiceTypes = async (systemId: string | number, serviceTypes: (string | number)[]) => {
  return request('/centerSys/evaluation/addService', {
    method: 'POST',
    data: { systemId, serviceTypes },
  });
};

// 根据服务类型获取评价项列表
export const getServiceEvaluationItem = async (serviceType: string) => {
  return request<any>('/centerSys/evaluation/getServiceEvaluationItem', {
    method: 'GET',
    params: { serviceType },
  });
};

// 获取右侧表格：评价项目列表（按 ItemCode）
export const getEvaluationSelect = async (ItemCode: string, serviceType: string) => {
  return request<any>('/centerSys/evaluation/getEvaluationSelect', {
    method: 'GET',
    params: { ItemCode, serviceType },
  });
};

// 保存评价项目
export const addEvaluationItem = async (
  serviceType: string,
  itemCodes: { itemCode: string; itemName: string; itemValue: number; sort: number }[],
) => {
  return request('/centerSys/evaluation/addEvaluationItem', {
    method: 'POST',
    data: { serviceType, itemCodes },
  });
};

// 保存评价项的"选项"
export const addEvaluationSelect = async (
  itemCode: string,
  selectCodes: { itemCode: string; itemName: string; itemValue: number; sort: number }[],
) => {
  return request('/centerSys/evaluation/addEvaluationSelect', {
    method: 'POST',
    data: { itemCode, selectCodes },
  });
};

// 编辑选项得分
export const editEvaluationSelect = async (id: number | string, value: number) => {
  return request('/centerSys/evaluation/editEvaluationSelect', {
    method: 'POST',
    data: { id, value },
  });
};

// 删除评价项目
export const deleteEvaluationItem = async (id: number | string) => {
  return request(`/centerSys/evaluation/deleteEvaluationItem?id=${id}`, {
    method: 'POST',
  });
};

// 删除选项
export const deleteEvaluationSelect = async (id: number | string) => {
  return request(`/centerSys/evaluation/deleteEvaluationSelect?id=${id}`, {
    method: 'POST',
  });
};

// 获取分类树
// 内存数据：分类树
const __categoryTree__: CategoryNode[] = [
  {
    id: 'park-app',
    name: '停车服务APP',
    children: [
      { id: 'park-service', name: '停车服务', children: [] },
      { id: 'guard-service', name: '护工服务', children: [] },
      { id: 'food-app', name: '食堂点餐APP', children: [] },
    ],
  },
];

// 内存数据：项目、选项
const __projects__: Record<string, ProjectItem[]> = {
  'park-service': [
    { projectId: 'p1', projectCode: 'P0001', projectName: '专业能力', weight: 25 },
    { projectId: 'p2', projectCode: 'P0002', projectName: '服务态度', weight: 20 },
  ],
};

const __options__: Record<string, OptionItem[]> = {
  p1: [
    { optionId: 'o11', optionCode: 'X0006', optionName: '1星', score: 100 },
    { optionId: 'o12', optionCode: 'X0007', optionName: '2星', score: 2 },
    { optionId: 'o13', optionCode: 'X0008', optionName: '3星', score: 3 },
    { optionId: 'o14', optionCode: 'X0009', optionName: '4星', score: 4 },
    { optionId: 'o15', optionCode: 'X0010', optionName: '5星', score: 5 },
  ],
  p2: [],
};

// 工具：模拟异步
const delay = (ms = 200) => new Promise((r) => setTimeout(r, ms));

export const getCategoryTree = async () => {
  await delay();
  return __categoryTree__;
};

// 新增分类节点（默认添加到指定父节点 children 下；未传 parentId 则添加到根）
export const addCategory = async (parentId: string | undefined, name: string) => {
  await delay();
  const newNode: CategoryNode = { id: `cat_${Date.now()}`, name, children: [] };

  if (!parentId) {
    __categoryTree__.push(newNode);
    return newNode;
  }

  // 递归查找父节点
  const dfs = (list: CategoryNode[]): boolean => {
    for (const node of list) {
      if (node.id === parentId) {
        node.children = node.children || [];
        node.children.push(newNode);
        return true;
      }
      if (node.children && node.children.length > 0) {
        if (dfs(node.children)) return true;
      }
    }
    return false;
  };

  dfs(__categoryTree__);
  return newNode;
};

// 获取项目列表
export const getProjectList = async (params: { categoryId: string; current?: number; pageSize?: number }) => {
  await delay();
  const list = __projects__[params.categoryId] || [];
  return { list };
};

// 新增项目
export const addProject = async (data: { categoryId: string; projectCode: string; projectName: string; weight: number }) => {
  await delay();
  const newItem: ProjectItem = {
    projectId: `p_${Date.now()}`,
    projectCode: data.projectCode,
    projectName: data.projectName,
    weight: Number(data.weight) || 0,
  };
  __projects__[data.categoryId] = __projects__[data.categoryId] || [];
  __projects__[data.categoryId].push(newItem);
  return true as unknown as any;
};

// 删除项目
export const delProject = async (projectId: string) => {
  await delay();
  Object.keys(__projects__).forEach((k) => {
    __projects__[k] = (__projects__[k] || []).filter((p) => p.projectId !== projectId);
  });
  delete __options__[projectId];
  return true as unknown as any;
};

// 更新项目权重
export const updateProjectWeight = async (projectId: string, weight: number) => {
  await delay();
  Object.keys(__projects__).forEach((k) => {
    (__projects__[k] || []).forEach((p) => {
      if (p.projectId === projectId) p.weight = Number(weight) || 0;
    });
  });
  return true as unknown as any;
};

// 获取选项列表
export const getOptionList = async (params: { projectId: string }) => {
  await delay();
  return __options__[params.projectId] || [];
};

// 新增选项
export const addOption = async (data: { projectId: string; optionCode: string; optionName: string; score: number }) => {
  await delay();
  __options__[data.projectId] = __options__[data.projectId] || [];
  __options__[data.projectId].push({ optionId: `o_${Date.now()}`, optionCode: data.optionCode, optionName: data.optionName, score: Number(data.score) || 0 });
  return true as unknown as any;
};

// 删除选项
export const delOption = async (optionId: string) => {
  await delay();
  Object.keys(__options__).forEach((k) => {
    __options__[k] = (__options__[k] || []).filter((o) => o.optionId !== optionId);
  });
  return true as unknown as any;
};

// 更新选项分数
export const updateOptionScore = async (optionId: string, score: number) => {
  await delay();
  Object.keys(__options__).forEach((k) => {
    (__options__[k] || []).forEach((o) => {
      if (o.optionId === optionId) o.score = Number(score) || 0;
    });
  });
  return true as unknown as any;
};


