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

import type { MenuLeafFlat, RoleModel } from '@/request/model/manage.model';
import { usePagination, useRequest } from 'alova/client';
import { deleteRole, getMenus, listRoles } from '@/request/api/manage';
import { flattenMenuLeaves } from '@/request/model/manage.model';
import { useRouteMeta } from '@/router/hooks/useRouteMeta';
import { useFloatPanel } from '@/composables/FloatPanel';
import RoleTags from '@/modules/system/components/RoleTags.vue';
import RoleEdit from './role.edit.vue';

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

const form = ref({ rolename: '' });
const reset = () => {
  form.value = { rolename: '' };
  reload();
};
const { loading, data, isLastPage, page, replace, remove, reload, refresh } = usePagination((...args) => listRoles(...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<RoleModel, RoleModel>(RoleEdit);

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

const onEdit = async (item: RoleModel | 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 menus = shallowRef<MenuLeafFlat[]>([]);
const { loading: menus_loading } = useRequest(getMenus).onSuccess(({ data }) => {
  menus.value = flattenMenuLeaves(data);
});
</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="rolename" v-model="form.rolename" label="名称" placeholder="请输入角色名称" />
            <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>{{ item.name }}</template>
              <template #label><RoleTags v-model:selected="item.menus" :menus :loading="menus_loading" /></template>
              <template #value>
                <van-button square type="danger" text="删除" @click="onDelete(item, index)" />
                <van-button square type="primary" text="修改" @click="onEdit(item, index)" />
              </template>
            </van-cell>
          </van-list>
        </van-pull-refresh>
      </div>
    </div>
    <EditFloatPanel auto-height closable />
  </div>
</template>

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