import React, { useEffect, useImperativeHandle, useState } from 'react';
import { Transfer } from 'antd';
import { TransferItem, TransferProps } from 'antd/es/transfer';
import { ColumnsType } from 'antd/es/table';
import { difference } from 'lodash';
import { TableRowSelection } from 'antd/es/table/interface';
import { KCIMTable } from '@/components/KCIMTable';

interface TableTransferProps extends TransferProps<TransferItem> {
  leftColumns: ColumnsType<any>;
  rightColumns: ColumnsType<any>;
}

const TableTransfer = React.forwardRef(
  ({ leftColumns, rightColumns, ...restProps }: TableTransferProps, ref) => {
    const [_data, _set_data] = useState<any>();
    const [targetKeys, setTargetKeys] = useState<string[]>([]);
    const [datasource, set_datasource] = useState<any[]>([]);
    const [selectedKeys, setSelectedKeys] = useState<string[]>([]);

    //获取单元
    const getFuncList = async () => {
      // const resp = await getTotalEmps({
      //     computeDate: currentComputeDate as string,
      //     unitCode: currentSelectedTreeNode.code
      // });
      // if (resp) {
      //     //_set_data(resp);
      //     const allData = resp.allEmployees.concat(resp.checkEmployees);
      //     set_datasource(allData);
      //     const defaultSelctedkeys = resp.checkEmployees.map((item: any) => item.empNo);
      //     setTargetKeys(defaultSelctedkeys);
      // }
    };

    const onChange = (nextTargetKeys: string[]) => {
      setTargetKeys(nextTargetKeys);
    };

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

    useImperativeHandle(ref, () => ({
      save: async () => {
        // const items = datasource.filter(a => targetKeys.includes(a.empNo));
        // const resp = await saveEmpsRequest(items);
        // if (resp) {
        //     tableRef.current?.reload();
        // }
      },
    }));

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

    return (
      <Transfer
        className="TableTransfer"
        showSearch
        titles={['待选项', '已选项']}
        locale={{
          itemUnit: '项',
          itemsUnit: '项',
          searchPlaceholder: '请输入',
        }}
        oneWay={true}
        onChange={onChange}
        onSelectChange={onSelectChange}
        dataSource={datasource}
        rowKey={(record) => record.empNo}
        targetKeys={targetKeys}
        selectedKeys={selectedKeys}
        filterOption={(inputValue, item) => {
          return item.name!.indexOf(inputValue) !== -1;
        }}
      >
        {({
          direction,
          filteredItems,
          onItemSelectAll,
          onItemSelect,
          selectedKeys: listSelectedKeys,
          disabled: listDisabled,
        }) => {
          // console.log({ filteredItems, listSelectedKeys,direction });
          const columns = direction === 'left' ? leftColumns : rightColumns;

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

          return (
            <KCIMTable
              rowSelection={rowSelection}
              columns={columns as TransferItem[]}
              dataSource={filteredItems}
              size="small"
              bordered={false}
              rowKey={'empNo'}
              pagination={{
                showTitle: false,
                pageSize: 9,
                showLessItems: false,
                simple: true,
                showTotal: () => false,
              }}
              tableAlertRender={false}
              style={{ pointerEvents: listDisabled ? 'none' : undefined }}
              onRow={({ empNo, disabled: itemDisabled }) => ({
                onClick: () => {
                  if (itemDisabled || listDisabled) return;
                  onItemSelect(
                    empNo as string,
                    !listSelectedKeys.includes(empNo as string),
                  );
                },
              })}
            />
          );
        }}
      </Transfer>
    );
  },
);

export default TableTransfer;
