import React, { Key, 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';
import { ProColumns } from '@ant-design/pro-components';
import { getResponsibilityCenterConnectableList } from './service';
import { log } from 'mathjs';

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

const TableTransfer = React.forwardRef(
  (
    {
      leftColumns,
      rightColumns,
      record,
      onSave,
      ...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 () => {
      let resp = await getResponsibilityCenterConnectableList({
        responsibilityId: record.responsibilityId,
      });
      if (resp) {
        const defaultDepartments = record.departments
          ? record.departments.map((a: any) => ({
              id: a.departmentId,
              code: a.departmentId,
              departmentCode: '',
              departmentName: a.departmentName,
              departmentStatus: 0,
            }))
          : [];
        resp = resp.map((a: any) => ({ ...a, code: a.id }));
        set_datasource([...resp, ...defaultDepartments]);
        _set_data([...resp, ...(record.departments ? record.departments : [])]);
        const defaultSelctedkeys = record.departments
          ? record.departments.map((a: any) => a.departmentId)
          : [];
        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.code));
        onSave(targetKeys, items);
      },
    }));

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

    return (
      <Transfer
        className="TableTransfer"
        showSearch
        titles={['待选项', '已选项']}
        locale={{
          itemUnit: '项',
          itemsUnit: '项',
          searchPlaceholder: '请输入',
        }}
        oneWay={false}
        onChange={onChange}
        onSelectChange={onSelectChange}
        dataSource={datasource}
        rowKey={(record) => record.code}
        targetKeys={targetKeys}
        selectedKeys={selectedKeys}
        filterOption={(inputValue, item) => {
          return item.departmentName!.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(({ code }) => code);
              const diffKeys = selected
                ? difference(treeSelectedKeys, listSelectedKeys)
                : difference(listSelectedKeys, treeSelectedKeys);
              onItemSelectAll(diffKeys as string[], selected);
            },
            onSelect({ code }, selected) {
              onItemSelect(code as string, selected);
            },
            selectedRowKeys: listSelectedKeys,
          };

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

export default TableTransfer;
