import { RootState } from "@/store";
import { getUserInfoByIdAPI, userSaveAPI } from "@/store/action/A3User";
import { SaveUserType } from "@/types";
import { MessageFu } from "@/utils/message";
import {
  Button,
  Cascader,
  Form,
  FormInstance,
  Input,
  Modal,
  Popconfirm,
  Select,
} from "antd";
import React, { useCallback, useEffect, useRef, useState } from "react";
import { useSelector } from "react-redux";
import styles from "./index.module.scss";
import lastIdresArrFu from "./dataRes";

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

function UserAdd({ id, closePage, upTableList, addTableList }: Props) {
  // 从仓库获取角色下拉列表信息
  const roleList = useSelector((state: RootState) => state.A3User.roleList);

  // 从仓库获取部门 级联 信息
  const deptList = useSelector((state: RootState) => state.A5Section.tableList);

  // 设置表单初始数据（区分编辑和新增）
  const FormBoxRef = useRef<FormInstance>(null);

  // 回显 级联 信息
  const idresArr = useCallback(
    (deptId: string) => {
      const arr = lastIdresArrFu(deptId, deptList);
      return arr;
    },
    [deptList]
  );

  const getInfoInAPIFu = useCallback(
    async (id: number) => {
      const res = await getUserInfoByIdAPI(id);

      if (res.code === 0) {
        FormBoxRef.current?.setFieldsValue({
          ...res.data,
          deptId: idresArr(res.data.deptId + ""),
        });
      }
    },
    [idresArr]
  );

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

  // 密码提示
  const [passFlag, setPassFlag] = useState("");

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

  // 通过校验点击确定
  const onFinish = useCallback(
    async (values: any) => {
      const obj: SaveUserType = {
        ...values,
        deptId: values.deptId[values.deptId.length - 1],
        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={styles.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: "请输入用户名!" },
              {
                validator: (_: any, value: any) => {
                  if (value) {
                    const reg = new RegExp(/^[a-zA-Z0-9_]{6,15}$/);
                    const flag = reg.test(value);
                    if (flag) {
                      setPassFlag(value);
                      return Promise.resolve(value);
                    } else {
                      setPassFlag("");
                      return Promise.reject(
                        "用户名只包含字母、数字和下划线，最少 6 个字符!"
                      );
                    }
                  } else {
                    setPassFlag("");
                    return Promise.resolve(value);
                  }
                },
              },
            ]}
            getValueFromEvent={(e) => e.target.value.replace(/\s+/g, "")}
          >
            <Input
              style={{ width: 400 }}
              disabled={id}
              maxLength={15}
              showCount
              placeholder="请输入内容，6-15字；不能重复"
            />
          </Form.Item>

          <div className="e_row" hidden={id}>
            <div className="e_rowL">
              <span> </span>初始密码：
            </div>
            <div className="e_rowR">
              {passFlag ? `${passFlag}4dage` : "请先输入合法用户名"}
            </div>
          </div>

          <Form.Item
            label="手机号"
            name="phone"
            rules={[
              { required: true, message: "请输入手机号!" },
              // { max: 11, min: 11, message: "长度为11!" },
              {
                pattern: /^1[3-9][0-9]{9}$/,
                message: "请输入正确格式的手机号!",
              },
            ]}
            getValueFromEvent={(e) => e.target.value.replace(/\s+/g, "")}
          >
            <Input
              style={{ width: 400 }}
              maxLength={11}
              showCount
              placeholder="请输入11位手机号"
            />
          </Form.Item>

          <Form.Item
            label="所属部门"
            name="deptId"
            rules={[{ required: true, message: "请选择部门!" }]}
          >
            <Cascader
              style={{ width: 400 }}
              options={deptList}
              fieldNames={{ label: "name", value: "id" }}
              placeholder="请选择"
            />
          </Form.Item>

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

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

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

const MemoUserAdd = React.memo(UserAdd);

export default MemoUserAdd;
