<script setup lang="ts">
defineOptions({
  // name 作为一种规范最好必须写上并且和路由的name保持一致
  name: "rolePower"
});
import { ref, reactive, watch, onMounted } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import addRole from "./components/addRole.vue";
import addPerson from "./components/addPerson.vue";
import { getDeleteUserApi, postAssignmentUserApi } from "@/api/userSetting";
import {
  getMenuList,
  getMenuListCodeForRole,
  postAddMenuList,
  updateMenu
} from "@/api/menu";
import {
  postPageRole,
  postDelRole,
  postPageUserByRole,
  postUpdateRole,
  getUserPermissionsByRoleCode
} from "@/api/roles";
import pngcaret from "@/assets/icon-png/caret-right-small.svg";
import UserPageTable from "@/components/UserPageTable/index.vue";
const UserTable = ref();
// 新增角色
const addRoleRef = ref();
const addRoleShow = ref(false);
// 新增角色组人员
const addPersonRef = ref();
const addPersonShow = ref(false);
const tableData = ref([]);
interface Role {
  id?: number;
  roleName: string;
  records: Array<string>;
}
interface ApiResponse {
  code: number;
  data: {
    records: Role[];
    // 可能还有其他字段，比如 total, page, etc.
  };
}
const rolesList = reactive<any>({
  data: [],
  dataUser: [],
  rolesName: "",
  addPerson: {}
});
// 角色列表
let pageSize = reactive({
  pageNumber: 1,
  pageSize: 10
});
let pageSizeRoles = reactive({
  pageNumber: 1,
  pageSize: 10
});
const load = () => {
  console.log("load");
  pageSizeRoles.pageSize += 5;
  postPageRoleApi();
};
const loadSystem = async () => {
  pageSize.pageSize += 5;
  await postPageRoleApi();
};

// 系统角色
const postPageRoleApi = async () => {
  const { code, data }: ApiResponse = await postPageRole({
    ...pageSize,
    roleType: "system"
  });
  const res: ApiResponse = await postPageRole({
    ...pageSizeRoles,
    roleType: "user"
  });
  if (code === 200) {
    rolesList.data = [];
    data.records.map((item, index) => {
      rolesList.data.push({ ...item, id: index + 2 });
    });
  }
  if (res.code === 200) {
    rolesList.dataUser = [];
    res.data.records.map((item, index) => {
      rolesList.dataUser.push({ ...item, id: index + 3 });
    });
  }
};
// 自定义角色
// 查看角色组
const bgColor = ref(null);
onMounted(async () => {
  // 用来手动调用接口新增权限
  // updateMenu({
  //   menuName: "批量导入",
  //   menuType: "button",
  //   parentCode: "menu381258724305674240",
  //   orderNum: 2,
  //   url: "",
  //   moduleUrl: "/indexData/index",
  //   icon: "",
  //   remar: "",
  //   menuCode: "button381259601502412800"
  // });
  // 低网模式 等待 postPageRoleApi 完成
  await postPageRoleApi();
  // setTimeout(() => {
  //   formLink.targetCodes = [];
  //     console.log("123测试的撒大",rolesList.data[0])
  //   formLink.targetCodes.push(rolesList.data[0]?.roleCode);
  //   bgColor.value = rolesList.data[0]?.roleCode;
  //   paramsPageUser.roleName = rolesList.data[0]?.roleName;
  //   paramsPageUser.roleCode = rolesList.data[0]?.roleCode;
  //   rolesList.rolesName = rolesList.data[0]?.roleName;
  //   Object.assign(rolesList.addPerson, rolesList.data[0]);
  //   getMenuListApi();
  //   postPageUserByRoleApi();
  //   getUserPermissionsByRoleCodeApi(rolesList.data[0]?.roleCode);
  //   getMenuListCodeForRoleApi(rolesList.data[0]);
  // }, 500);
  if (rolesList.data.length > 0) {
    const firstRole = rolesList.data[0];
    formLink.targetCodes = [];
    formLink.targetCodes.push(firstRole.roleCode);
    bgColor.value = firstRole.roleCode;
    paramsPageUser.roleName = firstRole.roleName;
    paramsPageUser.roleCode = firstRole.roleCode;
    rolesList.rolesName = firstRole.roleName;
    Object.assign(rolesList.addPerson, firstRole);

    await Promise.all([
      getMenuListApi(),
      postPageUserByRoleApi(),
      getUserPermissionsByRoleCodeApi(firstRole.roleCode),
      getMenuListCodeForRoleApi(firstRole)
    ]);
  }
});
const lookRoles = item => {
  paramsPageUser.roleName = item.roleName;
  paramsPageUser.roleCode = item.roleCode;
  bgColor.value = item.roleCode;
  rolesList.rolesName = item.roleName;
  // 取消关联
  formLink.targetCodes = [];
  formLink.targetCodes.push(item.roleCode);
  Object.assign(rolesList.addPerson, item);
  getMenuListApi();
  postPageUserByRoleApi();
  getUserPermissionsByRoleCodeApi(item.roleCode);
  setTimeout(() => {
    // 查看角色权限
    getMenuListCodeForRoleApi(item);
  }, 500);
  Object.assign(roleParams, {
    roleName: "",
    roleSort: 0,
    menuCodes: [],
    roleCode: "",
    remark: ""
  });
};
// 添加角色
const addRoles = () => {
  addRoleRef.value.open();
  addRoleShow.value = true;
};
// 编辑角色
const editRoleName = item => {
  addRoleRef.value.open(item);
  addRoleShow.value = true;
};
// 删除角色
const postDelRoleApi = async item => {
  const { code, msg } = await postDelRole(item);
  if (code === 200) {
    ElMessage({
      message: "删除成功",
      type: "success"
    });
    postPageRoleApi();
    setTimeout(() => {
      formLink.targetCodes = [];
      formLink.targetCodes.push(rolesList.data[0]?.roleCode);
      bgColor.value = rolesList.data[0]?.roleCode;
      paramsPageUser.roleName = rolesList.data[0]?.roleName;
      paramsPageUser.roleCode = rolesList.data[0]?.roleCode;
      rolesList.rolesName = rolesList.data[0]?.roleName;
      Object.assign(rolesList.addPerson, rolesList.data[0]);
      getMenuListApi();
      postPageUserByRoleApi();
      getUserPermissionsByRoleCodeApi(rolesList.data[0]?.roleCode);
      getMenuListCodeForRoleApi(rolesList.data[0]);
    }, 500);
  } else {
    ElMessage.error(msg);
  }
};
const deleteRole = item => {
  ElMessageBox.confirm(
    `角色删除后不能恢复,是否确认删除角色【${item.roleName}】吗?`,
    "确认删除角色吗",
    {
      type: "warning"
    }
  )
    .then(() => {
      postDelRoleApi(item);
    })
    .catch(() => {
      // catch error
      ElMessage({
        message: "已取消"
      });
    });
};
// 标签选择
const activeName = ref("first");
const formLink = reactive({
  sourceCodes: [],
  targetCodes: [],
  linkAction: "unlink",
  correlatedModel: "userRole"
});
// 添加角色组人员
const AddRolesPerson = () => {
  formLink.sourceCodes = [];
  if (rolesList.rolesName) {
    addPersonRef.value.open(rolesList.addPerson);
    addPersonShow.value = true;
  } else {
    ElMessage.warning("请先选择角色");
  }
};
// 删除角色组人员
const deltetePerson = item => {
  formLink.sourceCodes = [];
  ElMessageBox.confirm(
    `是否确认移除【${item.realName}】吗?`,
    "确认移除人员吗",
    {
      type: "warning"
    }
  )
    .then(() => {
      // getDeleteUserApi(item.userCode, postPageUserByRoleApi);
      formLink.sourceCodes.push(item.userCode);
      postAssignmentUserApi(formLink, postPageUserByRoleApi);
    })
    .catch(() => {
      // catch error
      ElMessage({
        message: "已取消"
      });
    });
};
// 人员管理
const paramsPageUser = reactive({
  pageNumber: 1,
  pageSize: 10,
  roleName: "",
  roleCode: "",
  realName: "",
  userCodes: []
});
const total = ref(0);
const postPageUserByRoleApi = async () => {
  const { code, data } = await postPageUserByRole(paramsPageUser);
  if (code === 200) {
    tableData.value = data.records;
    total.value = data?.totalRow;
  }
};
// 菜单权限
const handleClick = (tab, event) => {
  console.log(tab, event);
};
// 查询角色的权限
// 递归处理菜单回显判断并更新 show 和 allShow
function updateMenuShow(menuList, data) {
  menuList.forEach(menu => {
    // 判断当前菜单的 menuCode 是否在 data 中
    if (data.includes(menu.menuCode)) {
      menu.show = true;
    }

    // 如果有子菜单，递归检查
    if (menu.childrenRes && menu.childrenRes.length > 0) {
      updateMenuShow(menu.childrenRes, data);

      // 检查所有子菜单的 show 属性是否都为 true
      const allChildrenShow = menu.childrenRes.every(
        child => child.show === true
      );
      if (allChildrenShow) {
        menu.allShow = true;
        menu.show = true;
      }
    }
  });
}

const getMenuListCodeForRoleApi = async item => {
  const { code, data } = await getMenuListCodeForRole({
    roleCode: item.roleCode
  });
  if (code == 200) {
    roleParams.menuCodes = data;
    updateMenuShow(menuListRoleList.value, data);
  }
};
// 分页----------------
const handleSizeChange = val => {
  paramsPageUser.pageSize = val;
  postPageUserByRoleApi();
};
const handleCurrentChange = val => {
  paramsPageUser.pageNumber = val;
  postPageUserByRoleApi();
};
// ------------------------
// 查看角色菜单权限表
const menuListRole = ref<any>([]);
const menuListRoleList = ref<any>([]);
function addShowProperty(menuArray) {
  menuArray.forEach(menu => {
    menu.show = false; // 添加 show 属性
    if (menu.childrenRes) {
      addShowProperty(menu.childrenRes); // 递归处理子菜单
    }
  });
  return menuArray; // 返回修改后的菜单数组
}

const getMenuListApi = async () => {
  const { code, data } = await getMenuList();
  if (code === 200) {
    let menuData = data;
    let modifiedMenuData = addShowProperty(menuData);
    modifiedMenuData.forEach(item => {
      item.allShow = false;
    });
    // 忘记干嘛的了，递归错数据了
    function checkMenuCodes(menuItems) {
      menuListRole.value.forEach(item => {
        const hasRole = menuListRole.value.includes(item.menuCode);
        item.show = hasRole;

        // Recursively check children
        if (item.childrenRes && item.childrenRes.length > 0) {
          checkMenuCodes(item.childrenRes);
        }

        // Check if all required roles are present
        if (item.childrenRes) {
          const allShow = item.childrenRes.every(child => child.show);
          if (allShow && item.menuCode === item.parentCode) {
            item.allShow = true; // Only set allShow for the top-level menus
          }
        }
      });
    }
    // checkMenuCodes(modifiedMenuData);
    // -------------------------------------
    menuListRoleList.value = modifiedMenuData;
    console.log("21312", menuListRoleList.value);
  }
};
const getUserPermissionsByRoleCodeApi = async roleCode => {
  const { code, msg, data } = await getUserPermissionsByRoleCode({
    roleCode
  });
  if (code == 200) {
    menuListRole.value = data;
  }
};
const roleParams = reactive({
  roleName: "",
  roleSort: 0,
  menuCodes: [],
  roleCode: "",
  remark: ""
});
const postUpdateRoleApi = async () => {
  const { code, msg, data } = await postUpdateRole(roleParams);
  if (code == 200) {
    getUserPermissionsByRoleCodeApi(roleParams.roleCode);
    ElMessage.success("修改成功");
  } else {
    ElMessage.error(msg);
  }
};
// 添加菜单code
function collectMenuCodes(menu) {
  // 添加当前菜单的 menuCode 到 roleParams.menuCodes
  roleParams.menuCodes.push(menu.menuCode);
  menu.show = true;
  // 如果有子菜单，递归处理
  if (menu.childrenRes && menu.childrenRes.length > 0) {
    menu.childrenRes.forEach(child => {
      collectMenuCodes(child);
    });
  }
}
// function collectMenuShow(menu, allShow) {
//   // 添加当前菜单的 menuCode 到 roleParams.menuCodes
//   if (!allShow) {
//     menu.show = true;
//   } else {
//     menu.show = false;
//   }
//   // 如果有子菜单，递归处理
//   if (menu.childrenRes && menu.childrenRes.length > 0) {
//     menu.childrenRes.forEach(child => {
//       collectMenuCodes(child);
//     });
//   }
// }
function collectMenuShow(data, allShow) {
  // 遍历 data 数组
  data.forEach(item => {
    // 设置当前项的 show 和 allShow 属性
    if (!allShow) {
      item.show = true;
      roleParams.menuCodes.push(item.menuCode);
    } else {
      item.show = false;
      data.map(itCode => {
        data.map(itCode => {
          // 使用 filter 来过滤掉与 itCode.menuCode 相同的元素
          roleParams.menuCodes = roleParams.menuCodes.filter(
            j => j !== itCode.menuCode
          );
        });
      });
      // roleParams.menuCodes = []
    }
    // 如果存在子菜单 (childrenRes)，则递归调用
    if (item.childrenRes && item.childrenRes.length > 0) {
      collectMenuShow(item.childrenRes, allShow);
    }
  });
}
const roleShowClick = (item, type: any) => {
  roleParams.roleName = rolesList.addPerson.roleName;
  roleParams.roleCode = rolesList.addPerson.roleCode;
  if (type) {
    // 不是全选
    if (item.show) {
      item.show = false;
      menuListRoleList.value.map = row => {
        if (row.menuCode == it.parentCode) {
          row.allShow = !row.allShow;
        }
      };
      roleParams.menuCodes.filter(it => it !== it.menuCode);
      postUpdateRoleApi();
    } else {
      item.show = true;
      roleParams.menuCodes.push(item.menuCode);
      postUpdateRoleApi();
    }
  } else {
    if (!item.allShow) {
      collectMenuShow([item], item.allShow);
      postUpdateRoleApi();
    } else {
      collectMenuShow([item], item.allShow);
      postUpdateRoleApi();
    }
  }
};
</script>

<template>
  <div class="flex w-full h-full">
    <!-- 新增角色 -->
    <addRole
      ref="addRoleRef"
      v-model="addRoleShow"
      @handleClick="postPageRoleApi"
    />
    <!-- 新增角色组人员 -->
    <addPerson
      ref="addPersonRef"
      v-model="addPersonShow"
      @handeClick="postPageUserByRoleApi"
    />
    <!-- 主体内容 -->
    <div class="box-left">
      <div class="w-[100%]">
        <div><el-text type="info">系统角色</el-text></div>
      </div>
      <div
        v-infinite-scroll="loadSystem"
        :infinite-scroll-immediate="false"
        class="h-1/4 w-[100%] overflow-auto infinite-list"
      >
        <div
          v-for="(item, index) in rolesList.data"
          :key="index"
          class="w-[100%] flex justify-between items-center roles-text"
        >
          <pngcaret class="mr-1 mt-2" />
          <div
            :class="[
              'w-[100%] flex justify-between items-center mt-2 cursor-pointer',
              { 'roles-bg': bgColor === item.roleCode }
            ]"
          >
            <div
              class="flex justify-between items-center"
              @click="lookRoles(item)"
            >
              <span class="">{{ item.roleName }}</span>
            </div>
            <div class="flex justify-between items-center">
              <el-dropdown trigger="click">
                <span>
                  <el-icon>
                    <Operation />
                  </el-icon>
                </span>
                <template #dropdown>
                  <div class="menu-bg">
                    <el-dropdown-menu class="setting">
                      <el-dropdown-item>
                        <el-link type="info">编辑名称</el-link>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <el-link type="info">删除</el-link>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </div>
                </template>
              </el-dropdown>
            </div>
          </div>
        </div>
      </div>
      <el-divider />
      <div class="w-[100%]">
        <div><el-text type="info">自定义角色</el-text></div>
      </div>
      <div
        v-infinite-scroll="load"
        :infinite-scroll-immediate="false"
        class="h-2/5 w-[100%] overflow-auto infinite-list"
      >
        <div
          v-for="(item, index) in rolesList.dataUser"
          :key="index"
          class="w-[100%] flex justify-between items-center roles-text"
        >
          <pngcaret class="mr-1 mt-2" />
          <div
            :class="[
              'w-[100%] flex justify-between items-center mt-2 cursor-pointer',
              { 'roles-bg': bgColor === item.roleCode }
            ]"
          >
            <div
              class="flex justify-between items-center"
              @click="lookRoles(item)"
            >
              <span class="">{{ item.roleName }}</span>
            </div>
            <div class="flex justify-between items-center">
              <el-dropdown trigger="click">
                <span>
                  <el-icon>
                    <Operation />
                  </el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu class="setting">
                    <Auth :value="['编辑角色']">
                      <el-dropdown-item @click="editRoleName(item)">
                        编辑名称
                      </el-dropdown-item>
                    </Auth>
                    <Auth :value="['删除']">
                      <el-dropdown-item @click="deleteRole(item)">
                        <el-link type="danger">删除</el-link>
                      </el-dropdown-item>
                    </Auth>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </div>
      </div>
      <el-divider />
      <Auth :value="['新建角色']">
        <el-button type="primary" class="addRole" plain @click="addRoles()"
          >新增角色</el-button
        >
      </Auth>
    </div>
    <!-- <div v-if="rolesList.rolesName" class="box-right"> -->
    <div class="box-right">
      <h3>{{ rolesList.rolesName }}</h3>
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="人员管理" name="first">
          <div class="flex justify-between mb-3">
            <el-input
              v-model="paramsPageUser.realName"
              placeholder="搜索姓名"
              class="mb-2"
              style="max-width: 300px"
              :prefix-icon="Search"
              @change="postPageUserByRoleApi"
            />
            <Auth :value="['添加成员']">
              <el-button type="primary" @click="AddRolesPerson"
                >添加人员</el-button
              >
            </Auth>
          </div>
          <el-table :data="tableData" style="width: 100%">
            <el-table-column prop="realName" label="姓名" />
            <el-table-column prop="hospitalCode" label="工号" />
            <el-table-column prop="jobTitle" label="职称" />
            <el-table-column prop="dept" label="部门" />
            <el-table-column prop="phone" label="手机号" />
            <el-table-column label="操作">
              <template #default="{ row }">
                <el-dropdown trigger="click" class="mr-2">
                  <Auth :value="['移出成员']">
                    <el-text type="danger" @click="deltetePerson(row)">
                      移除
                    </el-text>
                  </Auth>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>
          <div class="h-[80px]">
            <div class="float-left mt-3 total">共{{ total }}条数据</div>
            <div class="absolute right-0 mr-20 mt-3">
              <el-pagination
                v-model:current-page="paramsPageUser.pageNumber"
                v-model:page-size="paramsPageUser.pageSize"
                background
                layout="prev, pager, next"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
        </el-tab-pane>
        <Auth :value="['权限管理']">
          <el-tab-pane label="权限管理" name="second">
            <el-table :data="menuListRoleList" border style="width: 100%">
              <el-table-column prop="date" label="模块">
                <template #default="{ row }">
                  <div>
                    <input
                      v-model="row.show"
                      type="checkbox"
                      @click="roleShowClick(row, 1)"
                    />{{ row.menuName }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="name" label="菜单">
                <template #default="{ row }">
                  <div v-for="item in row.childrenRes" :key="item.childrenRes">
                    <div
                      v-for="item1 in item.childrenRes"
                      :key="item1.menuCode"
                    >
                      <input
                        v-model="item1.show"
                        type="checkbox"
                        @click="roleShowClick(item1, 1)"
                      />{{ item1.menuName }}
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="address" label="全选">
                <template #default="{ row }">
                  <div>
                    <input
                      v-model="row.allShow"
                      type="checkbox"
                      @click="roleShowClick(row, 0)"
                    />{{ row.date }}全选
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="address" label="权限点">
                <template #default="{ row }">
                  <div v-for="item in row.childrenRes" :key="item.childrenRes">
                    <div
                      v-for="item1 in item.childrenRes"
                      :key="item1.menuCode"
                    >
                      <div
                        v-for="item2 in item1.childrenRes"
                        :key="item2.menuCode"
                      >
                        <input
                          v-model="item2.show"
                          type="checkbox"
                          @click="roleShowClick(item2, 1)"
                        />{{ item2.menuName }}
                      </div>
                    </div>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </Auth>
      </el-tabs>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.total {
  font-size: 14px;
  // font-family: PingFangSC-Regular;
  font-weight: 400;
  line-height: 22px;
  color: #0009;
  letter-spacing: 0;
}

.box-left {
  position: relative;
  width: 25%;
  // border: 1px solid red;
  height: 100%;
  padding: 10px 20px;
  border-right: 1px solid #999;
}

.box-right {
  width: 70%;
  height: 100%;
  padding: 10px 20px;
}

.addRole {
  position: absolute;
  bottom: 70px;
  width: calc(100% - 50px);
}

.infinite-list {
  -ms-overflow-style: none;

  /* IE和Edge */
  scrollbar-width: none;

  /* Firefox */
  // border: 1px solid red;
}

/* 隐藏滚动条 */
.infinite-list::-webkit-scrollbar {
  display: none;

  /* 对于 Webkit 浏览器（Chrome, Safari等） */
}

// ::v-deep .el-dropdown {
//   line-height: 1;
// }
// ::v-deep .el-tree-node__expand-icon {
//   line-height: 10px;
//   border: 1px solid red;
// }
.roles-bg {
  color: #0052d9;
  background-color: #0053d91a;
}

.roles-text {
  font-size: 14px;
  // font-family: PingFangSC-Regular;
  font-weight: 400;
  line-height: 22px;
  color: #000000e6;
  letter-spacing: 0;
}
</style>
