<script lang="ts" setup>
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';

import { h } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';
import { MdiDelete, MdiDetail, MdiEdit } from '@vben/icons';
import { parseQueryValues } from '@vben/utils';

import { ElMessage, ElMessageBox, ElTag } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteMenuApi, getMenuListApi, initPermissionApi } from '#/api/menu';
import { $t } from '#/locales';

import MenuForm from './form.vue';

const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: true,
  // 控制表单是否显示折叠按钮
  showCollapseButton: true,
  // 按下回车时是否提交表单
  submitOnEnter: true,
  schema: [
    {
      component: 'Input',
      fieldName: 'menu_name',
      label: '菜单名称',
      componentProps: {
        placeholder: $t('ui.placeholder.input'),
        clearable: true,
      },
    },
    // {
    //   component: 'Input',
    //   fieldName: 'menu_sort',
    //   label: '菜单分类',
    //   componentProps: {
    //     placeholder: $t('ui.placeholder.input'),
    //     clearable: true,
    //   },
    // },
    {
      component: 'Select',
      fieldName: 'menu_type',
      label: '菜单类型',
      componentProps: {
        placeholder: $t('ui.placeholder.select'),
        clearable: true,
        clearable: true,
        options: [
          { label: '目录', value: 1 },
          { label: '菜单', value: 2 },
          { label: '按钮', value: 3 },
          { label: 'API接口', value: 4 },
        ],
      },
    },
  ],
  wrapperClass: 'grid-cols-1 md:grid-cols-3 lg:grid-cols-5',
};

const gridOptions: VxeGridProps<any> = {
  toolbarConfig: {
    custom: true,
    export: true,
    refresh: true,
    zoom: true,
  },
  height: 'auto',
  exportConfig: {},
  pagerConfig: {},
  rowConfig: {
    isHover: true,
  },
  stripe: true,

  proxyConfig: {
    response: {
      result: 'Data',
      total: 'Total',
    },
    ajax: {
      query: async ({ page }, formValues) => {
        return await getMenuListApi({
          pageindex: page.currentPage,
          rows: page.pageSize,
          ...parseQueryValues(formValues),
        });
      },
    },
  },

  columns: [
    { title: '菜单名称', field: 'menu_name', sortable: true },
    { title: '备注', field: 'remark', sortable: true },
    // { title: '菜单分类', field: 'menu_sort' },
    {
      title: '菜单类型',
      field: 'menu_type',
      sortable: true,
      slots: {
        default: ({ row }) => {
          const type = row.menu_type;
          const typeMap = {
            1: { text: '目录', type: 'primary' },
            2: { text: '菜单', type: 'success' },
            3: { text: '按钮', type: 'warning' },
            4: { text: 'API接口', type: 'info' },
          };
          return h(
            ElTag,
            {
              // @ts-ignore 运行时类型安全，但TypeScript无法正确推断
              type: typeMap[type]?.type || 'info',
              effect: 'light',
              size: 'small',
            },
            // @ts-ignore 运行时类型安全，但TypeScript无法正确推断
            () => typeMap[type]?.text || '未知',
          );
        },
      },
    },
    { title: '菜单标识', field: 'menu_key', sortable: true },
    { title: '路径', field: 'path', sortable: true },
    { title: '组件', field: 'component', sortable: true },
    { title: '图标', field: 'icon', sortable: true },
    {
      title: '状态',
      field: 'visible',
      sortable: true,
      slots: {
        default: ({ row }) => {
          const status = row.visible;
          return h(
            ElTag,
            {
              type: status === 0 ? 'success' : 'danger',
              effect: 'dark',
              size: 'small',
              round: true,
            },
            () => (status === 0 ? '显示' : '隐藏'),
          );
        },
      },
    },
    { title: '排序', field: 'order_num', sortable: true },
    {
      title: '操作',
      field: 'action',
      fixed: 'right',
      slots: { default: 'action' },
      width: 150,
    },
  ],
};

const gridEvents: VxeGridListeners<any> = {
  cellDblclick: ({ row }) => {
    handleDetail(row);
  },
};

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

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  closeOnClickModal: false,
  closeOnPressEscape: false,
  connectedComponent: MenuForm,
});

/* 创建 */
function handleCreate() {
  modalApi.setState({ showCancelButton: true });
  modalApi.setData({ formType: 'create' }).open();
}

/* 编辑 */
function handleEdit(row: any) {
  modalApi.setState({ showCancelButton: true });
  modalApi.setData({ formType: 'edit', row }).open();
}

/* 详情 */
function handleDetail(row: any) {
  modalApi.setState({ showCancelButton: false });
  modalApi.setData({ formType: 'detail', row }).open();
}

/* 删除 */
async function handleDelete(row: any) {
  try {
    await ElMessageBox.confirm('确认要删除该菜单吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    await deleteMenuApi({ 'menu_id.value': row.menu_id });
    ElMessage.success('删除成功');
    gridApi.reload();
  } catch (error) {
    console.error(error);
  }
}

/* 初始化权限 */
async function handleInitPermission() {
  try {
    await ElMessageBox.confirm('确认要初始化权限吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    await initPermissionApi();
    ElMessage.success('初始化成功');
    gridApi.reload();
  } catch (error) {
    console.error(error);
  }
}

function handleFinish() {
  gridApi.reload();
}
</script>

<template>
  <Page auto-content-height>
    <Grid table-title="菜单列表">
      <template #toolbar-tools>
        <el-button type="warning" @click="handleInitPermission">
          初始化权限
        </el-button>
        <el-button type="primary" @click="handleCreate"> 新增 </el-button>
      </template>
      <template #action="{ row }">
        <el-tooltip
          class="box-item"
          effect="dark"
          content="详情"
          placement="top"
        >
          <el-button
            round
            @click="() => handleDetail(row)"
            :icon="MdiDetail"
            class="!p-2"
          />
        </el-tooltip>
        <el-tooltip
          class="box-item"
          effect="dark"
          content="编辑"
          placement="top"
        >
          <el-button
            round
            @click="() => handleEdit(row)"
            :icon="MdiEdit"
            class="!p-2"
          />
        </el-tooltip>
        <el-tooltip
          class="box-item"
          effect="dark"
          content="删除"
          placement="top"
        >
          <el-button
            round
            @click="() => handleDelete(row)"
            :icon="MdiDelete"
            class="!p-2"
          />
        </el-tooltip>
      </template>
    </Grid>
    <Modal @finish="handleFinish" />
  </Page>
</template>
