<template>
  <div class="part-box is-filter">
    <el-form inline>
      <el-form-item label="角色">
        <el-select
          v-model="searchModel.role"
          placeholder="请选择角色"
          clearable
          filterable
        >
          <el-option
            v-for="item in roleList"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="toPage(1)">查询</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="part-box">
    <el-table
      class="page-table"
      :data="dataList"
      :loading="loading"
      border
      stripe
    >
      <el-table-column prop="name" label="角色名称" min-width="120" />
      <el-table-column prop="code" label="角色编码" min-width="120" />
      <el-table-column prop="updateTime" label="更新时间" width="180" />
      <el-table-column prop="updateName" label="更新人" width="120" />
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            link
            @click="onEdit(scope.row)"
          >
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pagination.pageNumber"
      v-model:page-size="pagination.pageSize"
      :layout="pagination.layout"
      :total="pagination.total"
      @size-change="pageSizeChange"
      @current-change="toPage"
    />
  </div>

  <!-- 编辑角色权限弹窗 -->
  <ModifyRolePrivilege
    ref="modifyRolePrivilegeRef"
    :row-data="curRow"
    :school-id="searchModel.schoolId"
    @modified="getList"
  />
</template>

<script setup lang="ts">
  import { onMounted, reactive, ref } from 'vue';
  import { useRoute } from 'vue-router';
  import { getRoleList, getAllRoleList } from '@/api/user';
  import { RoleItem, RoleListFilter } from '@/api/types/user';
  import useTable from '@/hooks/table';

  import ModifyRolePrivilege from './ModifyRolePrivilege.vue';

  defineOptions({
    name: 'RoleManage',
  });

  const route = useRoute();

  const searchModel = reactive<RoleListFilter>({
    schoolId: Number(route.params.schoolId),
    role: '',
  });

  const { dataList, pagination, loading, getList, toPage, pageSizeChange } =
    useTable<RoleItem>(getRoleList, searchModel, false);

  const roleList = ref([] as RoleItem[]);

  // 获取角色列表
  async function fetchAllRoleList() {
    roleList.value = await getAllRoleList(searchModel.schoolId);
  }

  // table action
  const curRow = ref({} as RoleItem);
  const modifyRolePrivilegeRef = ref();

  function onEdit(row: RoleItem) {
    curRow.value = row;
    modifyRolePrivilegeRef.value?.open();
  }

  onMounted(async () => {
    await fetchAllRoleList();
  });
</script>
