import { A4RolleAllType, AddRoleType } from "@/types";
import http from "@/utils/http";
import { AppDispatch } from "..";
/**
 * 获取角色表格列表数据
 */
export const getRoleListAPI = (data: any) => {
  return async (dispatch: AppDispatch) => {
    const res = await http.post("sys/role/listCountPage", data);
    if (res.code === 0) {
      const obj = {
        list: res.data.records,
        total: res.data.total,
      };

      dispatch({ type: "Role/getList", payload: obj });
    }
  };
};

/**
 * 删除角色
 */
export const roleRemoveAPI = (id: number) => {
  return http.get(`sys/role/remove/${id}`);
};

/**
 * 用户-是否显示
 */
// export const roleDisplayAPI = (id: number, display: number) => {
//   return http.get(`sys/role/editStatus/${id}/${display}`);
// };

/**
 * 新增或修改角色
 */
export const roleSaveAPI = (data: AddRoleType) => {
  return http.post("sys/role/save", data);
};

/**
 * 通过id获取角色详情
 */
export const getRoleInfoByIdAPI = (id: number) => {
  return http.get(`sys/role/detail/${id}`);
};

/**
 * 获取  用户  权限
 */
export const A4_APIgetRoleAll = () => {
  return async (dispatch: AppDispatch) => {
    const res = await http.get("sys/resource/getTreePermissions");

    if (res.code === 0) {
      // 数据扁平化处理，且过滤掉没有权限的数据
      const tempArr: A4RolleAllType[] = res.data;

      const arrRes: string[] = [];

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

      dispatch({ type: "A4RoleAll/getInfo", payload: arrRes });
    }
  };
};

/**
 * 获取角色内控文件权限列表
 */
export const A4_APIgetRoleFile = (id: number) => {
  return http.get(`sys/role/getRoleAttribute?roleId=${id}`);
};

/**
 * 功能授权
 */
export const A4_APIsave1 = (data: any) => {
  return http.post("sys/role/savePerm", data);
};

/**
 * 数据授权
 */
export const A4_APIsave2 = (data: any) => {
  return http.post("sys/role/saveDataScope", data);
};

/**
 * 内控文件授权
 */
export const A4_APIsave3 = (data: any) => {
  return http.post("sys/role/saveRoleAttribute", data);
};
