import React, { useState } from 'react';
import { Modal, Button, Form, Radio, Tooltip } from 'antd';

import ImportWord from './ImportWord';
import ImportExcel from './ImportExcel';
import ImportExcelCopy from './ImportExcelCopy';
import ImportDDL from './ImportDDL';

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

const importModes = [
  { name: '快速创建', key: 'excel-copy' },
  { name: '空白创建', key: 'no-condition' },
  { name: 'Word导入', key: 'word' },
  { name: 'Excel导入', key: 'excel' },
  { name: 'DDL导入', key: 'ddl' },
] 

const ImportModal = (props) => {
  const { view, catalogId, visible, onCancel, onCancelByWord, onCancelByDDL } = props;

  const [ modeKey, setModeKey ] = useState('excel-copy');
  const [ hints, setHints ] = useState([]);
  const [ ddl, setDDL ] = useState('');
  const [ confirmLoading, setConfirmLoading ] = useState(false);

  const [ form ] = Form.useForm();

  const onModeChange = (e) => {
    setModeKey(e.target?.value);
  }

  const onOk = async() => {
    try {

      const row = await form.validateFields();
   
      if (modeKey==='word') {
  
        setConfirmLoading(true);
        dispatchLatest({
          type: 'datamodel.importWordGenerateModelDraft',
          payload: { 
            params: {
              catalogId,
            },
            fileList: row.upload 
          },
          callback: data => {
            setConfirmLoading(false);
            reset();
            onCancelByWord && onCancelByWord(true, data||{});
          },
          error: () => {
            setConfirmLoading(false);
          }
        });
  
      } else if (modeKey==='excel') {
  
        setConfirmLoading(true);
        dispatchLatest({
          type: 'datamodel.extractExcelContent',
          payload: { fileList: row.upload },
          callback: data => {
            setConfirmLoading(false);
            reset();
            onCancel && onCancel(false, true, data||[]);
          },
          error: () => {
            setConfirmLoading(false);
          }
        })
  
      } else if (modeKey==='excel-copy') {
  
        reset();
        onCancel && onCancel(false, true, hints||[]);

      } else if (modeKey==='no-condition') {
        reset();
        onCancel && onCancel(false, true, []);
      } else if (modeKey==='ddl') {
        reset();
        onCancelByDDL && onCancelByDDL(true, ddl);
      }

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

  }

  const cancel = () => {
    reset();
    onCancel && onCancel();
  }

  const reset = () => {
    form.resetFields();
    form.setFieldsValue({mode: 'excel-copy'});
    setModeKey('excel-copy');
    setHints([]);
    setDDL('');
    setConfirmLoading(false);
  }

  const onImportExcelCopyChange = (data) => {
    setHints(data||[]);
  }

  const onImportDDLChange = (data) => {
    setDDL(data);
  }

  const footer = [ 
    <Button
      key="0" 
      onClick={cancel}
    >
    取消
    </Button>,
    <Button
      key="1" 
      type="primary"
      loading={confirmLoading}
      onClick={onOk}
    >
    确定
    </Button>,
  ];

  return (
    <Modal 
      forceRender
      visible={visible}
      title='新建模型'
      width={isSzseEnv?540:630}
      onCancel={cancel}
      footer={footer}
    >
      <Form form={form}>
        <Form.Item 
          name='mode'
          label='新建方式'
          rules={[
            {
              required: true,
              message: '请选择新建方式',
            },
          ]}
          initialValue={modeKey}
        >
          <Radio.Group onChange={onModeChange} value={modeKey}>
          {
            importModes.map((item, index) => {

              let title = '';
              if (item.key==='word'&&(view!=='dir'||(catalogId||'') === '')) {
                title = '请先选择主题';
              }

              if (isSzseEnv && item.key === 'ddl') {
                return <></>;
              } 

              return (
                <Tooltip key={index} title={title}>
                  <Radio 
                    value={item.key} 
                    disabled={item.key==='word'&&(view!=='dir'||(catalogId||'') === '')}>
                    {item.name}
                  </Radio>
                </Tooltip>
              );
            })
          }
          </Radio.Group>
        </Form.Item>
        {
          modeKey==='word' && (
            <ImportWord {...props} />
          )
        }
        {
          modeKey==='excel' && (
            <ImportExcel {...props} />
          )
        }
        {
          modeKey==='excel-copy' && (
            <ImportExcelCopy onChange={onImportExcelCopyChange} {...props} />
          )
        }
        {
          modeKey==='ddl' && (
            <ImportDDL onChange={onImportDDLChange} />
          )
        }
      </Form>
    </Modal>
  )
}

export default ImportModal;