import { RootState } from "@/store";
import {
  addUserAPI,
  getUserInfoAPI,
  userGetRoleAPI,
} from "@/store/action/system";
import { MessageFu } from "@/utils/message";
import { Button, Input, Modal, Select } from "antd";
import React, { useCallback, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";

type Props = {
  id: any;
  closeFu: any;
  btnOkSuccFu: any;
};

function UserModal({ id, closeFu, btnOkSuccFu }: Props) {
  const dispatch = useDispatch();

  // 从仓库中获取所有角色下拉
  const options = useSelector(
    (state: RootState) => state.systemStore.roleSelect
  );
  // 获取所有角色下拉信息存到仓库
  useEffect(() => {
    dispatch(userGetRoleAPI());
  }, [dispatch]);

  // 用户详情信息
  const [userInfo, setUserInfo] = useState<any>({});

  const getUserInfoAPIFu = useCallback(async (id: number) => {
    const res = await getUserInfoAPI(id);
    setUserInfo(res.data);
    setRoleId(res.data.roleId);
    setUserName(res.data.userName);
    setPhone(res.data.phone);
    setRealName(res.data.realName);
  }, []);

  useEffect(() => {
    if (id) getUserInfoAPIFu(id); // 是编辑
  }, [getUserInfoAPIFu, id]);

  useEffect(() => {
    if (id) {
      // 是编辑
    } else {
      // 是新增
      setRoleId(options[0] && options[0].id ? options[0].id : "");
    }
  }, [id, options]);

  // 角色
  const [roleId, setRoleId] = useState();

  // 账号
  const [userName, setUserName] = useState("");

  // 手机号码
  const [phone, setPhone] = useState("");
  // 真实姓名
  const [realName, setRealName] = useState("");

  // 点击提交
  const btnOkFu = useCallback(async () => {
    if (userName.length <= 4) return MessageFu.warning("用户账号长度为4-15位!");
    var reg: any = new RegExp(/^1[3-9]\d{9}$/);
    if (!reg.test(phone)) return MessageFu.warning("请输入正确格式的手机号!");
    if (realName === "") return MessageFu.warning("真实姓名不能为空!");
    const obj = {
      ...userInfo,
      phone,
      realName,
      userName,
      roleId,
    };
    const res: any = await addUserAPI(obj);
    if (res.code === 0) {
      MessageFu.success("操作成功!");
      btnOkSuccFu();
    }
  }, [btnOkSuccFu, phone, realName, roleId, userInfo, userName]);

  return (
    <>
      <Modal
        wrapClassName="systemUser"
        destroyOnClose
        open={true}
        title={id ? "编辑用户" : "新增用户"}
        onCancel={closeFu}
        footer={
          [] // 设置footer为空，去掉 取消 确定默认按钮
        }
      >
        <div className="systemTit">
          <div className="systemTitRow">
            <div className="bs">*</div>
            <div className="lable">用户账号：</div>
            <Input
              disabled={id}
              maxLength={15}
              showCount
              style={{ width: 600 }}
              placeholder="请输入"
              value={userName}
              onChange={(e) => setUserName(e.target.value.trim())}
            />
          </div>
          <div className="systemTitRow">
            <div className="bs">*</div>
            <div className="lable">用户角色：</div>
            <Select
              value={roleId}
              onChange={(val) => setRoleId(val)}
              style={{ width: 600 }}
              options={options.map((v: any) => ({
                label: v.roleName,
                value: v.id,
              }))}
            />
          </div>
          <div className="systemTitRow">
            <div className="bs">*</div>
            <div className="lable">手机号码：</div>
            <Input
              maxLength={11}
              showCount
              style={{ width: 600 }}
              placeholder="请输入"
              value={phone}
              onChange={(e) => setPhone(e.target.value.trim())}
            />
          </div>
          <div className="systemTitRow">
            <div className="bs">*</div>
            <div className="lable">真实姓名：</div>
            <Input
              maxLength={8}
              showCount
              style={{ width: 600 }}
              placeholder="请输入"
              value={realName}
              onChange={(e) => setRealName(e.target.value.trim())}
            />
          </div>
          {id ? null : (
            <div className="systemTitRow">
              <div className="systemTitRowTit">* 默认密码 123456</div>
            </div>
          )}

          <br />
          <div className="systemTitBtn">
            <Button type="primary" onClick={btnOkFu}>
              提交
            </Button>
            &emsp;
            <Button onClick={closeFu}>取消</Button>
          </div>
        </div>
      </Modal>
    </>
  );
}

const MemoUserModal = React.memo(UserModal);

export default MemoUserModal;
