import React, { useEffect, useState } from 'react';
import { Input, Switch } from 'antd';
import { KCIMTable } from '@/components/KCIMTable';
import { createFromIconfontCN } from '@ant-design/icons';
import { getChackGroupData, getCheckData } from '../checkGroupMana/service';

import { ModalForm, ProColumns } from '@ant-design/pro-components';
import { getData } from '../unitMana/service';
import { set } from 'lodash';

// import './style.less';

interface TableSelecterProps {
  record: any;
}

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

const TableSelecter = ({
  tableSelecterType,
  record,
  open,
  title,
  onVisibleChange,
  rowKey = 'id',
  request,
  onFinish,
}: {
  record: any;
  open: boolean;
  title: string;
  onVisibleChange: (bool: boolean) => void;
  tableSelecterType: 'UNIT' | 'CHECKGROUP';
  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 unitColumns: ProColumns[] = [
      {
        title: 'Code',
        dataIndex: 'code',
      },
      {
        title: '单位名',
        dataIndex: 'name',
      },
      {
        title: '是否单位管理人',
        dataIndex: 'flag',
        renderText(flag, record, index, action) {
          return (
            <Switch
              size="small"
              checked={flag}
              onChange={(bool) => onSwitchChange(bool, record)}
            />
          );
        },
      },
    ];
    const checkGroupColumns: ProColumns[] = [
      {
        title: 'ID',
        dataIndex: 'id',
      },
      {
        title: '查核组名',
        dataIndex: 'name',
      },
      {
        title: '是否查核组长',
        dataIndex: 'flag',
        renderText(flag, record, index, action) {
          return (
            <Switch
              size="small"
              checked={flag}
              onChange={(bool) => onSwitchChange(bool, record)}
            />
          );
        },
      },
    ];

    const onSwitchChange = (bool: boolean, record: any) => {
      const newData = datasource.map((item) => {
        if (item.code == record.code) {
          return {
            ...item,
            flag: bool,
          };
        } else {
          return item;
        }
      });
      const newShowList = showList.map((item) => {
        if (item.code == record.code) {
          return {
            ...item,
            flag: bool,
          };
        } else {
          return item;
        }
      });

      set_datasource([...newData]);
      set_showList([...newShowList]);
    };

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

    const saveHandle = async () => {
      const selectedRowCodes = selectedRows.map((a) => a.code);
      const rows = datasource.filter((a) => selectedRowCodes.includes(a.code));
      onFinish && onFinish(selectedKeys, rows);
    };

    const getTableData = async () => {
      if (tableSelecterType == 'UNIT') {
        const resp = await getData();
        const checkedUnitCodes = record.departList
          ? record.departList.map((a: any) => a.code)
          : [];
        let selectedCodes: string[] = [];
        let selectedRows: any[] = [];
        if (resp) {
          const data = resp.map((a: any) => {
            if (checkedUnitCodes.includes(a.code)) {
              selectedCodes.push(a.code);
              selectedRows.push(a);
              const needItem = record.departList.filter(
                (b: any) => a.code == b.code,
              );

              return {
                ...a,
                flag: needItem[0].isManager ? true : false,
              };
            } else {
              return a;
            }
          });

          set_showList(data);
          set_selectedRows([...selectedRows]);
          setSelectedKeys([...selectedCodes]);
          set_datasource([...datasource, ...data]);
        }
      }
      if (tableSelecterType == 'CHECKGROUP') {
        const resp = await getCheckData({ pageSize: 500, current: 1 });
        const checkedUnitCodes = record.groupList
          ? record.groupList.map((a: any) => a.code)
          : [];
        let selectedCodes: string[] = [];
        let selectedRows: any[] = [];
        if (resp) {
          const data = resp.list.map((a: any) => {
            if (checkedUnitCodes.includes(a.code)) {
              selectedCodes.push(a.code);
              selectedRows.push(a);
              const needItem = record.groupList.filter(
                (b: any) => a.code == b.code,
              );
              return {
                ...a,
                flag: needItem[0].isManager ? true : false,
              };
            } else {
              return a;
            }
          });
          set_showList(data);
          set_selectedRows([...selectedRows]);
          setSelectedKeys([...selectedCodes]);
          set_datasource([...datasource, ...data]);
        }
      }

      return Promise.resolve([]);
    };

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

    return (
      <div>
        <Input
          placeholder={
            tableSelecterType == 'UNIT' ? '请输入单位名称' : '请输入查核组名称'
          }
          allowClear
          suffix={<IconFont style={{ color: '#99A6BF' }} type="iconsousuo" />}
          style={{ marginBottom: 8 }}
          onChange={(e) => {
            if (e.target.value.length != 0) {
              const result = datasource.filter(
                (item) => item.name.indexOf(e.target.value) != -1,
              );
              set_showList(result);
            } else {
              set_showList(datasource);
            }
          }}
        />
        <KCIMTable
          columns={
            tableSelecterType == 'UNIT' ? unitColumns : checkGroupColumns
          }
          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 }}
          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={500}
      submitter={{
        render: false,
      }}
      open={open}
      modalProps={{
        closable: false,
      }}
    >
      <Table
        // ref={tableSelecterRef}
        record={undefined}
      ></Table>
    </ModalForm>
  );
};

export default TableSelecter;
