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 SelectAsset from './select-asset';

import { dispatchLatest, dispatch } from '../../../../model'; 
import { isSzseEnv } from '../../../../util';
import { AppContext } from '../../../../App';
import IframeDrawer from '../../ModelConfig/Component/IframeDrawer';
import { Action, CatalogId, MetadataId } from '../../../../util/constant';

const importModes = [
  { name: '快速创建', key: 'excel-copy' },
  { name: '空白创建', key: 'no-condition' },
  { name: '资产导入', key: 'asset-import' },
  { name: '元数据导入', key: 'metadata-import' },
  // { 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 [selectAssetParams, setSelectAssetParams] = useState({
    visible: false,
    catalogId: undefined,
  })
  const [iframeDrawerParams, setIframeDrawerParams] = React.useState({
    visible: false,
    title: undefined,
    url: undefined,
  })

  const app = React.useContext(AppContext)
  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);
            onCancelByWord && onCancelByWord(true, data||{});
            reset();
          },
          error: () => {
            setConfirmLoading(false);
          }
        });
  
      } else if (modeKey==='excel') {
  
        setConfirmLoading(true);
        dispatchLatest({
          type: 'datamodel.extractExcelContent',
          payload: { fileList: row.upload },
          callback: data => {
            setConfirmLoading(false);
            onCancel && onCancel(false, true, data||[]);
            reset();
          },
          error: () => {
            setConfirmLoading(false);
          }
        })
  
      } else if (modeKey==='excel-copy') {
        onCancel && onCancel(false, true, hints||[]);
        reset();
      } else if (modeKey==='no-condition') {
        onCancel && onCancel(false, true, []);
        reset();
      } else if (modeKey==='ddl') {
        onCancelByDDL && onCancelByDDL(true, ddl);
        reset();
      } else if (modeKey === 'asset-import') {
        setSelectAssetParams({ visible: true, catalogId })
      } else if (modeKey === 'metadata-import') {
        app?.setGlobalState?.({
          message: 'data-govern-show-select-metadata',
          data: {
            cb: (val) => {
              dispatch({
                type: 'datamodel.getDraftUsingMetadataId',
                payload: {
                  params: {
                    dataCatalogId: catalogId,
                  },
                  data: {
                    metadataTableId: val,
                    modelerModelingConstraint: null,
                    easyDataModelerModelingTemplate: {}, 
                  }   
                },
                callback: data => {
                  setIframeDrawerParams({
                    visible: true,
                    title: '新增模型',
                    url: `/data-govern/data-model-action?${Action}=add&${MetadataId}=${val}&${CatalogId}=${catalogId??''}`,
                  })
                }
              });
            }
          }
        })
      }
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }

  }

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

  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 
      destroyOnClose
      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>
    <SelectAsset 
      {...selectAssetParams}
      onCancel={() => {
        setSelectAssetParams({ visible: false, catalogId: undefined })
      }}
    />
    { iframeDrawerParams.visible && <IframeDrawer
      {...iframeDrawerParams}
      onCancel={() => {
        setIframeDrawerParams({
          visible: false,
          title: undefined,
          url: undefined,
        })
      }}
    /> }
    </>
  )
}

export default ImportModal;