<script setup lang="ts">
import RoleEdit          from '@/components/RoleEdit.vue';
import { statusOptions } from '@/model/options';

import type { RoleModel, RoleQuery } from '@/model/system.model';
import { usePermission } from '@/core/usePermission';

import { deleteRoleMethod, rolesMethod, updateRoleStatusMethod } from '@/request/api/system.api';
import { usePagination }                                         from 'alova/client';
import { notification }                                          from 'ant-design-vue';

import {
  type VxeFormListeners,
  type VxeFormProps,
  type VxeGridInstance,
  type VxeGridListeners,
  type VxeGridProps,
  VxeUI,
} from 'vxe-pc-ui';


const model = shallowRef<RoleQuery>();
const searchFormProps = reactive<VxeFormProps<RoleQuery>>({
  titleWidth: 100,
  titleAlign: 'right',
  titleColon: true,
  data: {
    roleName: '',
    status: void 0,
  },
  items: [
    { field: 'roleName', title: '角色名称', span: 8, itemRender: { name: 'VxeInput' } },
    {
      field: 'status', title: '是否启用', span: 8, itemRender: {
        name: 'VxeSelect',
        options: statusOptions,
      },
    },
    {
      span: 8, itemRender: {
        name: 'VxeButtonGroup',
        options: [
          { type: 'submit', content: '查询', status: 'primary' },
          { type: 'reset', content: '清空' },
        ],
      },
    },
  ],
});
const searchFormEmits: VxeFormListeners<RoleQuery> = {
  submit({ data }) { model.value = { ...data }; },
  reset({ data }) { model.value = { ...data }; },
};

const gridRef = ref<VxeGridInstance<RoleModel>>();
const gridOptions = reactive<VxeGridProps<RoleModel>>({
  id: 'role-list',
  border: true,
  showOverflow: true,
  height: 'auto', autoResize: false, syncResize: true,
  scrollY: { enabled: true, gt: 0 },
  toolbarConfig: {
    custom: true,
    zoom: true,
    slots: {
      buttons: 'handle',
      tools: 'toolbar-extra',
    },
  },
  columnConfig: {
    resizable: true,
  },
  customConfig: {
    storage: true,
  },
  columns: [
    { type: 'seq', width: 70, fixed: 'left' },
    { field: 'roleName', title: '角色名称' },
    { field: 'updateTime', title: '最近一次修改时间' },
    { field: 'updateBy', title: '操作者' },
    { field: 'createTime', title: '创建时间' },
    { field: 'createBy', title: '创建者' },
    {
      field: 'status', title: '启用状态', align: 'center', minWidth: 90, cellRender: {
        name: 'VxeSwitch',
        props: {
          openLabel: '启用', openValue: '0',
          closeLabel: '停用', closeValue: '1',
          disabled: !usePermission('system:role:edit').value
        },
        events: {
          change({ row, rowIndex }, { value }) {
            row.status = { '1': '0', '0': '1' }[ value as string ] as any;
            updateRoleStatus(row, rowIndex, value);
          },
        },
      },
    },
    {
      title: '操作',
      align: 'center',
      width: 120,
      showOverflow: false,
      cellRender: {
        name: 'VxeButtonGroup',
        props: {
          mode: 'text',
        },
        options: [
          { content: '修改', status: 'warning', name: 'editRole', permissionCode: 'system:role:edit' },
          { content: '删除', status: 'error', name: 'deleteRole', permissionCode: 'system:role:remove' },
        ],
        events: {
          click({ row, rowIndex }, { name }) {
            let method;
            if ( name === 'editRole' ) { method = editRole; } else if ( name === 'deleteRole' ) { method = deleteRole; }
            method?.(row, rowIndex);
          },
        },
      },
    },
  ],
  data: [],
});
const gridEvents: VxeGridListeners = {};

const { loading, page, pageSize, total, onSuccess, replace, refresh, remove } = usePagination(
  (page, size) => rolesMethod(page, size, model.value), {
    initialData: { data: [], total: 0 },
    initialPage: 1,
    initialPageSize: 100,
    watchingStates: [ model ],
    immediate: false,
  },
);
onSuccess(({ data: { data } }) => {
  gridRef.value?.loadData(data);
});

onMounted(() => {
  model.value = toRaw(searchFormProps.data);
});

function updateRoleStatus(model: RoleModel, index: number, status: RoleModel['status']) {
  const { roleId, roleName } = model;
  const label = { '1': '停用', '0': '启用' }[ status ];
  VxeUI.modal.confirm({
    title: `启用状态`,
    content: `确认要 ${ label } ${ roleName } 角色吗？`,
    showClose: false,
    onConfirm() {
      updateRoleStatusMethod({ roleId, status }).then(() => {
        notification.success({
          message: `${ label }角色: ${ roleName }`,
          description: '操作成功',
        });
        model.status = status;
        replace(model, index);
      });
    },
  });
}

function deleteRole(model: RoleModel, index: number) {
  const { roleName } = model;
  VxeUI.modal.confirm({
    title: `删除角色`,
    content: `确认要删除 ${ roleName } 角色吗？`,
    showClose: false,
    onConfirm() {
      deleteRoleMethod(model).then(() => {
        notification.success({
          message: `删除角色: ${ roleName }`,
          description: '操作成功',
        });
        refresh(page.value);
      });
    },
  });
}

function editRole(model?: RoleModel, index?: number) {
  VxeUI.modal.open({
    title: model?.roleId ? `修改角色` : `新增角色`,
    escClosable: true,
    destroyOnClose: true,
    id: `role-edit-modal`,
    remember: true,
    storage: true,
    position: {
      top: Math.min(100,window.innerHeight * 0.15),
    },
    width: 500,
    minHeight: 600,
    slots: {
      default() {
        return h(RoleEdit, <any> {
          data: model, onSubmit(data: RoleModel) {
            refresh(page.value);
            VxeUI.modal.close(`role-edit-modal`);
          },
        });
      },
    },
  });
}
</script>
<template>
  <div class="page-container flex flex-col">
    <header class="flex-none">
      <vxe-form v-bind="searchFormProps" v-on="searchFormEmits"></vxe-form>
    </header>
    <main class="flex-auto overflow-hidden">
      <vxe-grid ref="gridRef" v-bind="gridOptions" v-on="gridEvents" :loading="loading">
        <template #handle>
          <vxe-button status="primary" permission-code="system:role:add" @click="editRole()">新增</vxe-button>
        </template>
        <template #toolbar-extra>
          <vxe-button style="margin-right: 12px;" icon="vxe-icon-repeat" circle @click="refresh(page)"></vxe-button>
        </template>
      </vxe-grid>
    </main>
    <footer class="flex-none">
      <vxe-pager
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :total="total"
        :layouts="['Home', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'End', 'Sizes', 'FullJump', 'Total']"
      />
    </footer>
  </div>
</template>
<style scoped lang="scss">
.page-container {
  padding: 0 24px;
  max-height: var(--page-main-container);
}
</style>
