import React, { useState, useEffect } from 'react';
import { Button, Upload, Drawer, Table, Pagination, Form, Tooltip, Typography } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { Resizable } from 'react-resizable';

import { dispatch, dispatchLatest } from '../../../../model';
import { showMessage, formatDate } from '../../../../util';

const { Text } = Typography;

const ResizeableHeaderCell = props => {
  const { onResize, width, onClick, ...restProps } = props;

  if (!width) {
    return <th {...restProps} />;
  }

  return (
    <Resizable
      width={width}
      height={0}
      handle={
        <span
          className="react-resizable-handle"
          onClick={(e) => {
            e.stopPropagation();
          }}
        />
      }
      onResize={onResize}
      draggableOpts={{ enableUserSelectHack: false }}
    >
      <th
        onClick={onClick}
        {...restProps}
      />
    </Resizable>
  );
};

const ImportStockWordModal = (props) => {
  const { onCancel, onSuccess, visible, catalogId } = props;
  const [ fileList, setFileList ] = useState([]);
  const [ confirmLoading, setConfirmLoading ] = useState(false);

  const [ loading, setLoading ] = useState(false);
  const [ logs, setLogs ] = useState([]);
  const [ pagination, setPagination ] = useState( { pageNum: 1, pageSize: 20 } );
  const { pageNum, pageSize } = pagination;
  const [ total, setTotal ] = useState(0);

  const cols = [
    {
      title: '序号',
      dataIndex: 'key',
      render: (text, record, index) => {
        return (index+1).toString();
      },
      width: 60,
    },
    {
      title: '导入文件名',
      dataIndex: 'fileName',
      width: 200,
      ellipsis: true,
      render: (text, _, __) => {
        return <Tooltip title={text||''}>
          <Text ellipsis={true}>{text||''}</Text>
        </Tooltip>
      }
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      width: 170,
      ellipsis: true,
      render: (_, record, __) => {
        return formatDate(record.startTime);
      }
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      width: 170,
      ellipsis: true,
      render: (_, record, __) => {
        return formatDate(record.endTime);
      }
    },
    {
      title: '耗时',
      dataIndex: 'costTime',
      width: 100,
      ellipsis: true,
      render: (_, record, __) => {
        return record.costTime?`${Number(record.costTime/1000)}秒`:'';
      }
    },
    {
      title: '导入人',
      dataIndex: 'operator',
      width: 100,
      ellipsis: true,
    },
    {
      title: '导入状态',
      dataIndex: 'state',
      ellipsis: true,
    }
  ]

  const [ columns, setColumns ] = useState(cols);

  useEffect(() => {

    if (visible) {
      setPagination({ pageNum: 1, pageSize: 20 });
      getLogs();
    }

    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visible])

  const getLogs = (p = 1, s = 20) => {
    setLoading(true);
    dispatch({
      type: 'datamodel.importWordLogs',
      payload: {
        params: {
          page: p,
          pageSize: s
        }
      },
      callback: data => {
        setLoading(false);
        setTotal(data.totalElements);
        setLogs(data.content||[]);
      },
      error: () => {
        setLoading(false);
      }
    })
  }

  const onRefreshClick = () => {
    getLogs();
  }

  const uploadProps = {
    onRemove: file => {

      const index = fileList.indexOf(file);
      const newFileList = fileList.slice();
      newFileList.splice(index, 1);

      setFileList(newFileList);
    },
    beforeUpload: file => {

      setFileList([file]);
      return false;
    },
    fileList: fileList || [],
    accept: ".doc,.docx",
  };

  const handleOk = () => {

    if ((fileList || []).length === 0) {
      showMessage('info', '请先选择Word文件上传');
      return;
    }

    setConfirmLoading(true);
    dispatchLatest({
      type: 'datamodel.importWordGenerateModel',
      payload: {
        params: {
          catalogId,
          stateId: ''
        },
        fileList
      },
      callback: data => {
        setConfirmLoading(false);
        setFileList([]);
        getLogs(pageNum, pageSize);   
        onSuccess && onSuccess();     
      },
      error: () => {
        setConfirmLoading(false);
      }
    })
  }

  const reset = () => {
    setConfirmLoading(false);
    setFileList([]);
  }

  const handleResize = index => (e, { size }) => {
    const nextColumns = [...columns];
    nextColumns[index] = {
      ...nextColumns[index],
      width: size.width,
    };

    setColumns(nextColumns);
  };

  const mergedColumns = () => {
    return (
      columns.map((column, index) => { 
        return {
          ...column,
          onHeaderCell: column => ({
            width: column.width,
            onResize: handleResize(index),
          }),
        };
      })
    );
  }

  return (
    <Drawer 
      forceRender
      visible={ visible }
      title='存量模型导入'
      width={1000}
      placement="right"
      closable={ true }
      onClose={() => {
        reset();
        onCancel && onCancel();
      }}
    >
      <div className='mt-3'>
        <Form layout='inline'>
          <Form.Item label='Word上传:'>
            <Upload style={{ display: 'inline' }} {...uploadProps }>
              <Button icon={
                <UploadOutlined />}>
                选择文件上传
              </Button>
            </Upload>
          </Form.Item>
          <Form.Item>
            <Button type='primary' onClick={handleOk} loading={confirmLoading}>确定导入</Button>
          </Form.Item>
        </Form>
      </div>
      <div className='d-flex my-3' style={{ justifyContent: 'space-between', alignItems: 'center' }}>
        <h3 style={{ marginBottom: 0 }}>导入日志</h3> 
        <Button onClick={onRefreshClick}>刷新</Button>
      </div>
      <Table
        className='mt-3'
        components={{
          header: {
            cell: ResizeableHeaderCell,
          }
        }}
        columns={mergedColumns()} 
        rowKey={'id'}
        dataSource={logs||[]}
        pagination={false} 
        loading={loading}
        expandable={{
          expandedRowRender: record => <p style={{ margin: 0 }}>{record.message||''}</p>
        }}
        sticky
      />
      <Pagination
        className="text-center mt-3"
        showSizeChanger
        showQuickJumper
        onChange={(_pageNum, _pageSize) => {
          setPagination({ pageNum: _pageNum||1, pageSize: _pageSize || 20 });
          getLogs(_pageNum||1, _pageSize||20);
        }}
        onShowSizeChange={(_pageNum, _pageSize) => {
          setPagination({ pageNum: _pageNum || 1, pageSize: _pageSize || 20 });
          getLogs(_pageNum||1, _pageSize||20);
        }}
        current={pageNum}
        pageSize={pageSize}
        defaultCurrent={1}
        total={total}
        pageSizeOptions={[10,20]}
        showTotal={total => `共 ${total} 条`}
      />
    </Drawer>
  )
}

export default ImportStockWordModal;