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

import './AddAssetModel.less';

const AddAssetModel = (props) => {

  const { onCancel, visible, nodeId } = props;
  const [ confirmLoading, setConfirmLoading ] = useState(false);
  const [ metadataId, setMetadataId ] = useState('');
  const [ elements, setElements ] = useState([]);

  const [ form ] = Form.useForm();

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

  const onMetadataChange = (value) => {
    setMetadataId(value);
  }

  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];
        }
      });

      const params = {
        dirId: nodeId,
      }

      if ((metadataId||'')!=='') {
        params.metadataId = metadataId;
      }

      setConfirmLoading(true);

      dispatch({
        type: 'assetmanage.checkCodeIsExist',
        payload: { 
          data: { elements: newElements } 
        },
        callback: isExist => {
          if (isExist === 'true') {
            setConfirmLoading(false);
            showMessage('warn', '已存在相同的资产目录编号,请重新输入');
          } else {
            dispatch({
              type: 'assetmanage.addOrUpdateDataAsset',
              payload: { 
                params,
                data: { elements: newElements } 
              },
              callback: () => {
                setConfirmLoading(false);
                showMessage("success","新增成功");
                onCancel && onCancel(true);
              },
              error: () => {
                setConfirmLoading(false);
              }
            })
          }
        },
        error: () => {
          setConfirmLoading(false);
        }
      })

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

  return (
    <Modal
      forceRender
      className='asset-add'
      title='新增资产目录信息'
      visible={ visible }
      width={ 600 }
      onCancel={() => { onCancel && onCancel(); } }
      footer={
        <Space>
          <Button onClick={() => onCancel && onCancel() }>取消</Button>
          <Button type="primary" onClick={ onOk } loading={ confirmLoading }>确定</Button>
        </Space>
      }
      bodyStyle={{ padding: '10px' }}
    >
    {
      visible && <AssetAction 
        form={form}
        dirId={nodeId} 
        action='add'
        onMetadataChange={onMetadataChange}
        onElementsChange={onElementsChange}
      />
    }
    </Modal>
  );
} 

export default AddAssetModel;