<script setup lang="tsx">
import { NButton, NPopconfirm, NTag } from 'naive-ui';
import { DeleteUser, fetchGetUserList } from '@/service/api';
import { $t } from '@/locales';
import { useAppStore } from '@/store/modules/app';
import { enableStatusRecord } from '@/constants/business';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { useAuthStore } from '@/store/modules/auth';
import UserOperateDrawer from './modules/user-operate-drawer.vue';
import UserSearch from './modules/user-search.vue';

const appStore = useAppStore();
const appauStore = useAuthStore();

const {
  columns,
  columnChecks,
  data,
  getData,
  getDataByPage,
  loading,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchGetUserList,
  showTotal: true,
  apiParams: {
    current: 1,
    size: 10,
    // 如果要在 Form 中使用 searchParams，则需要定义以下属性，值为 null
    // 值不能是 undefined，否则 Form 中的属性将不是响应式的
    status: null,
    USER_NAME: null,
    USER_CODE: null,
    USER_REMARK: null
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'index',
      title: $t('common.index'),
      align: 'center',
      width: 64
    },
    {
      key: 'USER_CODE',
      title: '登录名',
      align: 'center',
      minWidth: 100
    },
    {
      key: 'USER_NAME',
      title: $t('page.manage.user.userName'),
      align: 'center',
      minWidth: 100
    },
    {
      key: 'USER_PASSWORD',
      title: '密码',
      align: 'center',
      minWidth: 100
    },
    {
      key: 'USER_REMARK',
      title: '备注',
      align: 'center',
      minWidth: 100
    },
    {
      key: 'status',
      title: $t('page.manage.user.userStatus'),
      align: 'center',
      width: 100,
      render: row => {
        if (row.status === null) {
          return null;
        }

        const tagMap: Record<Api.Common.EnableStatus, NaiveUI.ThemeColor> = {
          1: 'success',
          2: 'warning'
        };

        const label = $t(enableStatusRecord[row.status]);

        return <NTag type={tagMap[row.status]}>{label}</NTag>;
      }
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 130,
      render: row => {
        // 判断是否是 admin
        if (Number(appauStore.userInfo.userId) !== 0) return null;
        return (
          <div class="flex-center gap-8px">
            <NButton type="primary" ghost size="small" onClick={() => edit(row.id)}>
              {$t('common.edit')}
            </NButton>
            <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
              {{
                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
  const deluserlist: number[] = [];
  checkedRowKeys.value.forEach(item => {
    deluserlist.push(Number(item));
  });
  const delinfo = await DeleteUser(deluserlist);

  if (delinfo.response !== undefined) {
    if (delinfo.response.data.code === '0000') {
      window.$message?.success(delinfo.data?.msg as string);
      getData();
    }
  }
}

async function handleDelete(id: number) {
  const delinfo = await DeleteUser([id]);

  if (delinfo.response !== undefined) {
    if (delinfo.response.data.code === '0000') {
      window.$message?.success(delinfo.data?.msg as string);
      getData();
    }
  }
}

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

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

<style scoped></style>
