/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 16:31:27
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-06-24 11:26:30
 * @FilePath: /KC-MiddlePlatform/src/pages/platform/setting/pubDicTypeMana/service.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { request } from 'umi';

//获取table列表数据

export type FenyeTemplateItemType = {
  id: number;
  hiId: number;
  name: string;
  content: string;
  remark: string;
  createUserId: number;
  createUserName: string;
  date: string;
};

export const getChackGroupData = (params?: any) => {
  return request<{
    currPage: number;
    current: number;
    list: any[];
    pageSize: number;
    totalCount: number;
    totalPage: number;
  }>('/manager/CheckGroup/getCheckGroup', {
    method: 'GET',
    params: { ...params },
  });
};

//新增表格数据
export type AddTableDataType = {
  name: string;
};
export const addData = (data: AddTableDataType) => {
  return request('/manager/CheckGroup/addCheckGroup', {
    method: 'POST',
    data,
  });
};

//编辑表格数据
export const editData = (data: { id: number; name: string }) => {
  return request('/manager/CheckGroup/updateCheckGroup', {
    method: 'POST',
    data,
  });
};

//删除表格操作
export const delData = (id: number) => {
  return request('/manager/CheckGroup/deleteCheckGroup', {
    method: 'POST',
    data: [id],
  });
};

// 获取查核组人员列表
export const getCheckGroupEmployees = async (params: any) => {
  try {
    const { groupId } = params;

    const res = await request('/manager/CheckGroup/getGroupEmployee', {
      method: 'GET',
      params: {
        groupId: groupId || '',
      },
    });

    // 根据截图1，接口直接返回数组，不是分页格式
    const dataList = Array.isArray(res) ? res : [];

    return {
      data: dataList,
      success: true,
      total: dataList.length,
    };
  } catch (error) {
    console.error('获取查核组人员失败:', error);
    throw error;
  }
};

// 获取可添加的人员列表
export const getAvailableEmployees = async (
  groupId: number,
  filter: string = '',
  current: number = 1,
  pageSize: number = 10,
) => {
  try {
    const res = await request(
      '/manager/CheckGroup/getGroupPendingPageEmployee',
      {
        method: 'GET',
        params: {
          groupId,
          filter,
          current,
          pageSize,
        },
      },
    );

    return {
      list: res?.list || [],
      total: res?.totalCount || 0,
      success: true,
    };
  } catch (error) {
    throw error;
  }
};

// 添加查核组人员
export const addCheckGroupEmployee = async (
  groupId: number,
  employees: any[],
) => {
  try {
    const res = await request('/manager/CheckGroup/addGroupEmployee', {
      method: 'POST',
      data: {
        id: groupId.toString(),
        name: '', // 查核组名称，如果需要的话
        mapObjList: employees.map((emp) => ({
          id: emp.id.toString(),
          name: emp.name,
        })),
      },
    });

    return res;
  } catch (error) {
    throw error;
  }
};

// 删除查核组人员
export const delCheckGroupEmployee = async (employeeIds: React.Key[]) => {
  try {
    const res = await request('/manager/CheckGroup/delGroupEmp', {
      method: 'POST',
      data: employeeIds,
    });

    return res;
  } catch (error) {
    throw error;
  }
};

// 设置查核组组长
export const setGroupManager = async (groupId: number, employeeId: number) => {
  try {
    const res = await request('/manager/CheckGroup/setGroupManager', {
      method: 'POST',
      data: {
        checkGroupId: groupId,
        employeeId: employeeId,
      },
    });

    return res;
  } catch (error) {
    throw error;
  }
};

// 获取查核组的查核要点数据
export const getCheckGroupCheckpoints = async (params: any) => {
  try {
    const { groupId, filter = '' } = params;

    const res = await request('/manager/CheckGroup/getGroupCheckpoint', {
      method: 'GET',
      params: {
        groupId: groupId || '',
        filter: filter,
      },
    });

    // 转换数据格式以适配表格的合并行结构
    const convertToMergedRowData = (items: any[]): any[] => {
      if (!items || !Array.isArray(items)) return [];

      const flatData: any[] = [];

      items.forEach((point: any) => {
        if (
          Array.isArray(point.checkItemList) &&
          point.checkItemList.length > 0
        ) {
          // 如果有查核项，为每个查核项创建一行
          point.checkItemList.forEach((item: any, idx: number) => {
            flatData.push({
              id: idx === 0 ? String(point.id) : `${point.id}_item_${idx}`,
              pointName: point.checkPointName, // 使用checkPointName字段
              checkItemName: item.name,
              rowSpan: idx === 0 ? point.checkItemList.length : 0, // 第一行显示合并行数，其他行为0
              isFirst: idx === 0, // 标记是否为第一行
              originalPointId: point.id, // 保存原始关联ID用于删除
              checkPointId: point.checkPointId, // 保存查核要点ID
            });
          });
        } else {
          // 如果没有查核项，创建一行显示要点名称
          flatData.push({
            id: String(point.id),
            pointName: point.checkPointName, // 使用checkPointName字段
            checkItemName: '-',
            rowSpan: 1,
            isFirst: true,
            originalPointId: point.id, // 保存原始关联ID用于删除
            checkPointId: point.checkPointId, // 保存查核要点ID
          });
        }
      });

      return flatData;
    };

    // 处理数据
    let dataArray = [];

    if (Array.isArray(res)) {
      // 直接是数组
      dataArray = convertToMergedRowData(res);
    } else if (res && res.data && Array.isArray(res.data)) {
      // 数据在data字段中
      dataArray = convertToMergedRowData(res.data);
    } else if (res && res.list && Array.isArray(res.list)) {
      // 数据在list字段中
      dataArray = convertToMergedRowData(res.list);
    } else if (res && typeof res === 'object') {
      // 如果是单个对象，包装成数组
      dataArray = convertToMergedRowData([res]);
    }

    return {
      data: dataArray,
      success: true,
      total: dataArray.length,
    };
  } catch (error) {
    console.error('获取查核组查核要点失败:', error);
    throw error;
  }
};

// 获取可添加的查核要点列表
export const getGroupPendingCheckpoints = async (
  groupId: number,
  filter: string = '',
  current: number = 1,
  pageSize: number = 10,
) => {
  try {
    const res = await request(
      '/manager/CheckGroup/getGroupPendingPageCheckpoint',
      {
        method: 'GET',
        params: {
          groupId,
          filter,
          current,
          pageSize,
        },
      },
    );

    // 直接按“要点”为单位返回，不做铺平，保持与接口分页一致
    let list: any[] = [];
    let total = 0;

    if (res && res.data && Array.isArray(res.data.list)) {
      list = res.data.list;
      total = res.data.totalCount || res.data.list.length || 0;
    } else if (Array.isArray(res?.list)) {
      list = res.list;
      total = res.totalCount || res.total || res.list.length || 0;
    } else if (Array.isArray(res)) {
      list = res;
      total = res.length;
    } else if (Array.isArray(res?.data)) {
      list = res.data;
      total = res.total || res.totalCount || res.data.length || 0;
    } else if (res && typeof res === 'object') {
      list = [res];
      total = 1;
    }

    return {
      list,
      total,
      success: true,
    };
  } catch (error) {
    throw error;
  }
};

// 添加查核组查核要点
export const addCheckGroupCheckpoints = async (
  groupId: number,
  checkpointIds: number[],
) => {
  try {
    const res = await request('/manager/CheckGroup/addGroupCheckpoint', {
      method: 'POST',
      data: {
        id: groupId,
        name: '', // 查核组名称，如果需要的话
        mapObjList: checkpointIds.map((id) => ({
          id: id,
          name: '', // 要点名称，如果需要的话
        })),
      },
    });

    return res;
  } catch (error) {
    throw error;
  }
};

// 删除查核组查核要点
export const delCheckGroupCheckpoints = async (checkpointIds: React.Key[]) => {
  try {
    const res = await request('/manager/CheckGroup/delGroupCheckpoint', {
      method: 'POST',
      data: checkpointIds,
    });

    return res;
  } catch (error) {
    throw error;
  }
};
