<template>
  <div>
    <n-card class="shadow-sm rounded-8px">
      <div class="mt-4 flex justify-between">
        <div class="flex">
          <div class="w-200px mr-2">
            <n-input v-model:value="searchParams.roleName" clearable type="text" placeholder="角色名称" />
          </div>
          <n-button class="mr-2" type="primary" @click="getRoleList">搜索</n-button>
        </div>
        <n-button v-permission="EnumSystemRolePermission.add" type="primary" @click="handleShowModal(undefined, 'add')"
          >新增角色</n-button
        >
      </div>
      <div class="mt-4">
        <!-- <n-data-table :single-line="false" :columns="columns" :data="roleData" /> -->
        <n-spin :show="loading">
          <vxe-table
            :seq-config="{ startIndex: (pagination.pageNum - 1) * pagination.pageSize }"
            :row-config="{ isHover: true }"
            stripe
            border
            :data="roleData"
          >
            <vxe-column type="seq" title="序号" width="60"></vxe-column>
            <vxe-column field="roleName" title="角色名称"></vxe-column>
            <vxe-column field="roleDesc" title="角色描述"></vxe-column>
            <vxe-column field="createTime" title="创建时间"></vxe-column>
            <vxe-column title="操作">
              <template #default="{ row }">
                <n-space>
                  <n-button strong text type="info" @click="handleShowModal(row, 'view')">查看</n-button>
                  <n-button
                    v-permission="EnumSystemRolePermission.update"
                    strong
                    text
                    type="info"
                    @click="handleShowModal(row, 'edit')"
                    >修改</n-button
                  >
                  <n-button
                    v-permission="EnumSystemRolePermission.delete"
                    strong
                    text
                    type="info"
                    @click="handleDelUser(row)"
                    >删除</n-button
                  >
                </n-space>
              </template>
            </vxe-column>
          </vxe-table>
        </n-spin>
        <div v-if="pagination.itemCount !== 0" class="w-full flex justify-end mt-4">
          <n-pagination
            v-model:page="pagination.pageNum"
            v-model:page-size="pagination.pageSize"
            :item-count="pagination.itemCount"
            :page-sizes="PAGINATION_PAGE_SIZES"
            :on-update:page="handlePageUpdate"
            :on-update:page-size="handlePageSizeUpdate"
            show-size-picker
          />
        </div>
      </div>
    </n-card>
    <RoleForm
      ref="roleFormDom"
      :cur-edit-role-id="curEditRoleId"
      :modal-title="modalTitle"
      @get-role-list="getRoleList"
    />
  </div>
</template>
<script setup lang="ts">
import { h, onMounted, ref, nextTick } from 'vue';
import { NButton, type DataTableColumns } from 'naive-ui';
import { EnumSystemRolePermission } from '@/enum';
import { fetchGetRoles, fetchDelRole } from '@/service';
import { PAGINATION_PAGE_SIZES } from '@/const';
import RoleForm from './components/RoleForm/index.vue';

const pagination = ref({
  pageSize: 10,
  itemCount: 0,
  pageNum: 1
});
function handlePageUpdate(pageNum: number) {
  pagination.value.pageNum = pageNum;
  getRoleList();
}
function handlePageSizeUpdate(pageSize: number) {
  pagination.value.pageNum = 1;
  pagination.value.pageSize = pageSize;
  getRoleList();
}

const searchParams = ref({
  roleName: ''
});

const roleData = ref([]);

const createColumns = (): DataTableColumns<System.RoleTableRow> => {
  return [
    {
      title: '角色编号',
      key: 'roleId'
    },
    {
      title: '角色名称',
      key: 'roleName'
    },
    {
      title: '权限字符',
      key: 'roleKey'
    },
    {
      title: '显示排序',
      key: 'roleSort'
    },
    {
      title: '创建时间',
      key: 'createTime'
    },
    {
      title: '操作',
      key: 'actions',
      render(row) {
        return [
          h(
            NButton,
            {
              strong: true,
              tertiary: true,
              size: 'small',
              type: 'info',
              onClick: () => handleShowModal(row, 'edit')
            },
            { default: () => '修改' }
          ),
          h(
            NButton,
            {
              strong: true,
              tertiary: true,
              size: 'small',
              class: 'mx-2',
              type: 'info',
              onClick: () => handleDelUser(row)
            },
            { default: () => '删除' }
          )
        ];
      }
    }
  ];
};
const columns = createColumns();
/** 删除用户 */
function handleDelUser(row: System.RoleTableRow) {
  window.$dialog?.info({
    title: '提示',
    content: '您确定要删除当前角色吗？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const { data } = await fetchDelRole([row?.roleId]);
      if (data?.ok) {
        window.$message?.success('操作成功');
        getRoleList();
      }
    }
  });
}

/** 获取角色列表 */
const loading = ref(false);
async function getRoleList() {
  loading.value = true;
  const { pageNum, pageSize } = pagination.value;
  const { roleName } = searchParams.value;
  const { data } = await fetchGetRoles(pageNum, pageSize, roleName);
  if (data.ok && data.data) {
    roleData.value = data.data.rows;
    pagination.value.itemCount = data.data.total;
  }
  loading.value = false;
}

/** 角色表单 */
const roleFormDom = ref();
const modalTitle = ref('新增角色');
const curEditRoleId = ref(-1);
/** 打开角色的Form弹窗（新增 or 修改） */
function handleShowModal(row: any, type: string) {
  nextTick(() => {
    if (type === 'add') modalTitle.value = '新增角色';
    if (type === 'edit') modalTitle.value = '修改角色';
    if (type === 'view') modalTitle.value = '查看角色';
    if (row) {
      curEditRoleId.value = row.roleId;
    } else {
      curEditRoleId.value = -1;
    }
    roleFormDom.value.handleShowModal();
  });
}
/** 角色表单 */

/** 分配数据权限表单 */
onMounted(() => {
  getRoleList();
});
</script>
