import React, { useEffect, useState } from 'react';
import { Modal, Form, Input, Space, Button, Select } from 'antd';
import { dispatch } from '../../../../model';
import { AppContext } from '../../../../App';
import MetadataInfo from './MetadataInfo';
import { showMessage } from '../../../../util';

const { Option } = Select;

const DirsSelect = ({ value = [], data = [], onChange, ...restProps }) => {

  const onDirChange = (value, option) => {
    if (option.length > 0) {
      const recentItem = option[option.length-1];
      const recentItemTheme = recentItem.children.split('/')[0];

      const newValue = [];
      option.forEach(item => {
        if (item.children.split('/')[0] !== recentItemTheme) {
          newValue.push(item.value);
        }
      })

      newValue.push(recentItem.value);
      onChange(newValue);
    } else {
      onChange(value);
    }
  }

  return (
    <Select
      mode="multiple"
      value={value||[]}
      onChange={onDirChange}
      allowClear
      style={{ width: '100%' }}
    >
    {
      (data||[]).map((dir, index) => {
        return (
          <Option key={index} value={dir.id||''}>{dir.path||''}</Option>
        );
      })
    }
    </Select>
  )
}

const AssetTagModal = (props) => {

  const { onCancel, visible, id, tag, creator } = props;
  const [ form ] = Form.useForm();
  const [ confirmLoading, setConfirmLoading ] = useState(false);
  const [ elements, setElements ] = useState([]);
  const [ asset, setAsset ] = useState('');
  const [ metadataId, setMetadataId ] = useState('');
  const [ dirs, setDirs ] = useState([]);

  useEffect(() => {

    if (visible && (id||'')!=='') {
      getAsset();
    } else {
      setMetadataId('');
    }
    
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [ visible, id ])

  useEffect(() => {

    if (visible && (tag?.name||'')!=='') {
      getDirectoryByName(tag?.name);
    }
    
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [ visible ])

  const getAsset = () => {
    dispatch({
      type: 'assetmanage.getDataAssetDetail',
      payload: {
        dataAssetId: id
      },
      callback: data => {
        setAsset(data);
        setElements(data?.elements||[]);
        setMetadataId(data.mid||'');
        let _fieldsValue = {};
        (data.elements||[]).forEach(element => {
          _fieldsValue[element.name] = element.value;
        })

        form.setFieldsValue(_fieldsValue);
      }
    })
  }

  const getDirectoryByName = (keyword) => {
    dispatch({
      type: 'assetmanage.listDirectoryByName',
      payload: {
        name: keyword
      },
      callback: data => {
        setDirs(data||[]);
      }
    });
  }

  //选中元数据后 内容回填.
  const fillElementValueBeforeCreate = (mid = metadataId) => {
    dispatch({
      type: 'assetmanage.fillElementValueBeforeCreate',
      payload: {
        params: {
          metadataIds: mid
        }
      },
      callback: data => {
        let _fieldsValue = {};
        (data||[]).forEach(element => {
          _fieldsValue[element.name] = element.value;
        })

        form.setFieldsValue(_fieldsValue);
      }
    })
  }

  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: (row.dirs||[]).join(','),
      }

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

      setConfirmLoading(true);

      dispatch({
        type: 'assetmanage.addOrUpdateDataAsset',
        payload: { 
          params,
          data: { ...asset, elements: newElements } 
        },
        callback: data => {
          const ids = [id];
          if (data && ((data?.id||'')!=='') && (data?.id!==id)) {
            ids.push(data?.id);
          }

          dispatch({
            type: 'tag.batchAddTagResourceByTagList',
            payload: {
              params: {
                tagIds: tag?.tagId,
                resourceIds: ids.join(','),
                type: 'dataAsset',
                creator
              }
            },
            callback: () => {
              reset();
              onCancel && onCancel(true);
            },
            error: () => {
              setConfirmLoading(false);
            }
          })
        },
        error: () => {
          setConfirmLoading(false);
        }
      })

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

  const reset = () => {
    setConfirmLoading(false);
    form?.resetFields();
  }

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 5 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 17 },
    },
  };

  return (
    <Modal
      forceRender
      className='asset-add'
      title='资产目录打标签'
      visible={ visible }
      width={ 600 }
      onCancel={() => { 
        reset();
        onCancel && onCancel(); 
      } }
      footer={
        <Space>
          <Button onClick={() => onCancel && onCancel() }>取消</Button>
          <Button type="primary" onClick={ onOk } loading={ confirmLoading }>确定</Button>
        </Space>
      }
    >
    {
      visible && <Form {...formItemLayout} form={form}>
       <AppContext.Consumer>
       {
       value => {
         value?.onGlobalStateChange&&value?.onGlobalStateChange((state, prev) => {
           if (state.message === 'data-govern-show-metadata-list-callback-message') {
             setMetadataId(state.data?.metadataId||'');
             form?.setFieldsValue({ '资产项': state.data?.metadataInfoJson||'' });

             if ((state.data?.metadataId||'') !== '') {
               fillElementValueBeforeCreate(state.data?.metadataId||'');
             }
           }
         });

         return (
           <>
           <Form.Item
             label='资产目录标签'
             name='tag'
           >
            <span>{tag?.name||''}</span>
           </Form.Item>
           <Form.Item
             label='挂载目录'
             name='dirs'
             required={true}
           >
             <DirsSelect data={dirs||[]} />
           </Form.Item>
           { (elements||[]).map((element, index) => {
             return ( 
               <Form.Item 
                 label={element.name}
                 name={element.name}
                 key={index}
               >
               { (element.name==='资产项') ? <MetadataInfo /> : <Input disabled={element.manualMaintain==='否'}  /> }
               </Form.Item>
             )
           })}
           </>
         );
       }}
       </AppContext.Consumer>
     </Form>
    }
    </Modal>
  );
} 

export default AssetTagModal;
