/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2025-04-14 10:28:42
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-07-09 15:04:26
 * @FilePath: /pfmBackMana/src/pages/baseInfoMana/empMana/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import KCIMPagecontainer from '@/components/KCIMPageContainer';
import EmployeeList from './components/EmployeeList/EmployeeList';
import './style.less';

import { Tabs, Input, Popconfirm, message, Button } from 'antd';
import { createFromIconfontCN } from '@ant-design/icons';
import { KCIMTable } from '@/components/KCIMTable';
import { useRef, useState } from 'react';
import { ActionType, ProColumns } from '@ant-design/pro-components';
import TableSelecter from './components/tableSelector';
import {
  fetchEmpDeptDict,
  fetchEmpGroup,
  fetchEmpRoleDict,
  deleteEmpRole,
  deleteEmpDept,
  deleteEmpGroup,
  addEmpRole,
  addEmpDept,
  addEmpGroup,
} from './service';
import { Employee } from './service';

const items = [
  {
    label: `角色`,
    key: 'ROLE',
  },
  {
    label: `查核单位`,
    key: 'UNIT',
  },
  {
    label: `查核组`,
    key: 'GROUP',
  },
];

export const roleColumns: ProColumns[] = [
  {
    title: '角色代码',
    dataIndex: 'roleCode',
  },
  {
    title: '角色名称',
    dataIndex: 'roleName',
  },
];

export const unitColumns: ProColumns[] = [
  {
    title: '单位名称',
    dataIndex: 'deptName',
  },
  {
    title: '单位负责人',
    dataIndex: 'empName',
  },
];

export const groupColumns: ProColumns[] = [
  {
    title: '查核组',
    dataIndex: 'checkGroupName',
  },
  {
    title: '组长',
    dataIndex: 'employeeName',
  },
];

const IconFont = createFromIconfontCN({
  scriptUrl: '',
});

function EmpMana() {
  const tableRef = useRef<ActionType>();
  const [selectedEmployee, setSelectedEmployee] = useState<Employee | null>(
    null,
  );
  const [searchKeyword, setSearchKeyword] = useState<string>('');
  const [searchPlaceholder, setSearchPlaceholder] =
    useState<string>('单位名称、负责人');

  // 保存原始数据，用于本地搜索
  const [originalRoleData, setOriginalRoleData] = useState<any[]>([]);
  const [originalUnitData, setOriginalUnitData] = useState<any[]>([]);
  const [originalGroupData, setOriginalGroupData] = useState<any[]>([]);

  // 当前过滤后的数据
  const [filteredData, setFilteredData] = useState<any[]>([]);

  // 批量选择相关状态
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [selectedRows, setSelectedRows] = useState<any[]>([]);

  // 将optionColumns改为函数
  const getOptionColumns = (type: string): ProColumns[] => [
    {
      title: '操作',
      key: 'option',
      width: 80,
      valueType: 'option',
      render: (_: any, record: any) => {
        return [
          <Popconfirm
            title={'是否确认删除？'}
            onConfirm={() => {
              // 这里直接用type参数，确保和tab一致
              if (type === 'ROLE') {
                deleteTableHandle({ ...record, _type: 'ROLE' });
              } else if (type === 'UNIT') {
                deleteTableHandle({ ...record, _type: 'UNIT' });
              } else if (type === 'GROUP') {
                deleteTableHandle({ ...record, _type: 'GROUP' });
              }
            }}
            okText="确定"
            cancelText="取消"
          >
            <a key="emp">删除</a>
          </Popconfirm>,
        ];
      },
    },
  ];

  // set_tableColumns时动态生成操作列
  const [tableColumns, set_tableColumns] = useState<ProColumns[]>([
    ...unitColumns,
    ...getOptionColumns('UNIT'),
  ]);
  const [tableSelecterVisible, set_tableSelecterVisible] =
    useState<boolean>(false);
  const [tableSelecterType, set_tableSelecterType] = useState<any>('UNIT');
  const [currentEdit, set_currentEdit] = useState<any>({});

  const getEmpListData = async (params: any) => {};

  const tableSelecterCommit = async (keys: React.Key[], rows: any[]) => {
    if (!selectedEmployee) {
      message.error('请先选择员工');
      return;
    }

    const empId = selectedEmployee.id;

    try {
      let response;

      // 根据当前tab类型确定要使用的接口
      if (tableSelecterType === 'ROLE') {
        // 添加角色关联
        const mapIdList = rows.map((row) => row.roleId.toString());
        response = await addEmpRole({
          id: empId.toString(),
          mapIdList,
        });
      } else if (tableSelecterType === 'UNIT') {
        // 添加部门关联 - 修正入参格式
        const mapObjList = rows.map((row) => ({
          id: row.id.toString(),
          name: row.deptName || row.name,
          type: "0" // 默认类型为0
        }));
        response = await addEmpDept({
          id: empId.toString(),
          name: selectedEmployee.name,
          mapObjList,
        });
      } else if (tableSelecterType === 'GROUP') {
        // 添加查核组关联
        const mapIdList = rows.map((row) => row.id.toString());
        response = await addEmpGroup({
          id: empId.toString(),
          mapIdList,
        });
      }

      if (response) {
        message.success('添加成功');
        // 刷新当前表格数据
        tableRef.current?.reload();
      }
    } catch (error) {
      console.error('添加关联失败', error);
      message.error('添加失败，请稍后重试');
    }

    // 关闭选择器
    set_tableSelecterVisible(false);
  };

  const getTableData = async (params: any) => {
    if (!selectedEmployee) {
      return {
        data: [],
        success: true,
        total: 0,
      };
    }

    const empId = selectedEmployee.id;

    try {
      // 根据当前选中的tab调用不同的接口
      if (tableSelecterType === 'ROLE') {
        const response = await fetchEmpRoleDict({
          empId,
          // 不传递filter参数，全部在前端过滤
        });

        // 保存原始数据用于本地搜索
        setOriginalRoleData(response || []);

        // 根据搜索关键词过滤数据
        const filtered = filterDataByKeyword(response || [], searchKeyword);
        setFilteredData(filtered);

        // 返回过滤后的数据
        return {
          data: filtered,
          success: true,
        };
      } else if (tableSelecterType === 'UNIT') {
        const response = await fetchEmpDeptDict({
          empId,
          // 不传递filter参数，全部在前端过滤
        });

        // 保存原始数据用于本地搜索
        setOriginalUnitData(response || []);

        // 根据搜索关键词过滤数据
        const filtered = filterDataByKeyword(response || [], searchKeyword);
        setFilteredData(filtered);

        // 返回过滤后的数据
        return {
          data: filtered,
          success: true,
        };
      } else if (tableSelecterType === 'GROUP') {
        const response = await fetchEmpGroup({
          empId,
          // 不传递filter参数，全部在前端过滤
        });

        // 保存原始数据用于本地搜索
        setOriginalGroupData(response || []);

        // 根据搜索关键词过滤数据
        const filtered = filterDataByKeyword(response || [], searchKeyword);
        setFilteredData(filtered);

        // 返回过滤后的数据
        return {
          data: filtered,
          success: true,
        };
      }

      return { data: [], success: true };
    } catch (error) {
      console.error('获取数据失败', error);
      message.error('获取数据失败');
      return { data: [], success: false };
    }
  };

  // 本地搜索函数，根据关键词过滤数据
  const filterDataByKeyword = (data: any[], keyword: string) => {
    if (!keyword || keyword.trim() === '') {
      return data;
    }

    const lowercaseKeyword = keyword.toLowerCase();

    return data.filter((item) => {
      // 根据不同的tab类型，搜索不同的字段
      if (tableSelecterType === 'ROLE') {
        return (
          (item.roleCode &&
            item.roleCode.toLowerCase().includes(lowercaseKeyword)) ||
          (item.roleName &&
            item.roleName.toLowerCase().includes(lowercaseKeyword))
        );
      } else if (tableSelecterType === 'UNIT') {
        return (
          (item.deptName && item.deptName.toLowerCase().includes(lowercaseKeyword)) ||
          (item.empName &&
            item.empName.toLowerCase().includes(lowercaseKeyword))
        );
      } else if (tableSelecterType === 'GROUP') {
        return (
          (item.checkGroupName &&
            item.checkGroupName.toLowerCase().includes(lowercaseKeyword)) ||
          (item.employeeName &&
            item.employeeName.toLowerCase().includes(lowercaseKeyword))
        );
      }
      return false;
    });
  };

  // 执行本地搜索的函数
  const handleSearch = () => {
    let dataToFilter: any[] = [];

    // 根据当前tab选择相应的原始数据
    if (tableSelecterType === 'ROLE') {
      dataToFilter = originalRoleData;
    } else if (tableSelecterType === 'UNIT') {
      dataToFilter = originalUnitData;
    } else if (tableSelecterType === 'GROUP') {
      dataToFilter = originalGroupData;
    }

    // 过滤数据
    const filtered = filterDataByKeyword(dataToFilter, searchKeyword);
    setFilteredData(filtered);

    // 刷新表格
    tableRef.current?.reload();
  };

  // 批量删除处理函数
  const handleBatchDelete = async () => {
    if (selectedRowKeys.length === 0) {
      message.error('请选择要删除的数据');
      return;
    }

    try {
      let response;
      let idsToDelete: number[] = [];

      // 根据当前tab类型确定要使用的ID字段和对应的删除接口
      if (tableSelecterType === 'ROLE') {
        idsToDelete = selectedRows.map((row) => row.id);
        response = await deleteEmpRole(idsToDelete);
      } else if (tableSelecterType === 'UNIT') {
        const itemsToDelete = selectedRows.map((row) => ({ 
          id: row.id.toString(), 
          type: row.type || '0' 
        }));
        response = await deleteEmpDept(itemsToDelete);
      } else if (tableSelecterType === 'GROUP') {
        idsToDelete = selectedRows.map((row) => row.id);
        response = await deleteEmpGroup(idsToDelete);
      }

      if (response) {
        message.success(`批量删除成功，共删除 ${selectedRowKeys.length} 条数据`);

        // 从本地缓存的数据中删除对应记录
        if (tableSelecterType === 'ROLE') {
          setOriginalRoleData(
            originalRoleData.filter((item) => !idsToDelete.includes(item.id)),
          );
        } else if (tableSelecterType === 'UNIT') {
          const deletedIds = selectedRows.map(row => row.id);
          setOriginalUnitData(
            originalUnitData.filter((item) => !deletedIds.includes(item.id)),
          );
        } else if (tableSelecterType === 'GROUP') {
          setOriginalGroupData(
            originalGroupData.filter((item) => !idsToDelete.includes(item.id)),
          );
        }

        // 清空选中状态
        setSelectedRowKeys([]);
        setSelectedRows([]);

        // 刷新当前搜索结果
        handleSearch();
      }
    } catch (error) {
      console.error('批量删除失败', error);
      message.error('批量删除失败');
    }
  };

  // 处理行选择变化
  const handleRowSelectionChange = (newSelectedRowKeys: React.Key[], newSelectedRows: any[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
    setSelectedRows(newSelectedRows);
  };

  // deleteTableHandle里优先用record._type（如果有）
  const deleteTableHandle = async (record: any) => {
    try {
      let response;
      let idToDelete: number;
      // 优先用record._type，否则用tableSelecterType
      const type = record._type || tableSelecterType;
      if (type === 'ROLE') {
        idToDelete = record.id;
        response = await deleteEmpRole([idToDelete]);
      } else if (type === 'UNIT') {
        // 修正：使用record.id与批量删除保持一致
        idToDelete = record.id;
        response = await deleteEmpDept([{ id: idToDelete.toString(), type: record.type || '0' }]);
      } else if (type === 'GROUP') {
        idToDelete = record.id;
        response = await deleteEmpGroup([idToDelete]);
      }
      if (response) {
        message.success('删除成功');
        if (type === 'ROLE') {
          setOriginalRoleData(
            originalRoleData.filter((item) => item.id !== idToDelete),
          );
        } else if (type === 'UNIT') {
          // 修正：使用id过滤与批量删除保持一致
          setOriginalUnitData(
            originalUnitData.filter((item) => item.id !== idToDelete),
          );
        } else if (type === 'GROUP') {
          setOriginalGroupData(
            originalGroupData.filter((item) => item.id !== idToDelete),
          );
        }
        handleSearch();
      }
      return true;
    } catch (error) {
      console.error('删除失败', error);
      message.error('删除失败');
      return false;
    }
  };

  // onChange里动态生成操作列
  const onChange = (key: string) => {
    if (key == 'ROLE') {
      set_tableSelecterType('ROLE');
      set_tableColumns([...roleColumns, ...getOptionColumns('ROLE')]);
      setSearchPlaceholder('角色代码、名称');
    } else if (key == 'UNIT') {
      set_tableSelecterType('UNIT');
      set_tableColumns([...unitColumns, ...getOptionColumns('UNIT')]);
      setSearchPlaceholder('单位名称、负责人');
    } else if (key == 'GROUP') {
      set_tableSelecterType('GROUP');
      set_tableColumns([...groupColumns, ...getOptionColumns('GROUP')]);
      setSearchPlaceholder('查核组、组长');
    }
    // 重置搜索关键词和选中状态
    setSearchKeyword('');
    setSelectedRowKeys([]);
    setSelectedRows([]);
    // 切换tab后，触发表格重新加载数据
    tableRef.current?.reload();
  };

  const addhandle = () => {
    if (!selectedEmployee) {
      message.warning('请先选择一个员工');
      return;
    }
    set_tableSelecterVisible(true);
    set_currentEdit({});
  };

  return (
    <KCIMPagecontainer className="empMana" title={false} style={{ position: 'relative' }}>
      <TableSelecter
        onVisibleChange={(bool) => set_tableSelecterVisible(bool)}
        title={selectedEmployee ? `关联 - ${selectedEmployee.name}` : '关联'}
        rowKey={tableSelecterType === 'ROLE' ? 'roleId' : 'id'}
        tableSelecterType={tableSelecterType}
        record={currentEdit}
        open={tableSelecterVisible}
        onFinish={(keys, rows) => tableSelecterCommit(keys, rows)}
        selectedEmployee={selectedEmployee}
      />
      <EmployeeList
        onSelect={(employee) => {
          setSelectedEmployee(employee);
          // 选择员工后，触发表格重新加载数据
          tableRef.current?.reload();
        }}
      />
      <div className="content">
        <Tabs items={items} activeKey={tableSelecterType} onChange={onChange} />
        <div className="toolBar">
          <div className="filter">
            <div className="filterItem" style={{ marginRight: 16, width: 220 }}>
              <span className="label" style={{ whiteSpace: 'nowrap' }}>
                {' '}
                检索：
              </span>
              <Input
                placeholder={searchPlaceholder}
                allowClear
                value={searchKeyword}
                suffix={
                  <IconFont
                    type="iconsousuo"
                    style={{ color: '#99A6BF' }}
                    onClick={() => {
                      handleSearch();
                    }}
                  />
                }
                onChange={(e) => {
                  setSearchKeyword(e.target.value);
                  // 如果清空了搜索框，立即恢复显示所有数据
                  if (!e.target.value) {
                    handleSearch();
                  }
                }}
                onPressEnter={(e) => {
                  // 搜索框按回车时执行本地搜索
                  handleSearch();
                }}
              />
            </div>
          </div>
          <div className="btnGroup">
            <div className="add" onClick={() => addhandle()}>
              添加
            </div>
          </div>
        </div>

        <div style={{ marginTop: 16, paddingBottom: selectedRowKeys.length > 0 ? 68 : 0 }}>
          <KCIMTable
            columns={tableColumns}
            actionRef={tableRef}
            rowKey="id"
            request={(params) => getTableData(params)}
            pagination={false}
            rowSelection={{
              selectedRowKeys,
              onChange: handleRowSelectionChange,
            }}
            tableAlertRender={false}
          />
        </div>

      </div>

      {/* 批量操作栏 - 固定在右侧内容区域底部 */}
      {selectedRowKeys.length > 0 && (
        <div
          style={{
            position: 'absolute',
            bottom:0, // empMana的padding
            left:0, // 从人员列表右侧开始
            right: 0, // empMana的padding
            height: 48,
            background: '#FFFFFF',
            boxShadow: '0px -8px 16px 0px rgba(64,85,128,0.1)',
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            padding: '0 16px',
            zIndex: 1000,
          }}
        >
          <span style={{ 
            color: '#333333', 
            fontSize: 14,
            fontFamily: 'SourceHanSansCN-Normal, SourceHanSansCN',
            fontWeight: 400,
          }}>
            已选择 {selectedRowKeys.length} 项，将进行批量删除
          </span>
          <div style={{ display: 'flex', gap: 12 }}>
            <div
              onClick={() => {
                setSelectedRowKeys([]);
                setSelectedRows([]);
              }}
              style={{
                cursor: 'pointer',
                display: 'inline-block',
                fontSize: 14,
                fontFamily: 'SourceHanSansCN-Normal, SourceHanSansCN',
                fontWeight: 400,
                color: '#666666',
                lineHeight: '24px',
                padding: '0 14px',
                background: '#ffffff',
                border: '1px solid #dae2f2',
                borderRadius: 4,
              }}
            >
              取消选择
            </div>
            <Popconfirm
              title={`确认批量删除所选${
                tableSelecterType === 'ROLE'
                  ? '角色'
                  : tableSelecterType === 'UNIT'
                  ? '查核单位'
                  : '查核组'
              }？`}
              okText="确定"
              cancelText="取消"
              onConfirm={handleBatchDelete}
            >
              <div
                style={{
                  cursor: 'pointer',
                  display: 'inline-block',
                  fontSize: 14,
                  fontFamily: 'SourceHanSansCN-Normal, SourceHanSansCN',
                  fontWeight: 400,
                  color: '#ffffff',
                  lineHeight: '24px',
                  padding: '0 14px',
                  background: '#3377ff',
                  borderRadius: 4,
                }}
              >
                批量删除
              </div>
            </Popconfirm>
          </div>
        </div>
      )}
    </KCIMPagecontainer>
  );
}

export default EmpMana;
