import React, { useEffect, useState } from "react";
import { Modal, Form, Input, message } from "antd";
import { WorkTypeListVO, saveWorkType } from "../api";

interface Props {
  visible: boolean;
  onCancel: () => void;
  onRefreshing: () => void;
  item: WorkTypeListVO;
}
export default function CreateModal({
  visible,
  onCancel,
  item,
  onRefreshing,
}: Props) {
  const [form] = Form.useForm();
  const [saveLoading, setSaveLoading] = useState(false);

  useEffect(() => {
    if (visible) {
      form.setFieldsValue({
        ...item,
      });
    }
  }, [visible]);

  function handleSave(feildValue: any) {
    setSaveLoading(true);
    const params = {
      ...feildValue,
      id: item.id,
      name: (feildValue.name || "").trim(),
    };

    setSaveLoading(false);
    saveWorkType(params)
      .then((res) => {
        message.success("保存成功！");
        onCancel && onCancel();
      })
      .catch((e) => {
        message.error(e.message);
      })
      .finally(() => setSaveLoading(false));
  }

  return (
    <Modal
      visible={visible}
      onCancel={onCancel}
      onOk={form.submit}
      title={`${item.name ? "编辑" : "新增"}工作类型`}
      confirmLoading={saveLoading}
      maskClosable={false}
      afterClose={() => {
        form.resetFields();
      }}
    >
      <Form
        form={form}
        onFinish={handleSave}
        wrapperCol={{ span: 18 }}
        labelCol={{ span: 6 }}
      >
        <Form.Item
          label="工作类型名称"
          name="name"
          rules={[{ required: true }]}
        >
          <Input placeholder="请输入工作类型名称" />
        </Form.Item>
      </Form>
    </Modal>
  );
}
