import React, { useCallback, useEffect, useMemo, useState } from "react";
import styles from "./index.module.scss";
import { Button, Checkbox, Modal } from "antd";
import MyPopconfirm from "@/components/MyPopconfirm";
import { Z1_APIgetAuthByUserId, Z1_APIsetAuth } from "@/store/action/Z1user";
import classNmaes from "classnames";
import { MessageFu } from "@/utils/message";

export type UserListType = {
  id: number;
  name: string;
  children: {
    id: number;
    name: string;
    authority: boolean;
  }[];
};

type Props = {
  authInfo: { id: number; name: string };
  closeFu: () => void;
};

function Z1auth({ authInfo, closeFu }: Props) {
  const getAuthByUserIdFu = useCallback(async () => {
    const res = await Z1_APIgetAuthByUserId(authInfo.id);
    if (res.code === 0) setList(res.data);
  }, [authInfo.id]);

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

  const [list, setList] = useState<UserListType[]>([]);

  // 多选框变化
  const onChange = useCallback(
    (val: boolean, id1: number, id2: number) => {
      setList(
        list.map((v) => ({
          ...v,
          children:
            v.id === id1
              ? v.children.map((c) => ({
                  ...c,
                  authority: c.id === id2 ? val : c.authority,
                }))
              : v.children,
        }))
      );
    },
    [list]
  );

  // 二级选中的数组id集合
  const checkIds = useMemo(() => {
    const arr: number[] = [];
    list.forEach((v) => {
      v.children.forEach((c) => {
        if (c.authority) arr.push(c.id);
      });
    });
    return arr;
  }, [list]);

  // 点击确定
  const btnOkFu = useCallback(async () => {
    const obj = {
      userId: authInfo.id,
      resources: checkIds,
    };

    const res = await Z1_APIsetAuth(obj);

    if (res.code === 0) {
      MessageFu.success("授权成功!");
      closeFu();
    }
  }, [authInfo.id, checkIds, closeFu]);

  return (
    <Modal
      wrapClassName={styles.Z1auth}
      open={true}
      title={`${authInfo.name} - 权限管理`}
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className="Z1aEmain">
        {list.map((v) => (
          <div key={v.id} className="Z1aRow">
            <div className="Z1aRow1">{v.name}</div>
            <div className="Z1aRow2">
              {v.children.map((c) => (
                <Checkbox
                  key={c.id}
                  checked={c.authority}
                  onChange={(e) => onChange(e.target.checked, v.id, c.id)}
                >
                  {c.name}
                </Checkbox>
              ))}
            </div>
          </div>
        ))}

        <div
          className={classNmaes(
            "Z1aErr",
            checkIds.length <= 0 ? "Z1aErrAc" : ""
          )}
        >
          至少选中一个
        </div>

        <div className="Z1aEbtn">
          <Button
            type="primary"
            onClick={btnOkFu}
            disabled={checkIds.length <= 0}
          >
            提交
          </Button>
          &emsp;
          <MyPopconfirm txtK="取消" onConfirm={closeFu} />
        </div>
      </div>
    </Modal>
  );
}

const MemoZ1auth = React.memo(Z1auth);

export default MemoZ1auth;
