<template>
  <div class="role h-full">
    <div v-if="perm.BUTTON_Add" class="page-action page-header">
      <t-button theme="primary" @click="handleAdd">
        <template #icon><svg-icon name="add-circle" color="#fff" /></template>
        新增角色
      </t-button>
    </div>
    <div class="flex-1 page-wrap">
      <t-table
        size="small"
        row-key="id"
        :columns="columns"
        :data="tableData"
        bordered
        :pagination="{
          defaultCurrent: 1,
          defaultPageSize: 10,
          onChange,
          showJumper: true,
          showPageSize: false,
          total: pagination.total,
          current: pagination.pageNumber,
        }"
        v-loading="tableLoading"
      >
        <template #operate="{ row }">
          <div class="table-operations">
            <t-link
              v-if="perm.LINK_Update"
              theme="primary"
              hover="color"
              @click="handleEdit(row)"
            >
              修改
            </t-link>
            <t-link
              v-if="perm.LINK_Delete"
              theme="primary"
              hover="color"
              @click="handleDelete(row)"
            >
              删除
            </t-link>
          </div>
        </template>
      </t-table>
    </div>

    <!-- EditRoleDialog -->
    <edit-role-dialog
      v-if="perm.BUTTON_Add || perm.LINK_Update"
      v-model:visible="showEditRoleDialog"
      :curRow="curRow"
      @success="fetchData"
    ></edit-role-dialog>
  </div>
</template>

<script setup name="RoleManage">
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next';
import useFetchTable from '@/hooks/useFetchTable';
import { getRoleList, deleteRole } from '@/api/user';
import EditRoleDialog from './edit-role-dialog.vue';
import { ref } from 'vue';
import usePermission from '@/hooks/usePermission';
const { perm } = usePermission();

const showEditRoleDialog = ref(false);
const curRow = ref(null);

const columns = [
  { colKey: 'name', title: '角色名称' },
  {
    title: '管理',
    colKey: 'operate',
    fixed: 'right',
    width: 180,
  },
];

const handleAdd = () => {
  curRow.value = null;
  showEditRoleDialog.value = true;
};
const handleEdit = (row) => {
  curRow.value = row;
  showEditRoleDialog.value = true;
};

const handleDelete = (row) => {
  const confirmDia = DialogPlugin({
    header: '操作提示',
    body: `确定要删除角色 ${row.name} 吗`,
    confirmBtn: '确定',
    cancelBtn: '取消',
    theme: 'warning',
    onConfirm: async () => {
      confirmDia.hide();
      const res = await deleteRole({ roleId: row.id }).catch(() => {});
      if (!res) return;
      MessagePlugin.success('删除成功');
      fetchData();
    },
  });
};
const {
  loading: tableLoading,
  pagination,
  tableData,
  fetchData,
  onChange,
} = useFetchTable(getRoleList);
</script>
