import { useEffect, useState, useMemo } from "react";
import { Modal, Form, Input, Button, Descriptions } from "antd";

import { dispatch } from "../../../../../model";

import './UpdateDataMasterModal.less';

const UpdateDataMasterModal = (props) => {
  const {visible, onCancel, data, fields, action = 'add', nodeId} = props;
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [form] = Form.useForm();

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 6 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 18 },
    },
  };

  useEffect(() => {
    if (visible) {
      let newFieldsValue = {};
      (fields||[]).forEach(item => {
        newFieldsValue[item.name] = data?data[item.name]:'';
      });

      form?.setFieldsValue(newFieldsValue);    
    }
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visible, data, fields])

  const title = useMemo(() => {
    if (action === 'add') {
      return '新建主数据';
    }
    if (action === 'detail') {
      return '主数据详情';
    }
    if (action === 'update') {
      return '编辑主数据';
    }

    return '';
  }, [action])

  const onFormFinish = async() => {
    try {
      const row = await form.validateFields();

      setConfirmLoading(true);
      let url = '', newData = {};
      if (action === 'add') {
        url = 'msd.addData';
        newData = row;
      } else {
        url = 'msd.updateData';
        newData = {...data, ...row};
      }

      dispatch({
        type: url,
        payload: {
          params: {
            modelId: nodeId,
          },
          data: newData
        },
        callback: () => {
          setConfirmLoading(false);
          onCancel && onCancel(true);  
        },
        error: () => {
          setConfirmLoading(false);
        }
      });
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  }

  return (
    <Modal
      className='update-data-master-modal'
      title={title}
      visible={visible}
      onCancel={() => { onCancel && onCancel(false); }}
      onOk={onFormFinish}
      footer={[
        <Button key="cancel" onClick={() => {onCancel && onCancel();}}>
          取消
        </Button>,
        action!=='detail' && <Button
          key="ok"
          type="primary"
          loading={confirmLoading}
          onClick={onFormFinish}
        >
          确定
        </Button>,
      ]}
    >
    {
      (action!=='detail') ? <Form 
        form={form}
        {...formItemLayout}
      >
        {
          (fields||[]).map((item, index) => {
            return (
              <Form.Item key={index} label={item.name} name={item.name} rules={[{ required: false }]}>
                <Input />
              </Form.Item>
            )
          })
        }
      </Form> : <Descriptions column={1}>
        {
          (fields||[]).map((item, index) => {
            return (
              <Descriptions.Item label={<div style={{ textAlign: 'right', width: 85 }}>{item.name||''}</div>} >{data?data[item.name||'']:''}</Descriptions.Item>
            );
          })
        }
      </Descriptions>
    }
    </Modal>
  );
}

export default UpdateDataMasterModal;