import { Form, Input, message, Modal, Select } from "antd";
import { useEffect, useState } from "react";
import axiosInstance from "../../api/axios";
import Password from "antd/es/input/Password";

export default function UserDetailModal({
  visiable,
  mode = "create",
  user,
  roles,
  onclose,
  onSuccess,
}) {
  const [form] = Form.useForm();
  const [initialValues, setInitialValues] = useState();
  const [teams, setTeams] = useState([]);

  const fetchTeams = async () => {
    const data = await axiosInstance.get("/team-label");
    setTeams(data);
  };

  useEffect(() => {
    fetchTeams();
  }, []);

  useEffect(() => {
    if (visiable) {
      if (mode === "edit") {
        const values = {
          username: user.username,
          name: user.name,
          phone: user.phone,
          teamId: user.teamId,
          roleId: user.roleId,
        };

        setInitialValues(values);
        form.setFieldsValue(values);
      } else {
        const values = {
          username: undefined,
          password: undefined,
          name: undefined,
          phone: undefined,
          teamId: undefined,
          roleId: undefined,
        };
        setInitialValues(values);
        form.setFieldsValue(values);
      }
    }
  }, [visiable, mode, user, form]);

  const handleOk = async () => {
    const values = await form.validateFields();
    const data = {};
    Object.keys(initialValues).forEach((key) => {
      if (values[key] !== initialValues[key]) {
        data[key] = values[key];
      }
    });

    if (Object.keys(data).length > 0) {
      if (mode === "edit") {
        await axiosInstance.put(`/user/${user.userId}`, data);
        message.success("编辑成功");
      } else {
        await axiosInstance.post(`/user`, data);
        message.success("添加成功");
      }
    }
    onSuccess();
    onclose();
  };
  return (
    <Modal
      title={mode === "edit" ? "编辑用户" : "添加用户"}
      open={visiable}
      onCancel={() => {
        onclose();
      }}
      onOk={handleOk}
      okText="保存"
    >
      <Form form={form} layout="vertical" initialValues={initialValues}>
        <Form.Item
          name="username"
          label="用户账号"
          rules={[{ required: true }]}
        >
          <Input />
        </Form.Item>
        {mode === "create" && (
          <Form.Item
            name="password"
            label="初始密码"
            rules={[{ required: true }]}
          >
            <Input.Password />
          </Form.Item>
        )}
        <Form.Item name="name" label="姓名" rules={[{ required: true }]}>
          <Input />
        </Form.Item>
        <Form.Item name="phone" label="联系电话">
          <Input />
        </Form.Item>
        <Form.Item
          name="teamId"
          label="所属团队"
          rules={[{ required: true, message: "请选择所属团队" }]}
        >
          <Select options={teams} />
        </Form.Item>
        <Form.Item
          name="roleId"
          label="用户角色"
          rules={[{ required: true, message: "请选择用户角色" }]}
        >
          <Select options={roles} />
        </Form.Item>
      </Form>
    </Modal>
  );
}
