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

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

const ImportAssetDrawer = (props) => {
  const { onCancel, onSuccess, visible, nodeId, template } = 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 [ users, setUsers ] = useState([]);

  const app = useContext(AppContext);

  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      render: (text, record, index) => {
        return (index+1).toString();
      },
      width: 60,
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      width: 200,
      ellipsis: true,
      render: (_, record, __) => {
        return formatDate(record.startTime);
      }
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      width: 200,
      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) => {
        const user = users?.filter((user)=>user.pernr===text);
        if (user && user.length > 0) {
          return user[0].nachn?`${user[0].nachn}(${user[0].pernr})`:user[0].pernr;
        }

        return text;
      }
    },
    {
      title: '导入状态',
      dataIndex: 'state',
      ellipsis: true,
    }
  ]

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

  const downloadTemplate = () => {
    window.open(`/api/dataassetmanager/dataAssetColumnApi/getBusinessColumnImportTemplate?templateType=${template?.type??''}`);
  }

  const getLogs = (p = 1, s = 20) => {
    setLoading(true);
    dispatch({
      type: 'assetmanage.importBusinessColumnLogs',
      payload: {
        page: p,
        pageSize: s,
        templateType: template?.type
      },
      callback: data => {
        setLoading(false);
        setTotal(data.total);
        setLogs(data.data||[]);
      },
      error: () => {
        setLoading(false);
      }
    })
  }

  const getUsers = () => {
    dispatch({
      type: 'pds.getOwners',
      callback: (data) => {
        setUsers(data);
      }
    })
  }

  const uploadProps = {
    onRemove: file => {

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

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

      const isLt2OM = file.size / 1024 / 1024 < 20;
      if (!isLt2OM) {
        showMessage('error', '上传文件必须小于20M');
        setFileList([]);
        return false;
      }

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

  const handleOk = () => {

    if ((fileList||[]).length === 0) {
      showMessage('info', '请先选择文件上传');
      return;
    }
    
    setConfirmLoading(true);
    dispatch({
      type: 'assetmanage.checkIsNeedSaveAsDraft',
      callback: (data) => {
        const needSaveAsDraft = (data==='true')?true:false

        dispatch({
          type: 'assetmanage.assetImportBusinessColumn',
          payload: { fileList: fileList, params: { env: `${app?.env?.domainId}`, saveAsDraft: needSaveAsDraft } },
          callback: data => {
            setConfirmLoading(false);
            setFileList([]);
            getLogs(pageNum, pageSize); 
            showMessage('success', '导入动作完成，详情查看日志');
            onSuccess && onSuccess(data||''); 
          },
          error: () => {
            setConfirmLoading(false);
          }
        }); 
      },
      error: () => {
        setConfirmLoading(false);
      }
    })
  }

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

  return (
    <Drawer 
      forceRender
      visible={ visible }
      title='字段导入'
      width={900}
      placement="right"
      closable={ true }
      onClose={() => {
        reset();
        onCancel && onCancel();
      }}
    >
      <div className='mt-3'>
        <Form layout='inline'>
          <Form.Item label='Excel导入:'>
            <Button className='mr-2' icon={<DownloadOutlined />} onClick={ downloadTemplate }>
            模板下载
            </Button>
            <Upload style={{ display: 'inline' }} {...uploadProps }>
              <Button icon={
                <UploadOutlined />}>
                选择文件上传
              </Button>
            </Upload>
          </Form.Item>
          <Form.Item>
            <Button type='primary' onClick={handleOk} loading={confirmLoading}>确定导入</Button>
          </Form.Item>
          <Button  onClick={() => getLogs()} style={{ marginLeft: 'auto' }}>刷新日志</Button>
        </Form>
      </div>
      <Divider orientation="left">导入日志</Divider>
      <Table
        className='mt-3'
        columns={columns||[]} 
        rowKey={'id'}
        dataSource={logs||[]}
        pagination={false} 
        loading={loading}
        expandable={{
          expandedRowRender: record => <React.Fragment>
          {record.message?.split('<br/>').map((info, index) => {
            return <Typography.Paragraph key={index}>{info}</Typography.Paragraph>
          })}
          </React.Fragment>
        }}
        sticky
      />
      <Pagination
        className="text-center mt-3"
        showSizeChanger
        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}
        showTotal={total => `共 ${total} 条`}
      />
    </Drawer>
  )
}

export default ImportAssetDrawer;