<template>
  <div>
    <n-card class="shadow-sm rounded-8px">
      <div class="search-wrap">
        <n-grid cols="1 s:2 m:3 l:4 xl:5 2xl:6" responsive="screen" x-gap="12" y-gap="12">
          <n-grid-item>
            <p class="mb-6px">用户名：</p>
            <n-input v-model:value="queryParams.userName" placeholder="用户名"></n-input>
          </n-grid-item>
          <n-grid-item>
            <p class="mb-6px">状态：</p>
            <n-select v-model:value="queryParams.status" clearable placeholder="状态" :options="userStatusOptions" />
          </n-grid-item>
          <n-grid-item>
            <p class="mb-6px">创建时间：</p>
            <n-date-picker
              v-model:formatted-value="queryParams.createTime"
              :actions="[]"
              close-on-select
              value-format="yyyy-MM-dd"
              placeholder="创建时间"
              type="daterange"
              start-placeholder="开始"
              end-placeholder="结束"
              clearable
            />
          </n-grid-item>
          <n-grid-item class="flex items-end">
            <n-space>
              <n-button secondary strong type="primary" @click="handleQuery"> 查 询 </n-button>
              <n-button secondary strong @click="handleResetQuery">重 置</n-button>
              <n-button
                v-permission="EnumSystemUserPermission.add"
                type="primary"
                @click="handleShowModal(null, COMMON_OPERATE_TYPE_ADD)"
                >新增</n-button
              >
            </n-space>
          </n-grid-item>
        </n-grid>
      </div>
    </n-card>
    <n-card class="shadow-sm rounded-8px mt-12px">
      <n-spin :show="loading">
        <vxe-table
          :column-config="{ resizable: true }"
          :seq-config="{ startIndex: (pagination.pageNum - 1) * pagination.pageSize }"
          auto-resize
          :row-config="{ isHover: true }"
          stripe
          border
          :data="userData"
        >
          <vxe-column type="seq" title="序号" width="60"></vxe-column>
          <vxe-column min-width="100" show-overflow="tooltip" field="userName" title="用户名"></vxe-column>
          <vxe-column min-width="100" show-overflow="tooltip" field="nickName" title="用户姓名"></vxe-column>
          <!-- <vxe-column min-width="100" show-overflow="tooltip" field="userType" title="用户类型">
            <template #default="{ row }">
              {{ filterUserType(row.userType) }}
            </template>
          </vxe-column> -->
          <vxe-column min-width="100" show-overflow="tooltip" field="deptName" title="部门"></vxe-column>
          <vxe-column min-width="120" field="phonenumber" title="手机号"></vxe-column>
          <vxe-column min-width="120" field="roleNames" show-overflow="tooltip" title="所属角色"></vxe-column>
          <vxe-column min-width="100" field="status" title="状态">
            <template #default="{ row }">
              {{ row.status === SYSTEM_USER_STATUS_ENABLE ? '启用' : '禁用' }}
            </template>
          </vxe-column>
          <vxe-column min-width="180" field="createTime" title="创建时间"></vxe-column>
          <vxe-column field="title" title="操作" fixed="right" min-width="180">
            <template #default="{ row }">
              <n-space>
                <n-button
                  v-permission="EnumSystemUserPermission.update"
                  strong
                  text
                  type="info"
                  @click="handleShowModal(row, 'edit')"
                  >修改</n-button
                >
                <n-button
                  v-permission="EnumSystemUserPermission.delete"
                  strong
                  text
                  type="info"
                  @click="handleDelUser(row)"
                  >删除</n-button
                >
                <n-button
                  v-permission="EnumSystemUserPermission.resetPwd"
                  :disabled="row.status === SYSTEM_USER_STATUS_DISABLED"
                  strong
                  text
                  type="info"
                  @click="handleResetPwd(row)"
                  >重置密码</n-button
                >
              </n-space>
            </template>
          </vxe-column>
          <template #empty>
            <icon-custom-empty-data class="text-320px text-primary" />
          </template>
        </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>
    </n-card>
    <UserForm
      ref="userFormDom"
      :cur-edit-user-id="curEditUserId"
      :modal-title="modalTitle"
      @get-user-list="getUserList"
    />
    <ResetPwd ref="resetPwdDom" :cur-reset-pwd-user-id="curResetPwdUserId" />
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref, nextTick } from 'vue';
import { EnumSystemUserPermission } from '@/enum';
import { objectClean } from '@/utils';
import {
  PAGINATION_PAGE_SIZES,
  USER_TYPE_CORP,
  SYSTEM_USER_STATUS_ENABLE,
  COMMON_OPERATE_TYPE_ADD,
  SYSTEM_USER_STATUS_DISABLED
} from '@/const';
import { fetchGetUserList, fetchDelUser } from '@/service/api';
import UserForm from './components/UserForm/index.vue';
import ResetPwd from './components/ResetPwd/index.vue';

const userStatusOptions = [
  { label: '启用', value: SYSTEM_USER_STATUS_ENABLE },
  { label: '禁用', value: SYSTEM_USER_STATUS_DISABLED }
];

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

/** -------- table相关 -------- */

function createQueryParams() {
  return {
    userName: '',
    status: null,
    createTime: null
  };
}

const queryParams = ref(createQueryParams());

/** 检索 */
function handleQuery() {
  getUserList();
}
/** 重置检索 */
function handleResetQuery() {
  queryParams.value = { ...createQueryParams() };
  getUserList();
}
const userData = ref([]);

/** -------- table相关 -------- */
const curResetPwdUserId = ref(-1);
const resetPwdDom = ref();

function handleResetPwd(row: any) {
  curResetPwdUserId.value = row.userId;
  resetPwdDom.value.handleShowModal();
}
/** 获取用户列表 */
const loading = ref(false);
async function getUserList() {
  loading.value = true;
  const { pageNum, pageSize } = pagination.value;
  const { userName, status, createTime } = queryParams.value;
  const params = {
    userName,
    status,
    beginTime: createTime ? `${createTime[0]} 00:00:00` : '',
    endTime: createTime ? `${createTime[1]} 23:59:59` : '',
    pageNum,
    pageSize
  };
  const { data } = await fetchGetUserList(objectClean(params));
  if (data?.ok) {
    userData.value = data.data.rows;
    pagination.value.itemCount = data.data.total;
  }
  loading.value = false;
}
/** -------- table相关 -------- */

/** -------- modal相关 -------- */
const userFormDom = ref();
const modalTitle = ref('新增用户');
const curEditUserId = ref(-1);

/** 打开弹窗 */
function handleShowModal(row: any, type: string) {
  nextTick(() => {
    if (type === 'add') modalTitle.value = '新增用户';
    if (type === 'edit') modalTitle.value = '修改用户';
    if (row) {
      curEditUserId.value = row.userId;
    } else {
      curEditUserId.value = -1;
    }
    userFormDom.value.handleShowModal();
  });
}
/** -------- modal相关 -------- */

/** 删除用户 */
function handleDelUser(row: System.UserTableRow) {
  window.$dialog?.info({
    title: '提示',
    content: '您确定要删除当前用户吗？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const { data } = await fetchDelUser([row?.userId]);
      if (data?.ok) {
        window.$message?.success('操作成功');
        getUserList();
      }
    }
  });
}
onMounted(() => {
  getUserList();
});
</script>
