import React, { useState, useEffect } from 'react';
import { Spin, Tabs, Popover, Divider, Button, Space } from 'antd';
import { QuestionCircleOutlined } from '@ant-design/icons';

import TemplateActionHeader from './TemplateActionHeader'; 
import { ImportActionTable } from '../../Model/Component/ImportActionTable';

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

const { TabPane } = Tabs;

const TemplateAction = (props) => {
  const { action, onChange, form, id } = props;

  const [ templateData, setTemplateData ] = useState(null);
  const [ supportedDatatypes, setSupportedDatatypes ] = useState([]);

  const [ tabKey, setTabKey ] = useState('1');
  const [ loading, setLoading ] = useState(false);

  useEffect(() =>{

    //初始化form状态
    if (action==='add'||action==='edit') {
      form?.resetFields()
    }
    if (action === 'add') {
      getSupportedDatatypes();
    } else if ((action === 'edit'||action === 'detail') && id ) {
      getCurrentTemplate();
    }
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [action, id ]);

  const getCurrentTemplate = () => {
    setLoading(true);
    dispatchLatest({
      type: 'datamodel.getTemplate',
      payload: {
        params: {
          id 
        }
      },
      callback: data => {
        setTemplateData(data||{});
        onChange && onChange(data||{});
        getSupportedDatatypes();
        
        if (action === 'edit') {
          form.setFieldsValue(data)
        }
      }, 
      error: () => {
        setLoading(false);
      }
    })
  }

  const getSupportedDatatypes = () => {
    setLoading(true);
    dispatch({
      type: 'datamodel.getSupportedDatatypes',
      callback: data => {
        setLoading(false);
        setSupportedDatatypes(data||[]);
      },
      error: () => {
        setLoading(false);
      }
    });
  }

  //模版不需要对字段进行校验
  const onTableChange = (data) => { 

    let newTemplateData = {...templateData, ...{easyDataModelerDataModelAttributes: data}};
    
    setTemplateData(newTemplateData);
    onChange && onChange(newTemplateData);

  }

  const onTabChange = (key) => {
    setTabKey(key);
  }

  const prevStep = () => {
    setTabKey(`${Number(tabKey)-1}`);
  }

  const nextStep = () => {
    setTabKey(`${Number(tabKey)+1}`);
  }

  console.log('templateData', templateData)

  return (
    <Spin spinning={loading}>
      <Tabs activeKey={tabKey} onChange={onTabChange}>
        <TabPane tab='基本信息' key='1'>
          <TemplateActionHeader 
            form={form}
            editable={action!=='detail'} 
            templateData={templateData||{}}
            onChange={(val) => {
              const newTemplateData = {...templateData, ...val};    
              setTemplateData(newTemplateData);
              onChange && onChange(newTemplateData);
            }}
          /> 
        </TabPane>
        <TabPane 
          tab={
            <span>
              <span>数据表结构</span>
              {
                (action!=='detail'&&action!=='flow'&&action!=='detail-version') && (
                  <Popover content='表格可以通过拖拽来排序'>
                    <QuestionCircleOutlined className='ml-1 pointer' /> 
                  </Popover> 
                )
              }
            </span>
          } 
          key='2'
        > 
          <ImportActionTable 
            type='template'
            modelerData={templateData||{}}
            supportedDatatypes={supportedDatatypes} 
            onChange={onTableChange} 
            editable={action!=='detail'} 
          />
        </TabPane>
      </Tabs>
      {
        action!=='detail'&&(
          <React.Fragment>
            <Divider style={{ margin: 0 }} />
            <div className='flex' style={{ justifyContent: 'flex-end', height: 64, alignItems: 'center' }}>
              <Space size='small'>
                <Button type='primary' onClick={prevStep} disabled={tabKey==='1'} danger>上一步</Button>
                <Button type='primary' onClick={nextStep} disabled={tabKey==='2'} danger>下一步</Button>
              </Space>
            </div>
          </React.Fragment>
        )
      }
    </Spin>
  );
};

export default TemplateAction;