import React, { useEffect, useState } from 'react';
import { Input, message } from 'antd';
import { KCIMTable } from '@/components/KCIMTable';
import { createFromIconfontCN } from '@ant-design/icons';

import { ModalForm, ProColumns } from '@ant-design/pro-components';
import { roleColumns, unitColumns, groupColumns } from '..';
import {
  getEmpRoleDict,
  getEmpDeptDict,
  getEmpGroupDict,
  RoleDictItem,
  DeptDictItem,
  GroupDictItem,
} from '../service';

// import './style.less';

interface TableSelecterProps {
  record: any;
}

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

// 字典数据的列定义
const dictRoleColumns: ProColumns[] = [
  {
    title: '角色代码',
    dataIndex: 'roleCode',
  },
  {
    title: '角色名称',
    dataIndex: 'roleName',
  },
];

const dictUnitColumns: ProColumns[] = [
  {
    title: '单位名称',
    dataIndex: 'deptName',
    render: (_, record: any) => record.deptName || record.name,
  },
  {
    title: '单位负责人',
    dataIndex: 'manager_name',
    render: (_, record: any) => record.manager_name || record.deptManagerName,
  },
];

const dictGroupColumns: ProColumns[] = [
  {
    title: '查核组',
    dataIndex: 'name',
    render: (_, record: any) => record.name || record.checkGroupName,
  },
  {
    title: '组长',
    dataIndex: 'groupManagerName',
    render: (_, record: any) => record.groupManagerName || record.manager_name || record.managerName,
  },
];

const TableSelecter = ({
  tableSelecterType,
  record,
  open,
  title,
  onVisibleChange,
  rowKey = 'id',
  onFinish,
  selectedEmployee,
}: {
  record: any;
  open: boolean;
  title: string;
  onVisibleChange: (bool: boolean) => void;
  tableSelecterType: 'ROLE' | 'UNIT' | 'GROUP';
  rowKey?: string;
  onFinish?: (selectedKeys: React.Key[], selectedRows: any[]) => void;
  selectedEmployee?: any;
}) => {
  console.log('rowKey', rowKey);
  const Table = React.forwardRef(({}: TableSelecterProps, ref) => {
    const [datasource, set_datasource] = useState<any[]>([]);
    const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
    const [selectedRows, set_selectedRows] = useState<any[]>([]);
    const [showList, set_showList] = useState<any[]>([]);
    const [searchKeyword, setSearchKeyword] = useState<string>('');

    const onSelectChange = (
      newSelectedRowKeys: React.Key[],
      selectedRows: any,
    ) => {
      setSelectedKeys([...newSelectedRowKeys]);
      set_selectedRows([...selectedRows]);
    };

    const saveHandle = async () => {
      // 检查是否有必要的ID字段
      const hasRequiredFields = selectedRows.every((row) => {
        if (tableSelecterType === 'ROLE' && !row.roleId) {
          message.error('选中的角色缺少roleId字段');
          return false;
        } else if (tableSelecterType === 'UNIT' && !row.id) {
          message.error('选中的部门缺少id字段');
          return false;
        } else if (tableSelecterType === 'GROUP' && !row.id) {
          message.error('选中的查核组缺少id字段');
          return false;
        }
        return true;
      });

      if (!hasRequiredFields) return;

      onFinish && onFinish(selectedKeys, selectedRows);
      onVisibleChange(false);
    };

    // 获取字典数据
    const getTableData = async () => {
      try {
        if (!selectedEmployee) {
          message.error('请先选择员工');
          return Promise.resolve([]);
        }

        const empId = selectedEmployee.id;
        let response: any[] = [];

        // 根据当前tab类型确定使用哪个接口
        if (tableSelecterType === 'ROLE') {
          // 获取角色字典
          response = await getEmpRoleDict({ empId });
        } else if (tableSelecterType === 'UNIT') {
          // 获取部门字典
          response = await getEmpDeptDict({ empId });
        } else if (tableSelecterType === 'GROUP') {
          // 获取查核组字典
          response = await getEmpGroupDict({ empId });
        }

        // 处理响应数据
        if (response && response.length > 0) {
          // 确保所有数据都有id字段作为唯一标识
          const processedData = response.map((item) => {
            // 检查是否有必要的字段
            if (tableSelecterType === 'ROLE') {
              if (!item.id && item.roleId) {
                return { ...item, id: item.roleId };
              }
            } else if (tableSelecterType === 'GROUP') {
              // 查核组字典数据确保有正确的id字段
              if (!item.id && item.checkGroupId) {
                return { ...item, id: item.checkGroupId };
              }
            }
            return item;
          });

          set_datasource(processedData);
          set_showList(processedData);
        } else {
          set_datasource([]);
          set_showList([]);
        }

        return Promise.resolve(response);
      } catch (error) {
        console.error('获取字典数据失败', error);
        message.error('获取数据失败');
        return Promise.resolve([]);
      }
    };

    // 本地过滤数据
    const filterDataByKeyword = () => {
      if (!searchKeyword || searchKeyword.trim() === '') {
        set_showList(datasource);
        return;
      }

      const lowercaseKeyword = searchKeyword.toLowerCase();

      let filtered = [];

      if (tableSelecterType === 'ROLE') {
        filtered = datasource.filter((item: any) => {
          const matchRoleCode =
            item.roleCode &&
            item.roleCode.toLowerCase().includes(lowercaseKeyword);
          const matchRoleName =
            item.roleName &&
            item.roleName.toLowerCase().includes(lowercaseKeyword);
          return matchRoleCode || matchRoleName;
        });
      } else if (tableSelecterType === 'UNIT') {
        filtered = datasource.filter((item: any) => {
          // 尝试不同可能的字段名
          const deptNameMatch =
            (item.deptName &&
              item.deptName.toLowerCase().includes(lowercaseKeyword)) ||
            (item.name && item.name.toLowerCase().includes(lowercaseKeyword));

          const managerNameMatch =
            (item.manager_name &&
              item.manager_name.toLowerCase().includes(lowercaseKeyword)) ||
            (item.deptManagerName &&
              item.deptManagerName.toLowerCase().includes(lowercaseKeyword));

          return deptNameMatch || managerNameMatch;
        });
      } else if (tableSelecterType === 'GROUP') {
        filtered = datasource.filter((item: any) => {
          // 尝试不同可能的字段名
          const groupNameMatch =
            (item.name &&
              item.name.toLowerCase().includes(lowercaseKeyword)) ||
            (item.checkGroupName &&
              item.checkGroupName.toLowerCase().includes(lowercaseKeyword));

          const managerNameMatch =
            (item.groupManagerName &&
              item.groupManagerName.toLowerCase().includes(lowercaseKeyword)) ||
            (item.manager_name &&
              item.manager_name.toLowerCase().includes(lowercaseKeyword)) ||
            (item.managerName &&
              item.managerName.toLowerCase().includes(lowercaseKeyword));

          return groupNameMatch || managerNameMatch;
        });
      }

      set_showList(filtered);
    };

    useEffect(() => {
      if (selectedEmployee) {
        getTableData();
      }
    }, [tableSelecterType, selectedEmployee]);

    return (
      <div>
        <Input
          placeholder={'请输入搜索关键词'}
          allowClear
          value={searchKeyword}
          suffix={
            <IconFont
              style={{ color: '#99A6BF' }}
              type="iconsousuo"
              onClick={filterDataByKeyword}
            />
          }
          style={{ marginBottom: 8 }}
          onChange={(e) => {
            setSearchKeyword(e.target.value);
            // 如果清空搜索框，立即显示所有数据
            if (!e.target.value) {
              set_showList(datasource);
            }
          }}
          onPressEnter={() => filterDataByKeyword()}
        />
        <KCIMTable
          columns={
            tableSelecterType === 'ROLE'
              ? dictRoleColumns
              : tableSelecterType === 'UNIT'
              ? dictUnitColumns
              : dictGroupColumns
          }
          options={{
            density: true,
            setting: {
              listsHeight: 100,
            },
          }}
          rowKey={tableSelecterType === 'ROLE' ? 'roleId' : 'id'}
          scroll={{ y: 400 }}
          tableAlertRender={false}
          rowSelection={{
            selectedRowKeys: selectedKeys,
            onChange: onSelectChange,
          }}
          pagination={false}
          dataSource={showList}
        />
        <div className="footer">
          <span className="cancel" onClick={() => close()}>
            取消
          </span>
          <span
            className="ok"
            onClick={() => saveHandle()}
          >{`确认(${selectedKeys.length})`}</span>
        </div>
      </div>
    );
  });

  const close = () => {
    onVisibleChange && onVisibleChange(false);
  };

  return (
    <ModalForm
      className="TableSelecter"
      title={title}
      width={560}
      submitter={{
        render: false,
      }}
      open={open}
      modalProps={{
        closable: false,
      }}
    >
      <Table record={record}></Table>
    </ModalForm>
  );
};

export default TableSelecter;
