<script lang="ts" setup>
/**
 * 小程序工作台功能入口字典：维护四个业务角色（诊所管理员/平台管理员/业务员/诊所推广员）
 * 工作台宫格入口的展示信息（编码/名称/描述/图标/主题/路径/分组），
 * 角色可见性在「角色管理 → 小程序入口」抽屉里按角色勾选分配
 */
import type { VxeGridListeners } from '#/adapter/vxe-table';

import { ref } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { TableAction } from '#/components/table-action';

import { deleteWxWorkbenchEntry, getWxWorkbenchEntryList } from './api';
import FormModal from './components/modal.vue';
import { STATUS_OPTIONS } from './config/constants';

defineOptions({ name: 'WxWorkbenchEntry' });

const hasTopTableDropDownActions = ref(false);

const formOptions = {
  schema: [
    {
      component: 'VbenInput',
      fieldName: 'code',
      label: '编码',
      componentProps: { placeholder: '如 clinic_admin_withdrawal' },
    },
    {
      component: 'VbenInput',
      fieldName: 'name',
      label: '名称',
      componentProps: { placeholder: '入口名称' },
    },
    {
      component: 'VbenInput',
      fieldName: 'group_name',
      label: '分组',
      componentProps: { placeholder: '如 财务管理' },
    },
    {
      component: 'VbenSelect',
      fieldName: 'status',
      label: '状态',
      componentProps: { options: STATUS_OPTIONS, allowClear: true },
    },
  ],
};

const gridOptions = {
  checkboxConfig: { highlight: true, labelField: '' },
  columns: [
    { type: 'checkbox', width: 60 },
    { field: 'id', title: 'ID', width: 70 },
    { field: 'code', title: '编码', minWidth: 200 },
    { field: 'name', title: '名称', minWidth: 120 },
    { field: 'description', title: '描述', minWidth: 160 },
    { field: 'group_name', title: '分组', width: 110 },
    { field: 'icon', title: '图标', width: 140 },
    { field: 'path', title: '跳转路径', minWidth: 240 },
    { field: 'sort', title: '排序', width: 70 },
    { field: 'status', title: '状态', width: 80, slots: { default: 'status' } },
    { field: 'created_at', title: '创建时间', width: 170 },
    { title: '操作', slots: { default: 'action' }, width: 130, fixed: 'right' },
  ],
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }: any, formValues: any) => {
        return await getWxWorkbenchEntryList({
          page: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
      },
    },
  },
  height: 'auto',
  toolbarConfig: {
    search: true,
    refresh: true,
    slots: { buttons: 'toolbar-actions' },
  },
};

const gridEvents: VxeGridListeners<any> = {
  checkboxChange() {
    hasTopTableDropDownActions.value =
      gridApi.grid.getCheckboxRecords().length > 0;
  },
  checkboxAll() {
    hasTopTableDropDownActions.value =
      gridApi.grid.getCheckboxRecords().length > 0;
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions: gridOptions as any,
  gridEvents,
});

const [FormModalComp, formModalApi] = useVbenModal({
  connectedComponent: FormModal,
});

const showModal = (data: any = {}, isUpdate = false) => {
  formModalApi.setData({
    values: data,
    update: isUpdate,
    gridApi,
  });
  formModalApi.open();
};

const handleDelete = (row: any) => {
  deleteWxWorkbenchEntry({ ids: [row.id] }).then(() => {
    message.success('删除成功');
    gridApi.query();
  });
};

const handleBatchDelete = () => {
  const rows = gridApi.grid.getCheckboxRecords();
  if (!rows.length) return;
  deleteWxWorkbenchEntry({ ids: rows.map((r: any) => r.id) }).then(() => {
    message.success('删除成功');
    gridApi.query();
  });
};
</script>
<template>
  <Page auto-content-height>
    <FormModalComp />
    <Grid>
      <template #toolbar-actions>
        <TableAction
          :actions="[
            {
              label: '新增',
              type: 'primary',
              onClick: () => showModal({}, false),
            },
          ]"
          :drop-down-actions="
            hasTopTableDropDownActions
              ? [
                  {
                    label: '批量删除',
                    popConfirm: {
                      title: '确认删除选中入口？删除后各角色将不再展示',
                      confirm: handleBatchDelete,
                    },
                  },
                ]
              : []
          "
        />
      </template>
      <template #status="{ row }">
        <span :class="row.status === 1 ? 'entry-status-on' : 'entry-status-off'">
          {{ row.status === 1 ? '启用' : '禁用' }}
        </span>
      </template>
      <template #action="{ row }">
        <TableAction
          :actions="[
            {
              label: '编辑',
              onClick: () => showModal(row, true),
            },
            {
              label: '删除',
              popConfirm: {
                title: '确认删除该入口？删除后各角色将不再展示',
                confirm: () => handleDelete(row),
              },
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
<style scoped>
/* 状态文案：主题变量着色，暗色自动适配 */
.entry-status-on {
  color: hsl(var(--success, 142 71% 45%));
}

.entry-status-off {
  color: hsl(var(--muted-foreground));
}
</style>
