import React, { useState, useEffect } from 'react';
import { Modal, Radio, Transfer } from 'antd';
// import SelectDevice from '@/components/select-device';
import classNames from '@pansy/classnames';
import styles from './select-device-modal.less';
import { Table, Empty, MapDeviceSelection } from '@sensoro/sensoro-design';
import { difference } from 'lodash';
import { ModalProps } from 'antd/es/modal';
import { DeviceInfo } from '../../common/types/map-device';
import SensorIcon from '@sensoro/library/lib/components/sensor-icon';
import { iconMap } from '../select-device/config';

const TableTransfer = ({ getColumns, deviceKey, ...restProps }: any) => {
  return (
    <Transfer {...restProps} showSelectAll={false}>
      {({
        direction,
        filteredItems,
        onItemSelectAll,
        onItemSelect,
        selectedKeys: listSelectedKeys,
      }) => {
        const rowSelection = {
          onChange: () => {},
          onSelectAll(selected: boolean, selectedRows: any[]) {
            const treeSelectedKeys = selectedRows
              .filter(item => !item.disabled)
              .map(item => item?.[deviceKey]);
            const diffKeys = selected
              ? difference(treeSelectedKeys, listSelectedKeys)
              : difference(listSelectedKeys, treeSelectedKeys);
            onItemSelectAll(diffKeys, selected);
          },
          onSelect(item: any, selected: boolean) {
            onItemSelect(item?.[deviceKey], selected);
          },
          selectedRowKeys: listSelectedKeys,
        };

        return (
          <Table
            className={styles[direction]}
            rowSelection={rowSelection}
            columns={getColumns(direction)}
            dataSource={filteredItems}
            locale={{
              emptyText: (
                <Empty
                  icon="device"
                  description="暂无设备"
                  style={{ padding: 88 }}
                />
              ),
            }}
            size="small"
            pagination={{
              // size: 'small',
              pageSize: direction === 'left' ? 7 : 8,
              showQuickJumper: false,
              showSizeChanger: false,
            }}
          />
        );
      }}
    </Transfer>
  );
};

export interface Data {
  devices?: DeviceInfo[];
  relatedCameraIds?: string[];
}

export interface SelectDeviceModalProps extends ModalProps {
  data?: Data;
  onChange?: (value: string[]) => void;
  deviceKey?: string;
}

const SelectDeviceModal: React.FC<SelectDeviceModalProps> = props => {
  const {
    onChange,
    onCancel,
    data = {},
    visible,
    deviceKey = 'cid',
    ...rest
  } = props;
  const { devices, relatedCameraIds } = data;
  const [mode, setMode] = useState('map');
  const [targetIds, setTargetIds] = useState(relatedCameraIds);
  // @ts-ignore
  const handleModeChange = e => {
    const mode = e.target.value;
    setMode(mode);
  };

  useEffect(() => {
    setTargetIds(relatedCameraIds);
  }, [relatedCameraIds]);

  const getColumns = (position: string) => [
    {
      title: position === 'left' ? '摄像机列表' : '已选择摄像机',
      dataIndex: 'name',
      ellipsis: true,
      render: (text, row) => {
        return (
          <span
            className={classNames(styles.transferContainer, {
              [styles.offline]: row.status === 0,
            })}
          >
            <SensorIcon type={iconMap[row.deviceUsageType]} />
            <span>{row.name}</span>
          </span>
        );
      },
    },
  ];

  const handleChange = (nextTargetKeys: string[]) => {
    setTargetIds(nextTargetKeys);
  };

  const handleCancel = (e: any) => {
    setTargetIds(relatedCameraIds);
    onCancel?.(e);
  };

  return (
    <Modal
      title="选择设备"
      visible={visible}
      {...rest}
      width={960}
      onCancel={handleCancel}
      destroyOnClose
      onOk={e => {
        onChange?.(targetIds || []);
        onCancel?.(e);
      }}
    >
      <Radio.Group
        onChange={handleModeChange}
        value={mode}
        style={{ marginBottom: 24 }}
      >
        <Radio.Button value="list">列表模式</Radio.Button>
        <Radio.Button value="map">地图模式</Radio.Button>
      </Radio.Group>
      <div
        className={classNames(styles.transferContainer, {
          [styles.hide]: mode !== 'list',
        })}
      >
        {visible && (
          <TableTransfer
            deviceKey={deviceKey}
            dataSource={devices}
            targetKeys={targetIds}
            showSearch={true}
            onChange={handleChange}
            getColumns={getColumns}
            filterOption={(inputValue: string, item: any) =>
              item.name.indexOf(inputValue) !== -1
            }
            rowKey={(record: any) => record[deviceKey]}
          />
        )}
      </div>
      <div className={classNames({ [styles.hide]: mode === 'list' })}>
        <MapDeviceSelection
          deviceKey={deviceKey}
          style={{ height: 512, width: 912 }}
          list={devices}
          value={targetIds}
          onChange={handleChange}
        />
      </div>
    </Modal>
  );
};

export default SelectDeviceModal;
