<script setup lang="tsx">
import { NButton, NPopconfirm, NTag } from 'naive-ui';
import { fetchGetUserPageList } from '@/service/api';
import { $t } from '@/locales';
import { useAppStore } from '@/store/modules/app';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { roleRecord } from '@/constants/business';
import UserCenterOperateDrawer from './modules/user-manager-operate-drawer.vue';
import UserCenterSearch from './modules/user-manager-search.vue';

const appStore = useAppStore();

const { columns, columnChecks, data, getData, loading, mobilePagination, searchParams, resetSearchParams } = useTable({
  apiFn: fetchGetUserPageList,
  apiParams: {
    page: 1,
    size: 10,
    // if you want to use the searchParams in Form, you need to define the following properties, and the value is null
    // the value can not be undefined, otherwise the property in Form will not be reactive
    username: null,
    role: null
  },
  columns: () => [
    {
      key: 'username',
      title: $t('page.userManager.username'),
      align: 'left',
      minWidth: 120
    },
    {
      key: 'role',
      title: $t('page.userManager.role'),
      align: 'left',
      minWidth: 50,
      render: row => {
        if (row.role === null) {
          return null;
        }
        const tagMap: Record<Api.UserManager.Role, NaiveUI.ThemeColor> = {
          1: 'info',
          2: 'warning'
        };
        const label = $t(roleRecord[row.role]);

        return <NTag type={tagMap[row.role!]}>{label}</NTag>;
      }
    },
    {
      key: 'permissions',
      title: $t('page.userManager.permissions'),
      align: 'left',
      type: 'expand',
      minWidth: 200,
      renderExpand: row => {
        if (!row.permissions) {
          return <NTag type="info">ALL</NTag>;
        }
        return (
          <NTag type="warning">{row.permissions?.map(option => `${option.groupName}(${option.namespaceName})`)}</NTag>
        );
      }
    },
    {
      key: 'updateDt',
      title: $t('common.updateDt'),
      align: 'left',
      minWidth: 50
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 130,
      render: row => (
        <div class="flex-center gap-8px">
          <NButton type="primary" ghost size="small" onClick={() => edit(row.id!)}>
            {$t('common.edit')}
          </NButton>
          <NPopconfirm onPositiveClick={() => handleDelete()}>
            {{
              default: () => $t('common.confirmDelete'),
              trigger: () => (
                <NButton type="error" ghost size="small">
                  {$t('common.delete')}
                </NButton>
              )
            }}
          </NPopconfirm>
        </div>
      )
    }
  ]
});

const {
  drawerVisible,
  operateType,
  editingData,
  handleAdd,
  handleEdit,
  checkedRowKeys,
  onBatchDeleted,
  onDeleted
  // closeDrawer
} = useTableOperate(data, getData);

async function handleBatchDelete() {
  // request
  onBatchDeleted();
}

function handleDelete() {
  // request
  onDeleted();
}

function edit(id: string) {
  handleEdit(id);
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <UserCenterSearch v-model:model="searchParams" @reset="resetSearchParams" @search="getData" />
    <NCard
      :title="$t('page.userManager.title')"
      :bordered="false"
      size="small"
      class="sm:flex-1-hidden card-wrapper"
      header-class="view-card-header"
    >
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          @add="handleAdd"
          @delete="handleBatchDelete"
          @refresh="getData"
        />
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        :flex-height="!appStore.isMobile"
        :scroll-x="962"
        :loading="loading"
        remote
        :row-key="row => row.id"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
      <UserCenterOperateDrawer
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="getData"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
