import React, { Key, useEffect, useState } from 'react';
import { Input, Select } from 'antd';
import { KCIMTable } from '@/components/KCIMTable';
import { createFromIconfontCN } from '@ant-design/icons';

import {
  ModalForm,
  ProColumns,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-components';

import { set } from 'lodash';
import { getAddableTableData } from '../service';

// import './style.less';

interface TableSelecterProps {
  record: any;
}

const IconFont = createFromIconfontCN({
  scriptUrl: '',
});

const TableSelecter = ({
  record,
  open,
  title,
  onVisibleChange,
  rowKey = 'id',
  request,
  onFinish,
  defaultSelectedKeys,
}: {
  record: any;
  open: boolean;
  title: string;
  onVisibleChange: (bool: boolean) => void;
  defaultSelectedKeys: Key[];
  rowKey?: string;
  request?: (params: any) => Promise<any>;
  onFinish?: (selectedKeys: React.Key[], selectedRows: any[]) => void;
}) => {
  const Table = React.forwardRef(({}: TableSelecterProps, ref) => {
    const [datasource, set_datasource] = useState<any[]>([]);
    const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
    const [selectedRows, set_selectedRows] = useState<any[]>([]);
    const [showList, set_showList] = useState<any[]>([]);
    const [type, set_type] = useState<number>(1);
    const [keyword, set_keyword] = useState<string | undefined>(undefined);

    const columns: ProColumns[] = [
      {
        title: '项目代码',
        ellipsis: true,
        width: 85,
        dataIndex: 'code',
      },
      {
        title: '项目名称',
        ellipsis: true,
        dataIndex: 'name',
      },
    ];

    const onSelectChange = (
      newSelectedRowKeys: React.Key[],
      selectedRows: any,
    ) => {
      setSelectedKeys([...newSelectedRowKeys]);
      set_selectedRows([...selectedRows]);
    };

    const saveHandle = async () => {
      const selectedRowCodes = selectedRows.map((a) => a[`${rowKey}`]);
      const rows = datasource.filter((a) =>
        selectedRowCodes.includes(a[`${rowKey}`]),
      );
      console.log({ selectedKeys, rows });
      onFinish && onFinish(selectedKeys, rows);
    };

    const getTableData = async () => {
      const resp = await getAddableTableData(type, record.code);
      if (resp) {
        const data = resp.filter((a: any) => {
          if (!defaultSelectedKeys.includes(a[`${rowKey}`])) {
            return {
              ...a,
            };
          }
        });

        set_showList(data);
        set_datasource([...data]);
      }

      return Promise.resolve([]);
    };

    useEffect(() => {
      // console.log({code, keyword});
      const result = datasource.filter((a) => {
        return a.name.indexOf(keyword) != -1;
      });

      set_showList([...result]);
    }, [keyword]);

    useEffect(() => {
      getTableData();
    }, [type]);

    return (
      <div>
        <div
          className="filter"
          style={{
            marginBottom: 8,
            display: 'flex',
            flexDirection: 'row',
            alignItems: 'center',
          }}
        >
          <ProFormSelect
            noStyle
            style={{ marginRight: 8 }}
            options={[
              { label: '药品', value: 1 },
              { label: '材料', value: 2 },
              // {label:'项目',value:3}
            ]}
            fieldProps={{
              defaultValue: 1,
              onChange(value, option) {
                set_type(value);
                set_keyword('');
                setSelectedKeys([]);
                set_selectedRows([]);
              },
            }}
          />
          <ProFormText
            noStyle
            placeholder={'项目名称'}
            fieldProps={{
              value: keyword,
              suffix: (
                <IconFont style={{ color: '#99A6BF' }} type="iconsousuo" />
              ),
              onChange: (e) => {
                if (e.target.value.length != 0) {
                  set_keyword(e.target.value);
                } else {
                  set_keyword('');
                }
              },
            }}
          />
        </div>

        <KCIMTable
          columns={columns}
          options={{
            density: true,
            setting: {
              listsHeight: 100,
            },
          }}
          rowKey={rowKey}
          scroll={{ y: 400 }}
          tableAlertRender={false}
          rowSelection={{
            // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
            // 注释该行则默认不显示下拉选项
            // selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
            selectedRowKeys: selectedKeys,
            onChange: onSelectChange,
          }}
          pagination={{ showTitle: false, showSizeChanger: true, simple: true }}
          dataSource={showList}
        />
        <div className="footer">
          <span className="cancel" onClick={() => close()}>
            取消
          </span>
          <span className="ok" onClick={() => saveHandle()}>{`确认(${
            selectedKeys.length > 0 && selectedKeys.length
          })`}</span>
        </div>
      </div>
    );
  });

  const close = () => {
    onVisibleChange && onVisibleChange(false);
  };

  return (
    <ModalForm
      className="TableSelecter"
      title={title}
      width={400}
      submitter={{
        render: false,
      }}
      open={open}
      modalProps={{
        closable: false,
      }}
    >
      <Table
        // ref={tableSelecterRef}
        record={undefined}
      ></Table>
    </ModalForm>
  );
};

export default TableSelecter;
