import React, { Key, useEffect, useImperativeHandle, useState } from 'react';
import { Transfer } from 'antd';
import { TransferItem, TransferProps } from 'antd/es/transfer';
import { difference } from 'lodash';
import { TableRowSelection } from 'antd/es/table/interface';
import { KCIMTable } from '@/components/KCIMTable';
import { ProColumns } from '@ant-design/pro-components';
import { Tabs } from 'antd';
import { getAccountingSubjectList } from '../../accountingAccountSet/accountingSubMana/service';

function flatten(list: any[]) {
  let result: any[] = [];
  list.forEach((item) => {
    result.push(item);
    if (item.children) {
      result = result.concat(flatten(item.children));
    }
  });
  return result;
}

function getUniqueSubsetsByProperty(treeData: any[], uniqueProperty: string) {
  const result: any[] = [];
  const uniqueSet = new Set();

  function traverse(
    node: { [x: string]: any; children: string | any[] },
    isRoot = true,
  ) {
    if (!node) return;

    // 获取节点的唯一属性值
    const uniqueValue = node[uniqueProperty];

    // 如果节点是根节点，不添加到结果集，但处理它的子节点
    if (!isRoot && !uniqueSet.has(uniqueValue)) {
      result.push(node);
      uniqueSet.add(uniqueValue);
    }

    // 递归处理子节点
    if (node.children && node.children.length > 0) {
      for (let child of node.children) {
        traverse(child, false); // 子节点传递 isRoot = false
      }
    }
  }

  for (let rootNode of treeData) {
    traverse(rootNode);
  }

  return result;
}

function removeSelectedKeys(nodes: any[], keysToRemove: string[]): any[] {
  const result = nodes
    .map((node) => {
      // 检查 id 是否存在
      if (!node || node.id === undefined || node.id === null) {
        return node; // 或者返回 null, 取决于你的业务逻辑
      }

      if (keysToRemove.includes(node.id)) {
        return null;
      }

      if (node.children) {
        node.children = removeSelectedKeys(node.children, keysToRemove);
        if (node.children.length === 0) {
          return null;
        }
      }

      return node;
    })
    .filter((node) => node !== null);
  return result;
}

interface TableTransferProps extends TransferProps<TransferItem> {
  leftColumns: ProColumns[];
  rightColumns: ProColumns[];
  record: any;
  keyName: string;
  onSave: (selectedKeys: Key[], selectedRowKeys: any[]) => void;
}

const TableTransfer = React.forwardRef(
  (
    {
      leftColumns,
      rightColumns,
      keyName,
      record,
      onSave,
      ...restProps
    }: TableTransferProps,
    ref,
  ) => {
    const [_data, _set_data] = useState<any>();
    const [targetKeys, setTargetKeys] = useState<string[]>(
      record.accountingIds
        ? [...record.accountingIds.map((a: string) => Number(a))]
        : [],
    );
    const [datasource, set_datasource] = useState<any[]>([]);
    const [filteredDataSource, setFilteredDataSource] = useState<any[]>([]);
    const [selectedKeys, setSelectedKeys] = useState<string[]>(
      record.accountingIds
        ? [...record.accountingIds.map((a: string) => Number(a))]
        : [],
    );
    const [accountType, set_accountType] = useState(1);
    const [tabs, set_tabs] = useState<any[]>([]);

    const getFuncList = async () => {
      const resp = await getAccountingSubjectList({
        accountType: 1,
        pageSize: 500,
        current: 1,
      });
      if (resp) {
        set_datasource(resp.list);
        _set_data(resp.list);
      }
    };

    const onChange = (nextTargetKeys: string[]) => {
      setTargetKeys(nextTargetKeys);
      const clonedDataSource = JSON.parse(JSON.stringify(datasource));
      const filteredData = removeSelectedKeys(clonedDataSource, nextTargetKeys);
      setFilteredDataSource(filteredData);
    };

    const onSelectChange = (
      sourceSelectedKeys: string[],
      targetSelectedKeys: string[],
    ) => {
      setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys]);
    };

    useEffect(() => {
      // 过滤出左侧的待选项数据
      const clonedDataSource = JSON.parse(JSON.stringify(datasource));
      const filtered = removeSelectedKeys(clonedDataSource, targetKeys);
      setFilteredDataSource(filtered);
    }, [datasource, targetKeys]);

    useImperativeHandle(ref, () => ({
      save: async () => {
        const items = flatten(datasource).filter((a) =>
          targetKeys.includes(a[`${keyName}`]),
        );
        onSave(targetKeys, getUniqueSubsetsByProperty(items, `${keyName}`));
      },
    }));

    const onTabChanged = (key: string) => {
      set_accountType(Number(key));
    };

    const handleTreeItemSelect = (key: string, selected: boolean) => {
      let newSelectedKeys = [...selectedKeys];

      const updateSelection = (node: TransferItem, isSelected: boolean) => {
        const keyIndex = newSelectedKeys.indexOf(node[keyName]);
        if (isSelected && keyIndex === -1) {
          newSelectedKeys.push(node[keyName]);
        } else if (!isSelected && keyIndex > -1) {
          newSelectedKeys.splice(keyIndex, 1);
        }

        if (node.children) {
          node.children.forEach((child: any) =>
            updateSelection(child, isSelected),
          );
        }
      };

      const node = flatten(datasource).find((item) => item[keyName] === key);

      if (node) {
        updateSelection(node, selected);
      }

      // 确保没有重复项
      newSelectedKeys = Array.from(new Set(newSelectedKeys));
      setSelectedKeys(newSelectedKeys);
    };

    useEffect(() => {
      getFuncList();
    }, [accountType]);

    useEffect(() => {
      set_tabs([
        { label: '收入', key: 1 },
        { label: '支出', key: 2 },
      ]);
    }, []);

    return (
      <div>
        <Tabs
          defaultActiveKey={tabs.length > 0 ? tabs[0].key : undefined}
          items={tabs}
          onChange={(key) => onTabChanged(key)}
        />
        <Transfer
          className="TableTransfer"
          showSearch
          titles={['待选项', '已选项']}
          locale={{
            itemUnit: '项',
            itemsUnit: '项',
            searchPlaceholder: '请输入',
          }}
          oneWay={false}
          onChange={onChange}
          onSelectChange={onSelectChange}
          dataSource={flatten(datasource)}
          rowKey={(record) => record[`${keyName}`]}
          targetKeys={targetKeys}
          selectedKeys={selectedKeys}
          filterOption={(inputValue, item) =>
            item.accountingName.indexOf(inputValue) !== -1
          }
        >
          {({
            direction,
            filteredItems,
            onItemSelectAll,
            onItemSelect,
            selectedKeys: listSelectedKeys,
            disabled: listDisabled,
          }) => {
            const columns = direction === 'left' ? leftColumns : rightColumns;

            const rowSelection: TableRowSelection<TransferItem> = {
              getCheckboxProps: (item) => ({
                disabled: listDisabled || item.disabled,
              }),
              onSelectAll(selected, selectedRows) {
                const treeSelectedKeys = selectedRows.map(
                  (a) => a[`${keyName}`],
                );
                const diffKeys = selected
                  ? difference(treeSelectedKeys, listSelectedKeys)
                  : difference(listSelectedKeys, treeSelectedKeys);
                onItemSelectAll(diffKeys as string[], selected);
              },
              onSelect(item, selected) {
                onItemSelect(item[`${keyName}`], selected);
                handleTreeItemSelect(item[`${keyName}`], selected);
              },
              selectedRowKeys: listSelectedKeys,
            };

            // 使用 filteredDataSource 作为数据源，确保左侧表格正确显示未选中的数据

            const flattenAndFilter = (
              list: any[],
              targetKeys: string | any[],
            ) => {
              let result: any[] = [];
              list.forEach((item: { [x: string]: any; children: any }) => {
                if (targetKeys.includes(item[keyName])) {
                  // 如果父节点已经选中，不再单独加入子节点
                  result.push(item);
                } else if (item.children) {
                  // 递归处理子节点
                  const filteredChildren = flattenAndFilter(
                    item.children,
                    targetKeys,
                  );
                  if (filteredChildren.length > 0) {
                    result = result.concat(filteredChildren);
                  }
                }
              });
              return result;
            };

            const dataSourceToUse =
              direction === 'left'
                ? filteredDataSource // 左侧的未选中项
                : flattenAndFilter(datasource, targetKeys); // 右侧的已选中项

            return (
              <KCIMTable
                rowSelection={rowSelection}
                columns={columns as TransferItem[]}
                dataSource={dataSourceToUse}
                size="small"
                bordered={false}
                rowKey={keyName}
                scroll={{ y: 280 }}
                pagination={{
                  showTitle: false,
                  pageSize: 9,
                  showLessItems: false,
                  simple: true,
                  showTotal: () => false,
                }}
                tableAlertRender={false}
                style={{ pointerEvents: listDisabled ? 'none' : undefined }}
                onRow={(row) => ({
                  onClick: () => {
                    const selected = !listSelectedKeys.includes(
                      row[`${keyName}`],
                    );
                    onItemSelect(row[`${keyName}`], selected);
                    handleTreeItemSelect(row[`${keyName}`], selected);
                  },
                })}
              />
            );
          }}
        </Transfer>
      </div>
    );
  },
);

export default TableTransfer;
