import React, { useState } from "react";
import { Modal } from "antd";

import { dispatch } from '../../../../model';
import AssetTree from '../../AssetManage/Component/AssetManageTree';
import { showMessage } from '../../../../util';

import { AssetManageReference, AssetRecycleReference, AssetMountReference } from "../../../../util/constant";

const AssetMount = (props) => {
  
  const { onCancel, visible, ids, reference = AssetManageReference } = props;
  const [ dirIds, setDirIds ] = useState([]);
  const [ confirmLoading, setConfirmLoading ] = useState(false);

  const onCheck = (values) => {
    setDirIds(values||[]);
  }

  const onOk = () => {
    if ((dirIds||[]).length === 0) {
      showMessage('warn', '请先选择资产目录的目录');
      return;
    }
    
    setConfirmLoading(true);
    dispatch({
      type: 'assetmanage.checkIsNeedSaveAsDraft',
      callback: (data) => {
        const needSaveAsDraft = (data==='true')?true:false

        dispatch({
          type: (needSaveAsDraft)?'assetmanage.loadDataAssetsAsDraft':'assetmanage.loadDataAssets',
          payload: {
            params: {
              dirId: dirIds.join(","),
            },
            data: ids
          },
          callback: data => {
            setConfirmLoading(false);
            showMessage('success', (reference === AssetRecycleReference)?'挂载成功':'变更目录成功');
            reset();
            onCancel && onCancel(true);
          },
          error: () => {
            setConfirmLoading(false);
          }
        })
      },
      error: () => {
        setConfirmLoading(false);
      }
    })
  }

  const reset = () => {
    setConfirmLoading(false);
  }

  return(
    <Modal
      forceRender
      title={(reference===AssetRecycleReference)?'挂载目录详情':'变更目录详情'}
      visible={ visible }
      width={ 400 }
      confirmLoading={ confirmLoading }
      onCancel={()=>{ 
        reset();
        onCancel && onCancel()
      }}
      onOk={ onOk }
    >
      {
        visible && <AssetTree 
        checkable={true}
        onCheck={onCheck}
        tableId={(reference===AssetManageReference&&(ids||[].length>0))?ids[0]:''}
        reference={AssetMountReference}
      />
      }
    </Modal>
  )
}

export default AssetMount;