import React, { useEffect } from 'react';
import { UpdateFlowGroup } from '@/services/workflow/workflow';
import { Form, Modal, Input, notification } from 'antd';

const FlowGroupModal = props => {
  const { onSubumit, handleCancel, visible, msg, modalType, treeData, keep } = props;
  const [form] = Form.useForm();
  useEffect(() => {
    form.resetFields();
    if (visible) {
      console.log(keep);
      if (modalType === 'edit') {
        getFormData();
      }
    }
  }, [visible]);
  // 获取表单回显
  const getFormData = () => {
    form.setFieldsValue({ name: msg.name });
  };
  // 提交表单
  const onFinish = () => {
    form.validateFields().then(validate => {
      if (validate) {
        let hasName;
        hasName = treeData.some(item => item.name === validate.name);
        if (modalType === 'edit') {
          if (hasName && validate.name !== msg.name) {
            notification.error({
              message: '提示',
              duration: 3,
              description: '流程组名称不能重复',
            });
            return;
          }
          if (validate.name === msg.name) {
            onSubumit();
            return;
          }
          if (!msg.isOld) {
            onSubumit(validate.name);
            return;
          }
          UpdateFlowGroup({
            oldName: msg.name,
            newName: validate.name,
          }).then(res => {
            if (res.code === 0) {
              onSubumit();
              notification.success({
                message: '提示',
                duration: 3,
                description: '编辑成功',
              });
            } else {
              onSubumit(validate.name);
              notification.error({
                message: '提示',
                duration: 3,
                description: res.msg,
              });
            }
          });
        } else {
          // 新增
          if (hasName) {
            notification.error({
              message: '提示',
              duration: 3,
              description: '流程组名称不能重复',
            });
            return;
          }
          notification.success({
            message: '提示',
            duration: 3,
            description: '新增成功',
          });
          onSubumit(validate.name);
        }
      }
    });
  };
  return (
    <Modal
      title={`${modalType === 'edit' ? '编辑' : '创建'}分组`}
      visible={visible}
      onOk={onFinish}
      onCancel={handleCancel}
      maskClosable={false}
      destroyOnClose
    >
      <Form form={form} labelCol={{ span: 5 }} wrapperCol={{ span: 18 }}>
        <Form.Item
          label="分组名称"
          name="name"
          rules={[{ required: true, message: '请输入分组名称' }]}
        >
          <Input placeholder="请输入分组名称" />
        </Form.Item>
      </Form>
    </Modal>
  );
};
export default FlowGroupModal;
