import { Button, Checkbox, Empty } from "antd";
import { useCallback, useEffect, useState } from "react";
import { forwardRef, useImperativeHandle } from "react";
import { A4_APIgetRoleFile } from "@/store/action/A4Role";
import { A4getRoleFileType } from "@/types";

type ArrAllType = {
  hasPerm: boolean;
  id: number;
  name: string;
};

type Props = {
  ref: any;
  mId: number;
};

function A4AuRR2({ mId }: Props, ref: any) {
  const [arrAll, setArrAll] = useState<ArrAllType[]>([]);

  const getInfoFu = useCallback(async (id: number) => {
    const res = await A4_APIgetRoleFile(id);
    if (res.code === 0) {
      const arr: A4getRoleFileType[] = res.data;

      // 所有
      setArrAll(arr);

      // 选中的 id 集合
      const arr1 = arr.filter((v) => v.hasPerm).map((v) => v.id);
      setCheckArr(arr1);
    }
  }, []);

  useEffect(() => {
    if (mId) getInfoFu(mId);
  }, [getInfoFu, mId]);

  const [checkArr, setCheckArr] = useState([] as number[]);

  const onChangeFu = useCallback(
    (val: boolean, id: number) => {
      if (val) setCheckArr([...checkArr, id]);
      else setCheckArr(checkArr.filter((v) => v !== id));
    },
    [checkArr]
  );

  // 给父组件调用
  const sonRes = useCallback(() => {
    let flag2 = true;
    if (checkArr.length <= 0) flag2 = false;
    return {
      flag2,
      txt2: checkArr,
    };
  }, [checkArr]);

  // 可以让父组件调用子组件的方法
  useImperativeHandle(ref, () => ({
    sonRes,
  }));

  return (
    <div className="A4AuRR2">
      <div className="A4ATit">
        内控文件权限 &emsp;{" "}
        {arrAll.length > 1 ? (
          <Button
            type="primary"
            onClick={() => setCheckArr(arrAll.map((v) => v.id))}
          >
            全选
          </Button>
        ) : null}
      </div>

      {arrAll.length ? (
        <div className="A4AR2Row">
          {arrAll.map((v) => (
            <Checkbox
              key={v.id}
              checked={checkArr.includes(v.id)}
              onChange={(e) => onChangeFu(e.target.checked, v.id)}
            >
              {v.name}
            </Checkbox>
          ))}
        </div>
      ) : (
        <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
      )}
    </div>
  );
}

export default forwardRef(A4AuRR2);
