import { useEffect, useMemo, useState } 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 { UpdateTemplateModal } from './UpdateTemplateModal';
import { inputWidth, showMessage } from '../../../../../util';

import './DefineTable.less';
import 'react-contexify/dist/ReactContexify.css';
import { dispatch } from '../../../../../model';

const InputDebounce = DebounceInput(300)(Input);

const DefineTable = (props) => {
  const {nodeId} = props;
  const [keyword, setKeyword] = useState('');
  const [checkedKeys, setCheckedKeys] = useState([]);
  const [isTemplateModalVisible, setIsTemplateModalVisible] = useState(false);
  const [currentTemplate, setCurrentTemplate] = useState({});
  const [action, setAction] = useState('');
  const [loading, setLoading] = useState(false);
  const [deleteLoading, setDeleteLoading] = useState(false);
  const [tableData, setTableData] = useState([]);
  const [total, setTotal] = useState(0);
  const [pagination, setPagination] = useState({pageNum: 1, pageSize: 20});

  const {pageNum, pageSize} = pagination;

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

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

  const columns = useMemo(() => {
    return ([
      {
        title: '序号',
        dataIndex: 'key',
        render: (text, record, index) => {
          return (index+1).toString();
        },
        width: 60,
        ellipsis: true,
      },
      {
        title: '模版名称',
        dataIndex: 'name',
        width: 200,
        ellipsis: true,
        render: (text, record, index) => {
          return <a onClick={() => {onItemClick(record);}}>{text}</a>
        },
      },
      {
        title: '模版中文名称',
        dataIndex: 'cnName',
        width: 200,
        ellipsis: true,
      },
      {
        title: '修改时间',
        dataIndex: 'lastUpdateTime',
        width: 200,
        ellipsis: true,
      },
      {
        title: '模版描述',
        dataIndex: 'comment',
        width: 200,
        ellipsis: true,
      }
    ]);
  }, []);

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

  const getTemplates = () => {
    setLoading(true);
    dispatch({
      type: 'msd.getModels',
      payload: {
        params: {
          nodeId,
          keyword,
          pageNum,
          pageSize
        }
      },
      callback: (data) => {
        setLoading(false);
        setTableData(data?.content||[]);
        setTotal(data?.totalElements||0);
      }, 
      error: () => {
        setLoading(false);
      }
    });
  }

  const onAddClick = () => {
    setAction('add');
    setCurrentTemplate(null);
    setIsTemplateModalVisible(true);
  }

  const onItemClick = (record) => {
    setAction('detail');
    setCurrentTemplate(record);
    setIsTemplateModalVisible(true);
  }

  const onTemplateModalCancel = (refresh = false) => {
    setIsTemplateModalVisible(false);
    if (refresh) {
      getTemplates();
    }
  }

  const onBatchDeleteClick = () => {
    setDeleteLoading(true);
    dispatch({
      type: 'msd.deleteModels',
      payload: {
        params: {
          modelIds: (checkedKeys||[]).join(',')
        }
      },
      callback: (data) => {
        setDeleteLoading(false);
        showMessage('success', '删除成功');
        getTemplates();
      }, 
      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 === 'update') {
      setAction('update');
      setIsTemplateModalVisible(true);
    }
  }

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

  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>
            <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 
          loading={loading}
          rowKey='_id'
          rowSelection={rowSelection}
          columns={columns}
          dataSource={tableData}
          onRow={(record) => {
            return {
              onContextMenu: event => {
                setCurrentTemplate(record);
                show(event);
              },
            };
          }}
          pagination={false}
          scroll={{ y: 'calc(100vh - 94px - 32px - 57px - 24px - 39px - 36px)' }}
        />
        <Pagination
          size="small"
          className="text-center mt-3"
          showSizeChanger
          showQuickJumper
          onChange={changeCurrent}
          onShowSizeChange={changeCurrent}
          current={pageNum}
          pageSize={pageSize}
          defaultCurrent={1}
          total={total}
          showTotal={total => `共 ${total} 条`}
        />
      </div>

      <UpdateTemplateModal
        action={action}
        nodeId={nodeId}
        template={currentTemplate}
        visible={isTemplateModalVisible}
        onCancel={onTemplateModalCancel}
      />

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

export default DefineTable;