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

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 { ElMessage, ElMessageBox, ElTag } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteRoleApi, getRoleListApi } from '#/api/role';
import { $t } from '#/locales';

import RoleForm from './form.vue';

// 表单配置
const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: true,
  // 控制表单是否显示折叠按钮
  showCollapseButton: true,
  // 按下回车时是否提交表单
  submitOnEnter: true,
  schema: [
    {
      component: 'Input',
      fieldName: 'title',
      label: '角色名称',
      componentProps: {
        placeholder: $t('ui.placeholder.input'),
        allowClear: true,
      },
    },
    {
      component: 'Select',
      fieldName: 'available',
      label: '状态',
      componentProps: {
        placeholder: $t('ui.placeholder.select'),
        allowClear: true,
        options: [
          { label: '启用', value: 1 },
          { label: '禁用', value: 0 },
        ],
      },
    },
  ],
  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 getRoleListApi({
          pageindex: page.currentPage,
          rows: page.pageSize,
          ...formValues,
        });
      },
    },
  },

  columns: [
    // { title: '角色ID', field: 'id', width: 80 },
    { title: '角色名称', field: 'title', minWidth: 120, sortable: true },
    // { title: '排序', field: 'group_sort', width: 80 },
    {
      title: '状态',
      field: 'available',
      width: 100,
      sortable: true,
      slots: {
        default: ({ row }) => {
          return h(
            ElTag,
            {
              type: row.available === 1 ? 'success' : 'info',
            },
            {
              default: () => (row.available === 1 ? '启用' : '禁用'),
            },
          );
        },
      },
    },
    { title: '描述', field: 'details', minWidth: 150, sortable: true },
    {
      title: '创建时间',
      field: 'group_createdate',
      width: 160,
      sortable: true,
    },
    // { title: '更新时间', field: 'group_update', width: 160 },
    {
      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: RoleForm,
});

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

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

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

/* 删除 */
async function handleDelete(row: RoleGroupEntity) {
  try {
    await ElMessageBox.confirm('确认要删除该角色吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    await deleteRoleApi({ 'id.value': row.id });
    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="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>
