// 查核要点管理相关接口
import { request } from 'umi';

// 获取左侧树形菜单数据（查核要点列表）
export async function getTreeData(current: number = 1, filter: string = '', pageSize: number = 50) {
  try {
    const res = await request('/manager/Checkpoint/getCheckpointList', {
      method: 'GET',
      params: {
        current,
        pageSize,
        filter,
      },
    });

    if (res && res.list) {
      return {
        list: res.list,
        totalCount: res.totalCount || res.list.length,
        success: true,
      };
    } else if (res && Array.isArray(res)) {
      // 如果直接返回数组
      return {
        list: res,
        totalCount: res.length,
        success: true,
      };
    } else {
      return {
        list: [],
        totalCount: 0,
        success: false,
      };
    }
  } catch (error) {
    throw error;
  }
}

// 获取要点分类选项
export async function getPointCategoryList() {
  try {
    const res = await request('/manager/Checkpoint/getPointCategoryList', {
      method: 'GET',
    });

    let dataArray: any[] = [];

    // 处理不同的数据结构
    if (Array.isArray(res)) {
      dataArray = res;
    } else if (res && res.data && Array.isArray(res.data)) {
      dataArray = res.data;
    } else if (res && res.list && Array.isArray(res.list)) {
      dataArray = res.list;
    }

    // 根据接口字段说明转换数据
    const options = dataArray.map((item: any) => ({
      label: item.itemName,
      value: item.id,
    }));

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

// 获取右侧表格数据 - 查核单位
export async function getTableData(params: any) {
  try {
    const { current = 1, pageSize = 10, parentId, filter = '' } = params;

    const res = await request('/manager/Checkpoint/getCheckpointDept', {
      method: 'GET',
      params: {
        checkpointId: parentId || '',
        filter: filter,
      },
    });

    // 由于接口返回的就是data数组，直接使用
    let dataArray = [];
    let total = 0;

    // 兼容不同的数据结构
    if (Array.isArray(res)) {
      // 如果直接是数组
      dataArray = res;
      total = res.length;
    } else if (res && res.data && Array.isArray(res.data)) {
      // 如果是 {data: [...]}
      dataArray = res.data;
      total = res.total || res.data.length;
    } else if (res && res.list && Array.isArray(res.list)) {
      // 如果是 {list: [...]}
      dataArray = res.list;
      total = res.total || res.list.length;
    }

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

// 添加表格数据
export async function addTableData(data: any) {
  return { success: true };
}

// 删除表格数据
export async function deleteTableData(id: string) {
  return { success: true };
}

// 新增查核要点
export async function addCheckpoint(data: any) {
  try {
    const res = await request('/manager/Checkpoint/addCheckpoint', {
      method: 'POST',
      data: {
        name: data.name,
        sort: data.sort,
        pointCategory: data.pointCategory,
      },
    });

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

// 编辑查核要点
export async function updateCheckpoint(data: any) {
  try {
    const res = await request('/manager/Checkpoint/updateCheckpoint', {
      method: 'POST',
      data: {
        id: data.id,
        name: data.name,
        sort: data.sort,
        pointCategory: data.pointCategory,
      },
    });

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

// 删除查核要点
export async function deleteCheckpoint(id: number) {
  try {
    const res = await request('/manager/Checkpoint/deleteCheckpoint', {
      method: 'POST',
      data: { id },
    });

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

// 获取可添加的查核单位列表
export async function getCheckpointPendingDept(
  checkpointId: number,
  filter: string = '',
  current: number = 1,
  pageSize: number = 10,
) {
  try {
    const res = await request('/manager/Checkpoint/getCheckpointPendingDept', {
      method: 'GET',
      params: {
        checkpointId,
        filter,
        current,
        pageSize,
      },
    });

    // 由于接口返回的就是data数组，直接使用
    let dataArray = [];
    let total = 0;

    // 兼容不同的数据结构
    if (Array.isArray(res)) {
      // 如果直接是数组
      dataArray = res;
      total = res.length;
    } else if (res && res.data && Array.isArray(res.data)) {
      // 如果是 {data: [...]}
      dataArray = res.data;
      total = res.total || res.data.length;
    } else if (res && res.list && Array.isArray(res.list)) {
      // 如果是 {list: [...]}
      dataArray = res.list;
      total = res.total || res.list.length;
    }

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

// 添加查核单位
export async function addCheckpointDept(
  checkpointId: number,
  deptIds: number[],
) {
  try {
    const res = await request('/manager/Checkpoint/addCheckpointDept', {
      method: 'POST',
      data: {
        id: checkpointId.toString(),
        mapObjList: deptIds.map((id) => ({ id: id.toString(), type: '0' })),
      },
    });

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

// 删除查核单位
export async function delCheckpointDept(deptIds: React.Key[]) {
  try {
    const res = await request('/manager/Checkpoint/delCheckpointDept', {
      method: 'POST',
      data: deptIds,
    });

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

// 获取查核组数据
export async function getCheckpointGroup(params: any) {
  try {
    const { current = 1, pageSize = 10, parentId, filter = '' } = params;

    const res = await request('/manager/Checkpoint/getCheckpointGroup', {
      method: 'GET',
      params: {
        checkpointId: parentId || '',
        filter: filter,
      },
    });

    // 由于接口返回的就是data数组，直接使用
    return {
      data: res || [],
      success: true,
      total: res ? res.length : 0,
    };
  } catch (error) {
    throw error;
  }
}

// 获取可添加的查核组列表
export async function getCheckpointPendingGroup(
  checkpointId: number,
  filter: string = '',
  current: number = 1,
  pageSize: number = 10,
) {
  try {
    const res = await request('/manager/Checkpoint/getCheckpointPendingGroup', {
      method: 'GET',
      params: {
        checkpointId,
        filter,
        current,
        pageSize,
      },
    });

    // 由于接口返回的就是data数组，直接使用
    return {
      list: res || [],
      total: res ? res.length : 0,
      success: true,
    };
  } catch (error) {
    throw error;
  }
}

// 添加查核组
export async function addCheckpointGroup(
  checkpointId: number,
  groupIds: number[],
) {
  try {
    const res = await request('/manager/Checkpoint/addCheckpointGroup', {
      method: 'POST',
      data: {
        id: checkpointId.toString(),
        mapIdList: groupIds.map((id) => id.toString()),
      },
    });

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

// 删除查核组
export async function delCheckpointGroup(groupIds: React.Key[]) {
  try {
    const res = await request('/manager/Checkpoint/delCheckpointGroup', {
      method: 'POST',
      data: groupIds,
    });

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

// 获取查核项数据
export async function getCheckpointItem(params: any) {
  try {
    const { current = 1, pageSize = 10, parentId, filter = '' } = params;

    const res = await request('/manager/Checkpoint/getCheckpointItem', {
      method: 'GET',
      params: {
        checkpointId: parentId || '',
        filter: filter,
      },
    });

    // 兼容不同的数据结构
    let dataArray = [];
    let total = 0;

    if (Array.isArray(res)) {
      // 如果直接是数组
      dataArray = res;
      total = res.length;
    } else if (res && res.data && Array.isArray(res.data)) {
      // 如果是 {data: [...]}
      dataArray = res.data;
      total = res.total || res.data.length;
    } else if (res && res.list && Array.isArray(res.list)) {
      // 如果是 {list: [...]}
      dataArray = res.list;
      total = res.total || res.list.length;
    } else {
      // 其他情况，可能是对象包装
      dataArray = res ? [res] : [];
      total = dataArray.length;
    }

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

// 获取可添加的查核项列表
export async function getCheckpointPendingItem(
  checkpointId: number,
  filter: string = '',
  current: number = 1,
  pageSize: number = 10,
) {
  try {
    const res = await request('/manager/Checkpoint/getCheckpointPendingItem', {
      method: 'GET',
      params: {
        checkpointId,
        filter,
        current,
        pageSize,
      },
    });

    // 兼容不同的数据结构
    let dataArray = [];
    let total = 0;

    if (Array.isArray(res)) {
      dataArray = res;
      total = res.length;
    } else if (res && res.data && Array.isArray(res.data)) {
      dataArray = res.data;
      total = res.total || res.data.length;
    } else if (res && res.list && Array.isArray(res.list)) {
      dataArray = res.list;
      total = res.total || res.list.length;
    }

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

// 添加查核项
export async function addCheckpointItem(
  checkpointId: number,
  itemIds: number[],
) {
  try {
    const res = await request('/manager/Checkpoint/addCheckpointItem', {
      method: 'POST',
      data: {
        id: checkpointId.toString(),
        mapIdList: itemIds.map((id) => id.toString()),
      },
    });

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

// 删除查核项
export async function delCheckpointItem(itemIds: React.Key[]) {
  try {
    const res = await request('/manager/Checkpoint/delCheckpointItem', {
      method: 'POST',
      data: itemIds,
    });

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

// 获取条文条款数据
export async function getCheckpointRule(params: any) {
  try {
    const { current = 1, pageSize = 10, parentId, filter = '' } = params;

    const res = await request('/manager/Checkpoint/getCheckpointRule', {
      method: 'GET',
      params: {
        checkpointId: parentId || '',
        filter: filter,
      },
    });

    // 转换数据格式以适配 ProTable 的树形结构
    const convertToTreeData = (items: any[]): any[] => {
      if (!items || !Array.isArray(items)) return [];

      return items.map((item) => {
        const convertedItem = {
          ...item,
          key: item.id,
        };

        // 如果有子项，递归转换子项
        if (item.child && Array.isArray(item.child) && item.child.length > 0) {
          convertedItem.children = convertToTreeData(item.child);
        }

        return convertedItem;
      });
    };

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

    if (res && res.data && res.data.items && Array.isArray(res.data.items)) {
      dataArray = convertToTreeData(res.data.items);
    } else if (res && res.items && Array.isArray(res.items)) {
      dataArray = convertToTreeData(res.items);
    } else if (Array.isArray(res)) {
      dataArray = convertToTreeData(res);
    }

    return {
      data: dataArray,
      success: true,
      total: dataArray.length,
    };
  } catch (error) {
    throw error;
  }
}

// 获取版本下拉数据
export async function getReviewRuleVersion() {
  try {
    const res = await request('/manager/Checkpoint/getReviewRuleVersion', {
      method: 'GET',
    });

    let dataArray: any[] = [];

    // 处理不同的数据结构
    if (Array.isArray(res)) {
      dataArray = res;
    } else if (res && res.data && Array.isArray(res.data)) {
      dataArray = res.data;
    } else if (res && res.list && Array.isArray(res.list)) {
      dataArray = res.list;
    }

    // 转换为下拉选项格式
    const options = dataArray.map((item: any) => ({
      label: `${item.versionNo}`,
      value: item.versionNo,
    }));

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

// 获取可添加的条文条款
export async function getCheckpointPendingRule(
  checkpointId: number,
  version: string = '',
  filter: string = '',
  current: number = 1,
  pageSize: number = 10,
) {
  try {
    const res = await request('/manager/Checkpoint/getCheckpointPendingRule', {
      method: 'GET',
      params: {
        checkpointId,
        version,
        filter,
        page: current,
        size: pageSize,
      },
    });

    let dataArray: any[] = [];
    let total = 0;

    // 处理不同的数据结构
    if (Array.isArray(res)) {
      dataArray = res;
      total = res.length;
    } else if (res && res.data && Array.isArray(res.data)) {
      dataArray = res.data;
      total = res.total || res.data.length;
    } else if (res && res.list && Array.isArray(res.list)) {
      dataArray = res.list;
      total = res.total || res.list.length;
    }

    // 转换数据格式以适配 ProTable 的树形结构
    const convertToTreeData = (items: any[]): any[] => {
      if (!items || !Array.isArray(items)) return [];

      return items.map((item) => {
        const convertedItem = {
          ...item,
          key: item.id,
        };

        // 如果有子项，递归转换子项
        if (item.child && Array.isArray(item.child) && item.child.length > 0) {
          convertedItem.children = convertToTreeData(item.child);
        }

        return convertedItem;
      });
    };

    const treeData = convertToTreeData(dataArray);

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

// 添加条文条款
export async function addCheckpointRule(
  checkpointId: number,
  ruleNumStrs: string[],
  version: string = '',
) {
  try {
    const res = await request('/manager/Checkpoint/addCheckpointRule', {
      method: 'POST',
      data: {
        id: checkpointId.toString(),
        mapObjList: ruleNumStrs.map((numStr) => ({
          id: numStr, // 使用numStr作为id
          version: version,
        })),
      },
    });

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

// 删除条文条款
export async function delCheckpointRule(
  checkpointId: number,
  ruleData: Array<{ id: React.Key; version?: string }>,
) {
  try {
    const res = await request('/manager/Checkpoint/delCheckpointRule', {
      method: 'POST',
      data: {
        id: checkpointId.toString(),
        mapObjList: ruleData.map((item) => ({
          id: item.id.toString(),
          version: item.version || '',
        })),
      },
    });

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