import { Table, Transfer } from 'antd';
import type { ColumnsType, TableRowSelection } from 'antd/es/table/interface';
import type { TransferItem, TransferProps } from 'antd/es/transfer';
import difference from 'lodash/difference';
import React, { useState } from 'react';

interface RecordType extends API.Device {
  key: string;
}

interface DataType extends API.Device {
  key: string;
}

const tableListDataSource = [];
const valueEnum = {
  0: 'close',
  1: 'running',
  2: 'online',
  3: 'error',
};

const creators = ['付小小', '曲丽丽', '林东东', '陈帅帅', '兼某某'];

for (let i = 0; i < 5; i += 1) {
  tableListDataSource.push({
    key: i,
    name: 'AppName',
    containers: Math.floor(Math.random() * 20),
    creator: creators[Math.floor(Math.random() * creators.length)],
    status: valueEnum[((Math.floor(Math.random() * 10) % 4) + '') as '0'],
    createdAt: Date.now() - Math.floor(Math.random() * 100000),
    memo: i % 2 === 1 ? '很长很长很长很长很长很长很长的文字要展示但是要留下尾巴' : '简短备注文案',
  });
}

const columns1 = [
  {
    title: '应用名称',
    width: 80,
    dataIndex: 'name',
  },
  {
    title: '容器数量',
    dataIndex: 'containers',
  },
  {
    title: '状态',
    width: 80,
    dataIndex: 'status',
  },
  {
    title: '创建者',
    width: 80,
    dataIndex: 'creator',
  },
];

const testData = Array(100)
  .fill(0)
  .map((v, index) => {
    return {
      id: index,
      key: index + '',
      createTime: '2023-10-17T10:47:51.629494+08:00',
      updateTime: '2023-10-26T11:02:39.559715+08:00',
      name: '控制设备',
      code: 'DEVICE00002',
      position: '二楼客厅',
      param: 'rtsp://admin:@192.168.10.203',
      spec: '',
      categoryFkId: 2,
      groupFkId: 3,
      isEnable: true,
      remark: '',
    };
  });

interface TableTransferProps extends TransferProps<TransferItem> {
  dataSource: DataType[];
  leftColumns: ColumnsType<DataType>;
  rightColumns: ColumnsType<DataType>;
}

// Customize Table Transfer
const TableTransfer = ({ leftColumns, rightColumns, ...restProps }: TableTransferProps) => (
  <Transfer
    {...restProps}
    locale={{ itemUnit: '项', itemsUnit: '项', searchPlaceholder: '请输入搜索内容' }}
    listStyle={{ width: 432 }}
    operationStyle={{ width: 32, alignItems: 'center' }}


  >
    {({
      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) {
        //   console.log(4545, selected)
        //   const treeSelectedKeys = selectedRows
        //     .filter((item) => !item.disabled)
        //     .map(({ key }) => key);
        //   const diffKeys = selected
        //     ? difference(treeSelectedKeys, listSelectedKeys)
        //     : difference(listSelectedKeys, treeSelectedKeys);
        //   onItemSelectAll(diffKeys as string[], selected);
        // },
        onChange(selected, selectedRows, info) {
          // console.log(4545, selected, info)

          if (info.type == 'all') {
            const treeSelectedKeys = selectedRows
              .filter((item) => !item.disabled)
              .map(({ key }) => key);
            const diffKeys = selected
              ? difference(treeSelectedKeys, listSelectedKeys)
              : difference(listSelectedKeys, treeSelectedKeys);
            console.log(45678, diffKeys);
            onItemSelectAll(diffKeys as string[], true);
          }
        },
        onSelect({ key }, selected) {
          console.log(890, key);
          onItemSelect(key as string, selected);
        },
        selectedRowKeys: listSelectedKeys,
      };

      return (
        <Table<any>
          rowSelection={rowSelection}
          virtual={true}
          columns={columns}
          scroll={{ y: 500 }}
          dataSource={filteredItems}
          size="small"
          pagination={false}
          style={{ pointerEvents: listDisabled ? 'none' : undefined, width: 500 }}
          onRow={({ key, disabled: itemDisabled }) => ({
            onClick: () => {
              if (itemDisabled || listDisabled) return;
              onItemSelect(key as string, !listSelectedKeys.includes(key as string));
            },
          })}
        />
      );
    }}
  </Transfer>
);

const mockTags = ['cat', 'dog', 'bird'];

const mockData: RecordType[] = Array.from({ length: 20 }).map((_, i) => ({
  key: i.toString(),
  title: `监控1`,
  description: `DEVICE1002`,
  tag: '走廊123',
  age: 'rtsp://129.12.12.12:90001',
}));

const originTargetKeys = mockData
  .filter((item) => Number(item.key) % 3 > 1)
  .map((item) => item.key);

const leftTableColumns: ColumnsType<DataType> = [
  {
    dataIndex: 'name',
    title: '名称',
  },
  {
    dataIndex: 'code',
    title: '编码',
  },
  {
    dataIndex: 'position',
    title: '位置',
  },
  {
    dataIndex: 'param',
    title: '参数',
  },
];

const rightTableColumns: ColumnsType<DataType> = [
  {
    dataIndex: 'name',
    title: '名称',
  },
  {
    dataIndex: 'code',
    title: '编码',
  },
  {
    dataIndex: 'position',
    title: '位置',
  },
  {
    dataIndex: 'param',
    title: '参数',
  },
];

export type UpdateFormProps = {
  targetKeys: string[];
  setTargetKeys: (data: string[]) => void;
  dataSource: DataType[];
};

const TableTransferList: React.FC<UpdateFormProps> = (props) => {
  const [showSearch, setShowSearch] = useState(false);

  const onChange = (nextTargetKeys: string[]) => {
    props.setTargetKeys(nextTargetKeys);
  };
  const triggerShowSearch = (checked: boolean) => {
    setShowSearch(checked);
  };
  return (
    <>
      <TableTransfer
        dataSource={props.dataSource}
        targetKeys={props.targetKeys}
        showSearch={showSearch}
        onChange={onChange}
        leftColumns={leftTableColumns}
        rightColumns={rightTableColumns}
      />
    </>
  );
};

export default TableTransferList;
