import { RootState } from "@/store";
import { getUserInfoByIdAPI, userSaveAPI } from "@/store/action/C1User";
import { SaveUserType } from "@/types";
import { MessageFu } from "@/utils/message";
import { Button, Form, Input, Modal, Popconfirm, Select } from "antd";
import React, { useCallback, useEffect, useRef } from "react";
import { useSelector } from "react-redux";
import "./index.css";

type Props = {
  id: any;
  closePage: () => void;
  upTableList: () => void;
  addTableList: () => void;
};

function UserAdd({ id, closePage, upTableList, addTableList }: Props) {
  // 设置表单初始数据（区分编辑和新增）
  const FormBoxRef = useRef<any>({});

  const getInfoInAPIFu = useCallback(async (id: number) => {
    const res = await getUserInfoByIdAPI(id);
    FormBoxRef.current.setFieldsValue(res.data);
    console.log("是编辑，在这里发请求拿数据", res);
  }, []);

  // 没有通过校验
  const onFinishFailed = useCallback(() => {
    // return MessageFu.warning("有表单不符号规则!");
  }, []);

  useEffect(() => {
    if (id) getInfoInAPIFu(id);
    else {
      FormBoxRef.current.setFieldsValue({});
    }
  }, [getInfoInAPIFu, id]);

  // 从仓库获取角色下拉列表信息
  const roleList = useSelector(
    (state: RootState) => state.userReducer.roleList
  );

  // 通过校验点击确定
  const onFinish = useCallback(
    async (values: any) => {
      const obj: SaveUserType = {
        ...values,
        id: id ? id : null,
      };

      const res: any = await userSaveAPI(obj);

      if (res.code === 0) {
        MessageFu.success(id ? "编辑成功!" : "新增成功!");
        if (id) upTableList();
        else addTableList();

        closePage();
      }
      console.log("通过校验，点击确定");
    },
    [addTableList, closePage, id, upTableList]
  );

  return (
    <Modal
      wrapClassName="userAdd"
      destroyOnClose
      open={true}
      title={id ? "编辑用户" : "新增用户"}
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className="userAddMain">
        <Form
          ref={FormBoxRef}
          name="basic"
          labelCol={{ span: 5 }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="账号名"
            name="userName"
            rules={[{ required: true, message: "请输入账号名!" }]}
            getValueFromEvent={(e) => e.target.value.replace(/\s+/g, "")}
          >
            <Input
              disabled={id}
              maxLength={15}
              showCount
              placeholder="请输入内容"
            />
          </Form.Item>

          <Form.Item
            label="用户昵称"
            name="nickName"
            rules={[{ required: true, message: "请输入用户昵称!" }]}
            getValueFromEvent={(e) => e.target.value.replace(/\s+/g, "")}
          >
            <Input maxLength={8} showCount placeholder="请输入内容" />
          </Form.Item>

          <Form.Item
            label="用户角色"
            name="roleId"
            rules={[{ required: true, message: "请选择角色!" }]}
          >
            <Select placeholder="请选择" options={roleList} />
          </Form.Item>

          <Form.Item
            label="真实姓名"
            name="realName"
            rules={[{ required: true, message: "请输入真实姓名!" }]}
            getValueFromEvent={(e) => e.target.value.replace(/\s+/g, "")}
          >
            <Input maxLength={8} showCount placeholder="请输入内容" />
          </Form.Item>

          {id ? null : <div className="passTit">* 默认密码 123456</div>}

          {/* 确定和取消按钮 */}
          <br />
          <Form.Item wrapperCol={{ offset: 9, span: 16 }}>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
            &emsp;
            <Popconfirm
              title="放弃编辑后，信息将不会保存!"
              okText="放弃"
              cancelText="取消"
              onConfirm={closePage}
            >
              <Button>取消</Button>
            </Popconfirm>
          </Form.Item>
        </Form>
      </div>
    </Modal>
  );
}

const MemoUserAdd = React.memo(UserAdd);

export default MemoUserAdd;
