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

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

const catalogs = [
  { title: '字段级资产目录', key: '1' },
  { title: '映射关系', key: '2' },
]

const FC = (props) => {
  const { onCancel, onSuccess, visible, metadataId, onChange } = props;

  const [loading, setLoading] = useState(false);
  const [catalogId, setCatalogId] = useState('1');
  const [logs, setLogs] = useState([]);
  const [pagination, setPagination] = useState({ pageNum: 1, pageSize: 20 });
  const { pageNum, pageSize } = pagination;
  const [total, setTotal] = useState(0);
  const [step, setStep] = useState(1);
  const [fileList, setFileList] = useState([]);
  const [detailParam, setDetailParam] = useState({visible: false, type: undefined, id: undefined, message: undefined});

  const app = useContext(AppContext);

  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      render: (text, record, index) => {
        return (index+1).toString();
      },
      width: 60,
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      ellipsis: true,
      render: (_, record, __) => {
        return formatDate(record.startTime);
      }
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      ellipsis: true,
      render: (_, record, __) => {
        return formatDate(record.endTime);
      }
    },
    {
      title: '耗时',
      dataIndex: 'costTime',
      ellipsis: true,
      render: (_, record, __) => {
        return record.costTime?`${Number(record.costTime/1000)}秒`:'';
      }
    },
    // {
    //   title: '导入人',
    //   dataIndex: 'operator',
    //   width: 100,
    //   ellipsis: true,
    // },
    {
      title: '导入状态',
      dataIndex: 'state',
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: 80,
      render: (_, record) => {
        return <a onClick={() => {
          if (catalogId === '1') {
            setDetailParam({...detailParam, visible: true, type: catalogId, id: record.id});
          } else {
            setDetailParam({...detailParam, visible: true, type: catalogId, message: record.message});
          }
        }}>详情</a>
      }
    }
  ]

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

  const getLogs = () => {
    setLoading(true);
    if (catalogId === '1') {
      dispatch({
        type: 'assetmanage.getMetadataImportAssetLog',
        payload: {
          catalog: app?.env?.domainId,
          page: pageNum,
          size: pageSize,
        },
        callback: data => {
          setLoading(false);
          setTotal(data.totalElements);
          setLogs(data.content||[]);
        },
        error: () => {
          setLoading(false);
        }
      });
    } else {
      dispatch({
        type: 'assetmanage.importIndicatorLog',
        payload: {
          page: pageNum,
          size: pageSize,
          updater: app?.user?.userName,
        },
        callback: data => {
          setLoading(false);
          setTotal(data.totalElements);

          data.content?.forEach((item, index) => {
            item.id = index;
            item.startTime = item.updateTime;
            item.costTime = item.cost;
          });
          setLogs(data.content||[]);
        },
        error: () => {
          setLoading(false);
        }
      });
    }
  }

  const reset = () => {
    setFileList([]);
    setStep(1);
    setCatalogId('1');
  }

  const downloadTemplate = () => {
    if (catalogId === '2') {
      window.open("/api/standard/indicator/exportModel");
    }
  }

  const onImportClick = () => {
    if (fileList.length === 0) {
      showMessage('warn', '请先上传文件');
      return;
    }

    if (catalogId === '1') {
      dispatch({
        type: 'assetmanage.importMetadataAttributes',
        payload: { 
          fileList: [fileList[0]],
          params: {
            catalog: app?.env?.domainId,
          }
        },
        callback: (data) => {
          onChange?.(catalogId);
          showMessage('success', '导入动作完成，详情查看日志');
        }
      })
    } else {
      dispatch({
        type: 'assetmanage.importIndicator',
        payload: { 
          fileList: [fileList[0]],
          params: {
            updater: app?.user?.userName
          }
        },
        callback: (data) => {
          onChange?.(catalogId);
          showMessage('success', '导入动作完成，详情查看日志');
        }
      })
    }
  }

  const onExportClick = () => {
    if (catalogId === '1') {
      dispatch({
        type: 'assetmanage.exportMetadataAttributes',
        payload: { 
          responseType: 'blob', 
          params: {  
            tableId: metadataId
          } 
        },
        callback: (res) => {
          download(res);
        }
      })
    } else {
      dispatch({
        type: 'assetmanage.getMetadataStandardList',
        payload: {
          data: {
            parentMetadataId: metadataId
          },
          params: {
            page: 1,
            size: 999999
          }
        },
        callback: data => {
          dispatch({
            type: 'assetmanage.exportIndicator',
            payload: { 
              responseType: 'blob', 
              params: {  
                tableId: metadataId,
                ids: data.content?.map(item => item.id)
              } 
            },
            callback: (res) => {
              download(res);
            }
          })
        },
      });
    }
  }

  const onDetailCancel = () => {
    setDetailParam({...detailParam, visible: false});
  }

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

  return (
    <Drawer 
      visible={visible}
      title='字段级资产目录维护'
      width={900}
      placement="right"
      closable={ true }
      onClose={() => {
        reset();
        onCancel?.();
      }}
    >
      {
        step === 1 && <React.Fragment>
          <div className='flex' style={{ justifyContent: 'space-between' }}>
            <Button type='primary' onClick={() => {setStep(2);}}>上传文件</Button>
            <Space>
              <Select 
                value={catalogId}
                onChange={(value) => {
                  setCatalogId(value);
                }}
                style={{ width: 150 }}
              >
              {
                catalogs?.map((catalog, index) => {
                  return <Select.Option key={index} value={catalog.key}>
                  {catalog.title}
                  </Select.Option>
                })
              }
              </Select>
              <Button onClick={() => getLogs()}>刷新</Button>
            </Space>
          </div>
          <Table
            className='mt-3'
            columns={columns||[]} 
            rowKey='id'
            dataSource={logs||[]}
            pagination={false} 
            loading={loading}
            sticky
          />
          <Pagination
            className="text-center mt-3"
            showSizeChanger
            showQuickJumper
            onChange={(_pageNum, _pageSize) => {
              setPagination({ pageNum: _pageNum||1, pageSize: _pageSize || 20 });
            }}
            onShowSizeChange={(_pageNum, _pageSize) => {
              setPagination({ pageNum: _pageNum || 1, pageSize: _pageSize || 20 });
            }}
            current={pageNum}
            pageSize={pageSize}
            defaultCurrent={1}
            total={total}
            pageSizeOptions={[10,20]}
            showTotal={total => `共 ${total} 条`}
          />
        </React.Fragment>
      }
      {
        step === 2 && <React.Fragment>
           <div className='flex' style={{ justifyContent: 'space-between', alignItems: 'center' }}>
            <Radio.Group 
              onChange={(e) => {
                setCatalogId(e.target.value);
              }} 
              value={catalogId}
            >
              {
                catalogs.map((catalog, index) => <Radio key={index} value={catalog.key}>{catalog.title}</Radio>)
              }
            </Radio.Group>
            <Button onClick={() => { 
              setStep(1); 
              getLogs();
            }}>查看日志</Button>
          </div>
          <div className='flex mt-3' style={{ justifyContent: 'space-between' }}>
            <Upload style={{ display: 'inline' }} {...uploadProps }>
              <Button icon={
                <UploadOutlined />}>
                选择文件上传
              </Button>
            </Upload>
            {/* {
              catalogId === '2' && <Button icon={<DownloadOutlined />} onClick={ downloadTemplate }>
              模板下载
              </Button>
            } */}
          </div>
          <div className='mt-3'>
            <Space>
              <Button type='primary' onClick={onImportClick}>导入</Button>
              <Button type='primary' onClick={onExportClick}>导出</Button>
            </Space>
          </div>
        </React.Fragment>
      }
      <Detail
        visible={detailParam.visible}
        type={detailParam.type}
        id={detailParam.id}
        message={detailParam.message}
        onCancel={onDetailCancel}
      />
    </Drawer>
  )
}

export default FC;

const Detail = ({ visible, message, id, type, onCancel }) => {
  const [currentMessage, setCurrentMessage] = useState(undefined);
  const [loading, setLoading] = useState(false);
  useEffect(() => {
    if (visible) {
      if (type === '1') {
        getMetadataImportAssetLogDetail();
      } else {
        setCurrentMessage(message);
      }
    }
  }, [visible, type, message, id])

  const getMetadataImportAssetLogDetail = () => {
    setLoading(true);
    dispatch({
      type: 'assetmanage.getMetadataImportAssetLogDetail',
      payload: {
        logId: id
      },
      callback: data => {
        setLoading(false);
        setCurrentMessage(data?.message);
      },
      error: () => {
        setLoading(false);
      }
    });
  }

  return (
    <Modal
      title='导入详情'
      width={600}
      visible={visible}
      footer={null}
      onCancel={() => { 
        setLoading(false);
        onCancel?.(); 
      }}
      bodyStyle={{ 
        height: 400,
        overflow: 'auto'
      }}
    >
      <Spin spinning={loading}>
      {
        (type === '1') ? currentMessage?.split('<br />').map((info, index) => {
          return <Typography.Paragraph key={index}>{info}</Typography.Paragraph>
        }) : currentMessage?.split('\n').map((info, index) => {
          return <Typography.Paragraph key={index}>{info}</Typography.Paragraph>
        })
      }
      </Spin>
    </Modal>
  )
}