import React, { useCallback, useEffect, useRef, useState } from "react";
import styles from "./index.module.scss";
import { A4RolleAllType } from "@/types";
import {
  A4_APIgetRoleAll,
  A4_APIsave1,
  A4_APIsave2,
  A4_APIsave3,
  getRoleInfoByIdAPI,
} from "@/store/action/A4Role";
import { Button, Checkbox, Popconfirm, Tooltip } from "antd";
import { MessageFu } from "@/utils/message";
import { A4getStorage, A4setStorage } from "@/utils/storage";
import A4AuRR from "./A4AuRR";
import A4AuRR2 from "./A4AuRR2";
import { useDispatch } from "react-redux";

type Props = {
  mId: number;
  authColseFu: () => void;
  authEditFu: () => void;
};

function A4Auth({ mId, authColseFu, authEditFu }: Props) {
  const dispatch = useDispatch();

  // 传递给子组件的数据权限信息
  const [infoData, setInfoData] = useState(
    {} as {
      dataScope: 1 | 2 | 3;
      scopeDept: string;
    }
  );

  const [arr1, setArr1] = useState([] as A4RolleAllType[]);

  const getInfo1Fu = useCallback(async (id: number) => {
    const res = await getRoleInfoByIdAPI(id);
    if (res.code === 0) {
      setArr1(res.data.permission);

      // 数据权限的回显
      const temp = res.data.role;
      setInfoData({
        dataScope: temp.dataScope,
        scopeDept: temp.scopeDept,
      });
    }
  }, []);

  useEffect(() => {
    if (mId) {
      // 获取角色 功能权限 信息
      getInfo1Fu(mId);
    }
  }, [getInfo1Fu, mId]);

  // 多选框的变化
  const onChange1Fu = useCallback(
    (val: boolean, ind: number, id: string) => {
      const arr = [...arr1];

      if (ind === 1) {
        if (!val && arr.filter((v) => v.authority).length <= 1)
          return MessageFu.warning("至少勾选一个 功能权限 的页面模块!");

        if (!val && id === "1000") setIsTit(false);

        // 第一级的选中
        setArr1(
          arr.map((v) => ({
            ...v,
            authority: v.id === id ? val : v.authority,
          }))
        );
      } else if (ind === 2) {
        if (val) {
          if (id === "1010" || id === "1020") setIsTit(false);
        }

        // 第二级的选中
        setArr1(
          arr.map((v) => ({
            ...v,
            children: v.children?.map((v2) => ({
              ...v2,
              authority: v2.id === id ? val : v2.authority,
            })),
          }))
        );
      } else if (ind === 3) {
        // 第三级的选中
        setArr1(
          arr.map((v) => ({
            ...v,
            children: v.children?.map((v2) => ({
              ...v2,
              children: v2.children?.map((v3) => ({
                ...v3,
                authority: v3.id === id ? val : v3.authority,
              })),
            })),
          }))
        );
      }
    },
    [arr1]
  );

  // 点击复制权限配置
  const copyRoleFu = useCallback(() => {
    A4setStorage(arr1);
    MessageFu.success("复制数据到本地成功!");
  }, [arr1]);

  // 点击应用权限配置
  const setArr1Fu = useCallback(() => {
    const arr = A4getStorage();
    if (arr && arr.length) {
      setArr1(arr);
    } else MessageFu.warning("本地还没有关于功能权限的配置!");
  }, []);

  // 数据权限 组件 的 ref
  const r2Ref = useRef<any>(null);

  // 内控文件权限 组件 的 ref
  const r3Ref = useRef<any>(null);

  // 项目文件视图和内控文件视图 必须选中一个

  // 点击确定
  const btnOkFu = useCallback(async () => {
    if (arr1.filter((v) => v.authority).length <= 0)
      return MessageFu.warning("至少勾选一个 功能权限 的页面模块!");

    // 数据权限的信息
    const { flag, txt, value } = r2Ref.current.sonRes();
    if (!flag) return MessageFu.warning("至少勾选一个 数据权限 的跨部门数据!");

    // if(1+1===2) {
    //   console.log('----------',{ flag, txt, value });

    //   return
    // }

    const { flag2, txt2 } = r3Ref.current.sonRes();
    console.log(flag2);

    // if (!flag2) return MessageFu.warning("至少勾选一个 内控文件权限 模块!");

    // 处理功能权限
    const tempArr: string[] = [];

    arr1.forEach((v1) => {
      if (v1.authority) {
        tempArr.push(v1.id);
        if (v1.children && v1.children.length) {
          v1.children.forEach((v2) => {
            if (v2.authority) {
              tempArr.push(v2.id);
              if (v2.children && v2.children.length) {
                v2.children.forEach((v3) => {
                  if (v3.authority) tempArr.push(v3.id);
                });
              }
            }
          });
        }
      }
    });

    if (tempArr) {
      // 勾选了 项目管理 页面权限
      if (tempArr.includes("1000")) {
        if (!tempArr.includes("1010") && !tempArr.includes("1020")) {
          setIsTit(true);
          return;
        }
      }
    }

    const obj1 = {
      id: mId,
      dataScope: value,
      scopeDept: txt,
    };

    const res1 = await A4_APIsave2(obj1);

    if (res1.code === 0) {
      const obj2 = {
        roleId: mId,
        attrId: txt2,
      };

      const res2 = await A4_APIsave3(obj2);
      if (res2.code === 0) {
        const obj3 = {
          resources: tempArr,
          roleId: mId,
        };

        const res3 = await A4_APIsave1(obj3);

        if (res3.code === 0) {
          MessageFu.success("授权成功!");
          authEditFu();
          authColseFu();

          // 实时更新 权限 信息,用于控制页面和按钮
          dispatch(A4_APIgetRoleAll());
        }
      }
    }
  }, [arr1, authColseFu, authEditFu, dispatch, mId]);

  // 项目文件视图/内控文件视图 至少勾选一个
  const [isTit, setIsTit] = useState(false);

  return (
    <div className={styles.A4Auth}>
      <div className="A4AMain">
        <div className="A4AMainLL">
          <div className="A4ATit">功能权限</div>
          <div className="A4A1Btn">
            <Button
              type="primary"
              size="small"
              disabled={arr1.filter((v) => v.authority).length <= 0}
              onClick={copyRoleFu}
            >
              复制权限配置
            </Button>
            &emsp;
            <Button type="primary" size="small" onClick={setArr1Fu}>
              应用权限配置
            </Button>
            <div className="A4AMainTit" hidden={!isTit}>
              项目文件视图/内控文件视图 至少勾选一个
            </div>
          </div>
          <div className="A4A1Cen">
            {arr1.map((v1) => (
              <div className="A4A1CenRow" key={v1.id}>
                <div className="A4A1CenRow1">
                  <Checkbox
                    checked={v1.authority}
                    onChange={(e) => onChange1Fu(e.target.checked, 1, v1.id)}
                  >
                    {v1.name}
                  </Checkbox>

                  {v1.children && v1.children.length
                    ? v1.children.map((v2) => (
                        <div className="A4A1CenRow2" key={v2.id}>
                          <>
                            <Checkbox
                              disabled={!v1.authority}
                              checked={v2.authority}
                              onChange={(e) =>
                                onChange1Fu(e.target.checked, 2, v2.id)
                              }
                            >
                              {v2.name}
                            </Checkbox>
                            {v2.description ? (
                              <>
                                <Tooltip title={v2.description}>
                                  <div className="iconHoverTitTxt">?</div>
                                </Tooltip>
                              </>
                            ) : null}
                          </>
                          {v2.children && v2.children.length ? (
                            <div className="A4A1CenRow3Box">
                              {v2.children.map((v3) => (
                                <div className="A4A1CenRow3" key={v3.id}>
                                  <Checkbox
                                    disabled={!v2.authority || !v1.authority}
                                    checked={v3.authority}
                                    onChange={(e) =>
                                      onChange1Fu(e.target.checked, 3, v3.id)
                                    }
                                  >
                                    {v3.name}
                                  </Checkbox>
                                  {v3.description ? (
                                    <>
                                      <Tooltip title={v3.description}>
                                        <div className="iconHoverTitTxt">?</div>
                                      </Tooltip>
                                      &emsp;
                                    </>
                                  ) : null}
                                </div>
                              ))}
                            </div>
                          ) : null}
                        </div>
                      ))
                    : null}
                </div>
              </div>
            ))}
          </div>
        </div>
        {/* 右侧的 数据权限 和 内控文件权限*/}
        <div className="A4AMainRR">
          <A4AuRR ref={r2Ref} info={infoData} />
          <br />
          <A4AuRR2 ref={r3Ref} mId={mId} />
        </div>
      </div>

      <div className="A4AcliBtn">
        <Popconfirm
          title="放弃编辑后，信息将不会保存!"
          okText="放弃"
          cancelText="取消"
          onConfirm={authColseFu}
          okButtonProps={{ loading: false }}
        >
          <Button>取消</Button>
        </Popconfirm>
        &emsp;&emsp;
        <Button type="primary" onClick={btnOkFu}>
          确定
        </Button>
      </div>
    </div>
  );
}

const MemoA4Auth = React.memo(A4Auth);

export default MemoA4Auth;
