import { useMemo, useState, useEffect } from 'react';
import { Space, Button, Input, Pagination, Tooltip } from 'antd';
import { useContextMenu, Menu as RcMenu, Item as RcItem } from "react-contexify";

import ResizeableTable from '../../../ResizeableTable';
import DebounceInput from '../../../Model/Component/DebounceInput';
import UpdateDataMasterModal from './UpdateDataMasterModal';
import ImportDataDrawer from './ImportDataDrawer';
import { inputWidth, showMessage } from '../../../../../util';
import { dispatch } from '../../../../../model';

import '../../Define/Component/DefineTable.less';
import 'react-contexify/dist/ReactContexify.css';

const InputDebounce = DebounceInput(300)(Input);

const ManageTable = (props) => {
  const {nodeId} = props;
  const [keyword, setKeyword] = useState('');
  const [checkedKeys, setCheckedKeys] = useState([]);
  const [isDataMasterModalVisible, setIsDataMasterModalVisible] = useState(false);
  const [currentData, setCurrentData] = useState(null);
  const [action, setAction] = useState('');
  const [loading, setLoading] = useState(false);
  const [deleteLoading, setDeleteLoading] = useState(false);
  const [fields, setFields] = useState([]);
  const [tableData, setTableData] = useState([]);
  const [total, setTotal] = useState(0);
  const [pagination, setPagination] = useState({pageNum: 1, pageSize: 20});
  const [importDataDrawerVisible, setImportDataDrawerVisible] = useState(false);

  const {pageNum, pageSize} = pagination;

  const columns = useMemo(() => {
    const newColumns = [
      {
        title: '序号',
        dataIndex: 'key',
        render: (text, record, index) => {
          return (index+1).toString();
        },
        width: 60,
        ellipsis: true,
      }
    ];
    (fields||[]).forEach(item => {
      newColumns.push({
        title: item.name,
        dataIndex: item.name,
        width: 200,
        ellipsis: true,
      });
    })

    return newColumns;
  }, [fields]);

  const MENU_ID = 'data-master-manage-table-contextmenu';
  const { show } = useContextMenu({
    id: MENU_ID,
  });

  useEffect(() => {
    setCheckedKeys([]);
    setPagination({...pagination, pageNum: 1});
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [nodeId])

  useEffect(() => {
    if (!nodeId || nodeId==='') {
      setFields([]);
      setTableData([]);
      setTotal(0);
    } else {
      getFiledsAndDatas();
    }
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [keyword, pagination])

  const getFiledsAndDatas = () => {
    setLoading(true);
    dispatch({
      type: 'msd.getColumns',
      payload: {
        params: {
          modelId: nodeId
        }
      },
      callback: (data) => {
        setFields(data||[]);

        const newKeyList = [];
        (data||[]).forEach(item => {
          newKeyList.push(item.name||'');
        });

        dispatch({
          type: 'msd.getDatas',
          payload: {
            params: {
              modelId: nodeId,
              keyList: newKeyList.join(','),
              keyword,
              pageNum,
              pageSize
            }
          },
          callback: (data) => {
            setLoading(false);
            setTableData(data?.content||[]);
            setTotal(data?.totalElements||0);
          }, 
          error: () => {
            setLoading(false);
          }
        });
      }, 
      error: () => {
        setLoading(false);
      }
    });
  }

  const onAddClick = () => {
    setAction('add');
    setCurrentData(null);
    setIsDataMasterModalVisible(true);
  }

  const onImportClick = () => {
    setImportDataDrawerVisible(true);
  }

  const onDataMasterModalCancel = (refresh = false) => {
    setIsDataMasterModalVisible(false);

    if (refresh) {
      getFiledsAndDatas();
    }
  }

  const onBatchDeleteClick = () => {
    setDeleteLoading(true);
    dispatch({
      type: 'msd.deleteDatas',
      payload: {
        data: checkedKeys||[]
      },
      callback: (data) => {
        setDeleteLoading(false);
        showMessage('success', '删除成功');
        getFiledsAndDatas();
      }, 
      error: () => {
        setDeleteLoading(false);
      }
    });
  }

  const onSearchInputChange = (value) => {
    setKeyword(value);
  }

  const onTableSelectChange = keys => {
    setCheckedKeys(keys);
  };

  const handleItemClick = ({ event, props, data, triggerEvent }) => {
    const key = event.currentTarget.id;

    if (key === 'detail') {
      setAction('detail');
      setIsDataMasterModalVisible(true);
    } if (key === 'update') {
      setAction('update');
      setIsDataMasterModalVisible(true);
    }
  }

  const changeCurrent = (page,size) => {
    setCheckedKeys([]);
    setPagination({ pageNum: page, pageSize: size });
  }

  const onImportDataDrawerCancel = () => {
    setImportDataDrawerVisible(false);
  }

  const onImportDataSuccess = () => {
    getFiledsAndDatas();
  }

  const rowSelection = {
    selectedRowKeys: checkedKeys,
    onChange: onTableSelectChange,
  };

  return (
    <div className='data-master-table'>
      <div className='data-master-header px-3'>
        <Space>
          <Space>
            <Button onClick={onAddClick}>新建</Button>
          </Space>
          <Space>
            <Button onClick={onImportClick}>导入</Button>
          </Space>
          <Space>
            <Tooltip title={(checkedKeys||[]).length===0?'请先选择主数据':''}>
              <Button onClick={onBatchDeleteClick} disabled={(checkedKeys||[]).length===0} loading={deleteLoading}>删除</Button>
            </Tooltip>
          </Space>
        </Space>
        <InputDebounce 
          placeholder="请输入关键字" 
          allowClear 
          value={keyword}
          onChange={onSearchInputChange} 
          style={{ width: inputWidth, marginLeft: 'auto' }}
        />
      </div>
      <div className='data-master-content p-3'>
        <ResizeableTable 
          rowKey='_id'
          loading={loading}
          rowSelection={rowSelection}
          columns={columns}
          dataSource={tableData}
          onRow={(record) => {
            return {
              onContextMenu: event => {
                setCurrentData(record);
                show(event);
              },
            };
          }}
          pagination={false}
          scroll={{ y: 'calc(100vh - 94px - 32px - 57px - 24px - 39px - 36px)' }}        
        />
        <Pagination
          size="small"
          className="text-center m-3"
          showSizeChanger
          showQuickJumper
          onChange={changeCurrent}
          onShowSizeChange={changeCurrent}
          current={pageNum}
          pageSize={pageSize}
          defaultCurrent={1}
          total={total}
          showTotal={total => `共 ${total} 条`}
        />
      </div>

      <UpdateDataMasterModal
        action={action}
        data={currentData}
        fields={fields}
        nodeId={nodeId}
        visible={isDataMasterModalVisible}
        onCancel={onDataMasterModalCancel}
      />

      <ImportDataDrawer 
        visible={importDataDrawerVisible}
        nodeId={nodeId}
        onCancel={onImportDataDrawerCancel}
        onSuccess={onImportDataSuccess}
      />  

      <RcMenu id={MENU_ID}>
        <RcItem id="detail" onClick={handleItemClick}>
          详情
        </RcItem>
        <RcItem id="update" onClick={handleItemClick}>
          编辑
        </RcItem>
      </RcMenu>
    </div>
  );
}

export default ManageTable;