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 = {
  authority: boolean;
  id: number;
  name: string;
  resourceType: string;
};

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, id: number) => {
      setList(
        list.map((v) => ({
          ...v,
          authority: v.id === id ? val : v.authority,
        }))
      );
    },
    [list]
  );

  // 至少选中一个
  const isOneRes = useMemo(() => {
    return list.filter((v) => v.authority).length <= 0;
  }, [list]);

  // 点击确定
  const btnOkFu = useCallback(async () => {
    const obj = {
      userId: authInfo.id,
      resources: list.filter((c) => c.authority).map((v) => v.id),
    };

    const res = await Z1_APIsetAuth(obj);

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

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

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

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

const MemoZ1auth = React.memo(Z1auth);

export default MemoZ1auth;
