import React, { useState } from 'react';
import { Button, Upload, Form, Row, Col } from 'antd';
import { DownloadOutlined, UploadOutlined } from '@ant-design/icons';

import { dispatchLatest } from '../../../../model'; 

const WordTemplate = (props) => {
  const [ fileList, setFileList ] = useState([]);
  const [ confirmLoading, setConfirmLoading ] = useState(false);

  const [ form ] = Form.useForm();

  const downloadTemplate = () => {
    window.open("/api/datamodeler/easyDataModelerExport/word/downloadTemplate");
  }

  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 normFile = (e) => {  
    return fileList;
  };

  const handleOk = async() => {
    try {
      const row = await form.validateFields();

      setConfirmLoading(true);
      dispatchLatest({
        type: 'datamodel.uploadWordTemplate',
        payload: { fileList: row.upload },
        callback: data => {
          setConfirmLoading(false);
          reset();
        },
        error: () => {
          setConfirmLoading(false);
        }
      })

    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  }

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

  const layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
  };
  const tailLayout = {
    wrapperCol: { offset: 8, span: 16 },
  };

  return (
    <Form form={form} {...layout} onFinish={handleOk}>
      <Form.Item 
        label='最新模版上传'
        required={true} 
      >
        <Row>
          <Col>
            <Form.Item
              name='upload'
              valuePropName="fileList"
              getValueFromEvent={normFile}
              noStyle
              rules={[
                {
                  required: true,
                  message: '请选择文件上传',
                },
              ]}
            >
              <Upload {...uploadProps}>
                <Button icon={<UploadOutlined />}>
                  选择文件上传
                </Button>
              </Upload>
            </Form.Item>
          </Col>
          <Col>
            <Button className='ml-3' icon={<DownloadOutlined />} onClick={ downloadTemplate }>
            模版下载
            </Button>
          </Col>
        </Row>
      </Form.Item>
      <Form.Item {...tailLayout}>
        <Button type="primary" htmlType="submit" loading={confirmLoading}>
          确定
        </Button>
      </Form.Item>
    </Form>
  )
}

export default WordTemplate;