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 { Tabs } from 'antd';

import { log } from 'mathjs';
import { getAccountingSubjectList } from '../../accountingAccountSet/accountingSubMana/service';
import { getIncomeCollectionListHasConnected } from './service';

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[]>([]);
    const [datasource, set_datasource] = useState<any[]>([]);
    const [selectedKeys, setSelectedKeys] = useState<string[]>([]);

    //获取列表
    const getFuncList = async () => {
      const { id } = record;
      const resp = await getAccountingSubjectList({
        accountType: 1,
        shareParamId: id,
        pageSize: 500,
        current: 1,
      });

      if (resp) {
        set_datasource(resp.list);
        _set_data(resp.list);
        // setTargetKeys(accountingIds);
      }
    };

    const setInit = async () => {
      const { id } = record;
      const resp = await getIncomeCollectionListHasConnected({ id });
      if (resp) {
        const tempArr = resp
          ? resp.map((item: any) => item.accountingCode)
          : [];
        setTargetKeys([...tempArr]);
      }
    };

    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[`${keyName}`]),
        );
        onSave(targetKeys, items);
      },
    }));

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

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

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

export default TableTransfer;
