import React, { useState, useEffect } from 'react';
import { Button, Upload, Drawer, Pagination, Form, Spin } from 'antd';
import { UploadOutlined, DownloadOutlined } from '@ant-design/icons';

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

const ExpandedRow = (props) => {
  const {data} = props;

  const [loading, setLoading] = useState(false);
  const [log, setLog] = useState({});

  useEffect(() => {
    getLog();
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [data])

  const getLog = () => {
    setLoading(true);
    dispatch({
      type: 'msd.importLog',
      payload: {
        logId: data?.id
      },
      callback: data => {
        setLoading(false);
        setLog(data||{});
      },
      error: () => {
        setLoading(false);
      }
    })
  }

  return <Spin spinning={loading}>
    <p style={{ margin: 0 }}>{log?.message||''}</p>
  </Spin>
}

const ImportDataDrawer = (props) => {
  const { onCancel, onSuccess, visible, nodeId } = 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 columns = [
    {
      title: '序号',
      dataIndex: 'key',
      render: (text, record, index) => {
        return (index+1).toString();
      },
      width: 60,
      ellipsis: true,
    },
    {
      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,
      render: (text, record, __) => {
        return text.split(':')[0]; 
      }
    },
    {
      title: '导入状态',
      dataIndex: 'state',
      width: 100,
      ellipsis: true,
    }
  ]

  useEffect(() => {
    if (visible) {
      setPagination({ pageNum: 1, pageSize: 20 });
    }
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visible])

  useEffect(() => {
    if (visible) {
      getLogs();
    }
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pagination])

  const getLogs = () => {
    setLoading(true);
    dispatch({
      type: 'msd.importLogs',
      payload: {
        modelId: nodeId,
        page: pageNum,
        size: pageSize
      },
      callback: data => {
        setLoading(false);
        setTotal(data.totalElements);
        setLogs(data.content||[]);
      },
      error: () => {
        setLoading(false);
      }
    })
  }

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

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

  const downloadTemplate = () => {
    window.open(`/api/metadatarepo/rest/msdMgr/exportTemplate?modelId=${nodeId}`);
  }

  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: ".xlsx",
  };

  const handleOk = () => {

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

    setConfirmLoading(true);
    dispatchLatest({
      type: 'msd.importData',
      payload: {
        params: {
          modelId: nodeId,
        },
        fileList
      },
      callback: data => {
        setConfirmLoading(false);
        setFileList([]);
        getLogs();   
        onSuccess && onSuccess();     
      },
      error: () => {
        setConfirmLoading(false);
      }
    })
  }

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

  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='Excel上传:'>
            <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.Item>
            <Button icon={<DownloadOutlined />} onClick={downloadTemplate }>
            模版下载
            </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>
      <ResizeableTable
        className='mt-3'
        columns={columns} 
        rowKey={'id'}
        dataSource={logs||[]}
        pagination={false} 
        loading={loading}
        expandable={{
          expandedRowRender: record => <ExpandedRow data={record} />
        }}
        sticky
      />
      <Pagination
        className="text-center mt-3"
        showSizeChanger
        showQuickJumper
        onChange={changeCurrent}
        onShowSizeChange={changeCurrent}
        current={pageNum}
        pageSize={pageSize}
        defaultCurrent={1}
        total={total}
        pageSizeOptions={[10,20]}
        showTotal={total => `共 ${total} 条`}
      />
    </Drawer>
  )
}

export default ImportDataDrawer;