import React, { useState, useEffect } from 'react';
import { Form, Button, Space } from 'antd';
import LocalStorage from 'local-storage';

import TemplateAction from './TemplateAction';
import { dispatchLatest } from '../../../../model'; 
import { getQueryParam, showMessage } from '../../../../util';
import { Action, TemplateId } from '../../../../util/constant';

import '../../Model/Component/EditModel.less';

const EditTemplate = (props) => {

  const [ actionData, setActionData ] = useState({ action: '', templateId: '', });

  const [ templateData, setTemplateData ] = useState({});
  const [ confirmLoading, setConfirmLoading ] = useState(false);

  const { action, templateId } = actionData;

  const [form] = Form.useForm();

  useEffect(() => {
    const _action = getQueryParam(Action, props.location.search);
    const _templateId = getQueryParam(TemplateId, props.location.search);

    setActionData({ action: _action, templateId: _templateId });
    
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

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

      const newTemplateData = {...templateData, ...row};

      setConfirmLoading(true);
      dispatchLatest({
        type: 'datamodel.saveTemplate',
        payload: { 
          data: newTemplateData
        },
        callback: data => {
          setConfirmLoading(false);
          if (action === 'add') {
            showMessage("success", '新增模型成功');
            setActionData({ ...actionData, ...{ action: 'detail',templateId: data.id } });
          } else {
            showMessage("success", '保存模型成功');
            setActionData({ ...actionData, ...{ action: 'detail', templateId: data.id||'' } });
          }

          LocalStorage.set('templateChange', !(LocalStorage.get('templateChange')||false));
          
        },
        error: () => {
          setConfirmLoading(false);
        }
      })

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

  }

  const edit = () => {
    setActionData({ ...actionData, action: 'edit' });
  }

  const cancelEdit = () => {
    setActionData({ ...actionData, action: 'detail' });
  }

  const onActionChange = (data) => {
    setTemplateData(data);
  }

  let title = '';
  if (action === 'add') {
    title = '新增模版';
  } else if (action === 'edit') {
    title = '模版编辑';
  } else if (action === 'detail') {
    title = '模版详情';
  }

  let actionsBtn = null;

  if (action==='add') {
    actionsBtn = (
      <Space>
        <Button 
          type='primary' 
          onClick={save}
          loading={confirmLoading}
          danger
        >
        保存
        </Button>
      </Space>
    )
  } else if (action === 'detail') {
    actionsBtn = (
      <Space>
        <Button type='primary' onClick={edit} danger >
          编辑
        </Button>
      </Space>
    );
  } else if (action === 'edit') {
    actionsBtn = (
      <Space>
        <Button 
          type='primary' 
          onClick={save}
          loading={confirmLoading}
          danger
        >
        保存
        </Button>
        <Button onClick={cancelEdit} >
        取消
        </Button>
      </Space>
    )
  }

  return (
    <div className='edit-model position-relative'>
      {/* <div className='edit-header'>
        <span style={{ fontSize: 16, fontWeight: 'bold' }}>{title}</span>
      </div> */}
      <div className='edit-container'>
        <div className='edit-container-card'>
          <TemplateAction onChange={onActionChange} action={action} id={templateId} form={form} /> 
        </div>
      </div>
      <div className='edit-footer'>
      {actionsBtn}  
      </div>
    </div>
  );
} 

export default EditTemplate;