import React, { useState, useRef } from 'react';
import { Modal, Form, Space, Button, Spin } from 'antd';
import { showMessage } from '../../../../util';
import { dispatch } from '../../../../model';
import AssetAction from './AssetAction';
import { getTemplateType } from '../../../../util/axios';

const AddAssetModel = (props) => {
  const { onCancel, visible, nodeId } = props;
  const [ waiting, setWaiting ] = useState(false);
  const [ elements, setElements ] = useState([]);
  const [postRelations, setPostRelations] = useState();

  const [ form ] = Form.useForm();

  const onElementsChange = (value) => {
    setElements(value);
  }

  const onPostRelationsChange = (value) => {
    setPostRelations(value);
  }

  const close = (refresh = false) => {
    setWaiting(false)
    form?.resetFields()
    onCancel?.(refresh)
  }

  const onOk = async() => {
    try {
      const row = await form?.validateFields();
      const newElements = [...elements];
      (newElements||[]).forEach(element => {
        if (row.hasOwnProperty(element.name)) {
          element.value = row[element.name];
        }
      });

      setWaiting(true);

      dispatch({
        type: 'assetmanage.checkIsNeedSaveAsDraft',
        callback: (data) => {
          const needSaveAsDraft = (data==='true')?true:false
          
          dispatch({
            type: needSaveAsDraft?'assetmanage.saveAsDraft':'assetmanage.addOrUpdateDataAsset',
            payload: { 
              params: {
                dirId: nodeId,
                operation: 'release',
              },
              data: { elements: newElements, templateType: getTemplateType(), ...postRelations } 
            },
            callback: () => {
              showMessage("success","新增成功");
              close(true)
            },
            error: () => {
              setWaiting(false);
            }
          })
        },
        error: () => {
          setWaiting(false);
        }
      })

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

  return (
    <Modal
      destroyOnClose
      className='asset-add'
      title='新增资产目录信息'
      visible={ visible }
      centered
      width='80%'
      onCancel={() => { close() } }
      footer={
        <Space>
          <Button onClick={() => onCancel && onCancel() }>取消</Button>
          <Button type="primary" onClick={ onOk } disabled={ waiting }>确定</Button>
        </Space>
      }
      bodyStyle={{ overflowX: 'auto', height: '80vh' }}
    >
      <Spin spinning={waiting}>
        <AssetAction 
          form={form}
          dirId={nodeId} 
          action='add'
          onElementsChange={onElementsChange}
          onPostRelationsChange={onPostRelationsChange}
        />
      </Spin>
    </Modal>
  );
} 

export default AddAssetModel;