<script setup lang="ts">
import NavHomeSelect from '@/assets/images/nav-home.select.png?url';

import type { UserModel } from '@/request/model/manage.model';
import { usePagination } from 'alova/client';
import { deleteUser, listUsers, resetUserPassword } from '@/request/api/manage';
import { useRouteMeta } from '@/router/hooks/useRouteMeta';
import { useFloatPanel } from '@/composables/FloatPanel';
import UserEdit from '@/modules/system/user.edit.vue';
import RolePicker from '@/modules/system/components/RolePicker.vue';

const title = useRouteMeta('title', '用户管理', { priority: 'query' });

const form = ref({ userid: '', username: '', roleIds: '' });
const reset = () => {
  form.value = { userid: '', username: '', roleIds: '' };
  displayRoleName.value = '';
  reload();
};
const { loading, data, isLastPage, page, replace, remove, reload, refresh } = usePagination((...args) => listUsers(...args, form.value), {
  initialData: { total: 0, data: [] },
  initialPage: 1,
  initialPageSize: 20,
  append: true,
  immediate: true,
}).onComplete(() => (sending.value = false));
const sending = ref(true);
const onLoad = () => {
  if (sending.value) return;
  sending.value = true;
  page.value += 1;
};

const [EditFloatPanel, edit] = useFloatPanel<UserModel, UserModel>(UserEdit);

const onResetPassword = (item: UserModel, index: number) => {
  showConfirmDialog({
    title: '确定重置用户密码为初始密码吗？',
    message: `重置用户： ${item.name} 的密码`,
    confirmButtonText: '重置',
    async beforeClose(action) {
      if (action !== 'confirm') return true;
      try {
        await resetUserPassword(item.id).send(true);
        showSuccessToast(`重置用户： ${item.name} 的密码成功`);
        return true;
      } catch {
        return false;
      }
    },
  });
};

const onDelete = (item: UserModel, index: number) => {
  showConfirmDialog({
    title: '确定删除吗？',
    message: `删除用户： ${item.name}`,
    confirmButtonText: '删除',
    async beforeClose(action) {
      if (action !== 'confirm') return true;
      try {
        await deleteUser(item.id).send(true);
        remove(item);
        showSuccessToast(`删除用户： ${item.name} 成功`);
        return true;
      } catch {
        return false;
      }
    },
  });
};

const onEdit = async (item: UserModel | null, index: number) => {
  const result = await edit.open(item);
  if (!result) return;
  if (result.id) {
    replace(result, item);
    showSuccessToast(`修改用户： ${result.name} 成功`);
  } else {
    reload();
    showSuccessToast(`创建用户： ${result.name} 成功`);
  }
};

const showRolePicker = ref(false);
const displayRoleName = ref('');
const onRolePickerComplete = (roles: any[]) => {
  const length = roles.length;
  const value = roles
    .slice(0, 2)
    .map((role) => role.rolename || role.name || '-')
    .join('，');
  displayRoleName.value = length <= 2 ? value : `${value} + ${length - 2} 项`;
  reload();
};
</script>

<template>
  <div class="page-container">
    <div class="page-header flex py-4 px-4 overflow-hidden">
      <div class="grow shrink-0 h-full min-w-16"></div>
      <div class="grow-[3] shrink mx-2 flex flex-col justify-center overflow-hidden">
        <div class="font-bold text-3xl text-nowrap text-center tracking-wide overflow-ellipsis overflow-hidden">{{ title }}</div>
      </div>
      <div class="grow shrink-0 h-full min-w-16 flex items-center justify-end overflow-hidden">
        <router-link :to="{ path: '/screen' }" replace>
          <img class="size-8 object-scale-down" :src="NavHomeSelect" alt="返回首页" />
        </router-link>
      </div>
    </div>
    <div class="page-content flex flex-col overflow-hidden">
      <div class="flex-none">
        <van-form label-width="4em" @submit="reload()" @reset="reset()">
          <van-cell-group inset class="grid grid-cols-2 gap-2">
            <van-field :border="false" name="userid" v-model="form.userid" label="账号" placeholder="请输入账号" />
            <van-field :border="false" name="username" v-model="form.username" label="姓名" placeholder="请输入姓名" />
            <van-field :border="false" name="roleIds" v-model="displayRoleName" label="角色" placeholder="请选择角色" readonly @click="showRolePicker = true" />
            <div class="flex items-center justify-end gap-6">
              <div class="flex gap-4">
                <van-button plain size="small" native-type="reset">重置</van-button>
                <van-button plain size="small" type="success" native-type="submit">搜索</van-button>
              </div>
              <div class="flex justify-end gap-4 flex-auto">
                <van-button size="small" type="primary" @click="onEdit(null, -1)">创建用户</van-button>
              </div>
            </div>
          </van-cell-group>
        </van-form>
        <van-divider style="border-color: hsl(var(--primary-hover) / 0.5)" />
      </div>
      <div class="flex-auto overflow-y-scroll list-content-container">
        <van-pull-refresh :modelValue="loading && page === 1" class="min-h-full" @refresh="reload()">
          <van-list :loading="loading || sending" :finished="isLastPage" finished-text="没有更多了" @load="onLoad()">
            <van-cell v-for="(item, index) in data" :key="item.id" size="large" center>
              <template #title>
                <van-row>
                  <van-col span="8">
                    <label class="mr-2" style="color: hsl(var(--primary) / 0.8)">账号:</label>
                    <span>{{ item.account }}</span>
                  </van-col>
                  <van-col span="12">
                    <label class="mr-2" style="color: hsl(var(--primary) / 0.8)">姓名:</label>
                    <span>{{ item.name }}</span>
                  </van-col>
                </van-row>
              </template>
              <template #label>
                <div class="flex flex-wrap gap-2">
                  <van-tag plain type="primary" v-for="role in item.roles" :key="role.id">{{ role.name }}</van-tag>
                </div>
              </template>
              <template #value>
                <van-button square type="danger" text="删除" @click="onDelete(item, index)" />
                <van-button square type="primary" text="修改" @click="onEdit(item, index)" />
                <van-button square type="warning" text="重置密码" @click="onResetPassword(item, index)" />
              </template>
            </van-cell>
          </van-list>
        </van-pull-refresh>
      </div>
    </div>
    <EditFloatPanel auto-height closable />
    <RolePicker v-model:show="showRolePicker" v-model:selected="form.roleIds" @complete="onRolePickerComplete" />
  </div>
</template>

<style scoped lang="scss">
.list-content-container {
  :deep(.van-cell__title) {
    flex: auto;
  }
  :deep(.van-cell__value) {
    flex: none;
  }
}
</style>
