<template>
    <div class="p-2">
      <transition>
        <div class="search mb-[10px]">
            <el-card shadow="hover">
                <el-form :model="queryParams" ref="queryFormRef" :inline="true">
                    <el-form-item label="用户名称" prop="role_name">
                        <el-input v-model="queryParams.role_name" placeholder="请输入用户名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
                    </el-form-item>
                    <el-form-item label="权限字符" prop="role_code">
                        <el-input v-model="queryParams.role_code" placeholder="请输入权限字符" clearable style="width: 240px" @keyup.enter="handleQuery" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-card>
        </div>
      </transition>
      <el-card shadow="never">
        <template #header>
          <el-row :gutter="10">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="Plus" @click="openSelectRole">添加角色</el-button>
            </el-col> 
            <el-col :span="1.5">
            <el-button type="danger" plain icon="CircleClose" :disabled="multiple" @click="cancelAuthUserAll">
                批量取消授权
                </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="warning" plain icon="Close" @click="handleClose">关闭</el-button>
            </el-col> 
          </el-row>
        </template>
        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="角色名称" prop="role_name" :show-overflow-tooltip="true"  />
          <el-table-column label="权限字符" prop="role_code" :show-overflow-tooltip="true"  />
          <el-table-column label="描述" prop="description" :show-overflow-tooltip="true"/>  
          <el-table-column label="创建时间" align="center" prop="created_at" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.created_at) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-tooltip content="取消授权" placement="top">
                <el-button link type="primary" icon="CircleClose" @click="cancelAuthUser(scope.row)"> </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
  
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.page_size" @pagination="getList" />
        <select-menu ref="selectRef" :userId="queryParams.userId" @ok="handleQuery" />
      </el-card>
    </div>
</template>
  
  <script setup name="authRole">
  import { allocatedUserList, authUserCancel } from "@/api/role.js";
  import SelectMenu from "./SelectMenu.vue"; // 引入选择角色组件
 
  const route = useRoute();
  const router = useRouter();
  const { proxy } = getCurrentInstance();
   
  const userList = ref([]);
  const loading = ref(true); 
  const multiple = ref(true);
  const total = ref(0);
  const roleIds = ref([]);
  
  const sys_normal_disable = ref([
      {
        label: '启用',
        value: '1'
      },
      {
        label: '停用',
        value: '0'
      }
  ])
  
  const queryFormRef = ref();
  const selectRef = ref(); 

  const queryParams = reactive({
    page: 1,
    page_size: 10,
    userId: route.params.userId,
    role_name: undefined,
    role_code: undefined,
  });
  
  /** 查询当前用户下的角色 */
  const getList = async () => {
    loading.value = true; 
    const res = await allocatedUserList(queryParams);
    userList.value = res.data.roles;
    total.value = res.data.pagination.total;
    loading.value = false;
  }
  // 返回按钮
  const handleClose = () => { 
    router.push('/userManagement/UserManagementPage')
  
  }
  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.pageNum = 1;
    getList();
  }
  /** 重置按钮操作 */
  const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
  }
  // 多选框选中数据
  const handleSelectionChange = (selection) => {
    roleIds.value = selection.map(item => item.uid);
    multiple.value = !selection.length;
  }
  /** 打开授权用户表弹窗 */
  const openSelectRole = () => {
    selectRef.value?.show();
  }
  /** 取消授权按钮操作 */
  const cancelAuthUser = async (row) => { 
    try { 
    await ElMessageBox.confirm(
        `确认要取消该用户"${row.role_name}" 角色吗?`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    );
    if(!route.params.userId){
        ElMessage.error(`不能取消当前登录用户的角色`);
        return;
    } 
    await authUserCancel({ userId: route.params.userId, role_uids: [row.uid] });
    await getList();
    ElMessage.success(`取消授权成功`);  
    } catch (err) {  
        ElMessage.error(`取消授权失败`);
        return;  
    }  
  } 
  /** 批量取消授权按钮操作 */
  const cancelAuthUserAll = async () => {
    try { 
    await ElMessageBox.confirm(
        `是否取消选中角色授权数据项?`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    );
    if(!route.params.userId){
        ElMessage.error(`不能取消当前登录用户的角色`);
        return;
    }  
        const uIds = roleIds.value;   
        await authUserCancel({ userId: route.params.userId, role_uids:uIds });
        await getList();
        ElMessage.success(`取消授权成功`);  
    } catch (err) {  
        ElMessage.error(`取消授权失败`);
        return;  
    }  
}

  onMounted(() => { 
    getList();
  });
  </script>
  
  <style lang="scss" scoped></style>
  