import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Radio } from 'antd';

import { dispatchLatest } from '../../../../model'; 

class UpdateTreeItemForm extends React.Component {

  constructor(props){
    super(props);
    this.state = {
      radioDisable: false
    }
  }

  componentDidMount() {
    this.radioState();
  }

  componentDidUpdate(preProps, preState) {
    const { item } = this.props;
    if (item!==preProps.item) {
      this.radioState();
    }
  }

  radioState = () => {
    const { item } = this.props;
    this.setState({ radioDisable: item? false: true })
  }

  render() {
    const { type, form } = this.props;
    const { radioDisable } = this.state;

    return (
      <Form 
        form={form}
      >
        {
          type==='add'&&<Form.Item label="目录类型" name="action">
            <Radio.Group disabled={radioDisable} >
              <Radio value='root'>根目录</Radio>
              <Radio value='sub'>子目录</Radio>
            </Radio.Group>
          </Form.Item>
        }
        <Form.Item 
          label="名称" 
          name="name"
          rules={[{ required: true, message: '请输入名称!' }]}
          >
          <Input />
        </Form.Item>
        <Form.Item 
          label="简称" 
          name="abbreviation"
          rules={[{ required: true, message: '请输入简称!' }]}
          >
          <Input />
        </Form.Item>
        <Form.Item 
          label="范围" 
          name="rangeList"
          rules={[{ required: true, message: '请输入范围!' }]}
          >
          <Input placeholder='请输入范围,支持以空格、逗号作为分隔符' />
        </Form.Item>
        <Form.Item 
          label="描述" 
          name="remark"
          rules={[{ required: true, message: '请输入描述!' }]}
          >
          <Input />
        </Form.Item>
      </Form>
    );
  }
}

const UpdateTreeItemModal = (props) => {

  const { onOk, type, item, onCancel, visible, rootId } = props;
  const [ confirmLoading, setConfirmLoading ] = useState(false);
  const [form] = Form.useForm();

  useEffect(() => {
    if (visible) {
      let _action = '';
      if (type === 'add') {
        _action = item ? 'sub' : 'root';
      }

      if (type === 'add') {
        form.setFieldsValue({ action: _action });
      } else {
        form.setFieldsValue({ action: '', ...item, rangeList: (item?.rangeList??[]).toString() });
      }
    }
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visible])

  const handleOk = async () => {

    setConfirmLoading(true);

    try {
      const values = await form.validateFields();

      let payload = null;
      if (type === 'add' && values.action==='root') {
        payload = {
          ...values,
          rangeList: (values.rangeList??'').replace(/[,,， ]/g,'\n').split('\n').filter(value => value!==''&&value!==' '),
          parentId: rootId
        };
      } else if (type === 'add') {
        payload = {
          ...values,
          rangeList: (values.rangeList??'').replace(/[,,， ]/g,'\n').split('\n').filter(value => value!==''&&value!==' '),
          parentId: item.id
        };
      } else {
        payload = {
          ...item,
          ...values,
          rangeList: (values.rangeList??'').replace(/[,,， ]/g,'\n').split('\n').filter(value => value!==''&&value!==' '),
        }
      }

      dispatchLatest({
        type: 'datamodel.saveDataModelCatalog',
        payload: {
          data: payload
        },
        callback: id => {
          setConfirmLoading(false);
          form.resetFields();

          if (onOk) {
            onOk(id, payload);
          }
        },
        error: () => {
          setConfirmLoading(false);
        }
      });
    } catch (errInfo) {
      setConfirmLoading(false);
    }
  }

  return (
    <Modal 
      destroyOnClose
      confirmLoading={confirmLoading}
      visible={visible}
      title={type==='add'?"新增目录":"更新目录"}
      onOk={handleOk}
      onCancel={() => {
        setConfirmLoading(false);
        form.resetFields();
        onCancel && onCancel();
      }}
    >
      <UpdateTreeItemForm form={form} item={item} type={type} />
    </Modal>
  );
}

export default UpdateTreeItemModal;