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

import type { VxeGridProps } from '#/adapter/vxe-table';
import type { Notice } from '#/api/system/notice/model';
import type { DictOption } from '#/store/dict';

import { onMounted, ref } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';
import { DictEnum } from '@vben/constants';
import { $t } from '@vben/locales';

import { ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteNotice, listNotice } from '#/api/system/notice/notice';
import { DictTag } from '#/components/dict/index';
import { getDictOptions } from '#/utils/dict';

import { queryFormSchema, tableColumns } from './config-data';
import NoticeModelComp from './notice-modal.vue';

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: queryFormSchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};

// 列表中显示配置
const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
  },
  columns: tableColumns,
  size: 'medium',
  height: 'auto',
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const resp = await listNotice({
          ...formValues,
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        });
        return { items: resp.rows, total: resp.total };
      },
    },
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
};
const [BasicTable, basicTableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

const [NoticeModal, noticeModalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: NoticeModelComp,
});

// 新增打开测试
function openDrawer() {
  noticeModalApi.setData({ isUpdate: false }).open();
}
// 编辑修改角色
function handleEdit(notice: Notice) {
  noticeModalApi.setData({ ...notice, isUpdate: true }).open();
}
// 单个删除配置
async function confirmEvent(notice: Notice) {
  await deleteNotice([notice.noticeId]);
  await basicTableApi.reload();
}
// 删除多个配置
function deleteHandle() {
  // 获取全部选中的数据
  const checkRecords = basicTableApi.grid.getCheckboxRecords();
  // 数据转换只要roleId
  const ids = checkRecords.map((item: Notice) => item.noticeId);
  if (ids.length <= 0) {
    return;
  }
  ElMessageBox.confirm(`确认删除选中的${ids.length}条数据吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    // 删除角色
    await deleteNotice(ids);
    // 重置查询
    await basicTableApi.reload();
  });
}
// 获取状态字典值
const dictStatusRef = ref<DictOption[]>([]);
const noticeTypeRef = ref<DictOption[]>([]);
onMounted(() => {
  dictStatusRef.value = getDictOptions(DictEnum.SYS_NORMAL_DISABLE);
  noticeTypeRef.value = getDictOptions(DictEnum.SYS_NOTICE_TYPE);
});
</script>

<template>
  <Page :auto-content-height="true">
    <NoticeModal @reload="basicTableApi.reload()" />
    <BasicTable table-title="通知公告">
      <template #roleKey="{ row }">
        <ElTag>
          {{ row.roleKey }}
        </ElTag>
      </template>
      <template #noticeType="{ row }">
        <DictTag :value="row.noticeType" :dicts="noticeTypeRef" />
      </template>
      <template #status="{ row }">
        <DictTag :value="row.status" :dicts="dictStatusRef" />
      </template>
      <template #toolbar-tools>
        <ElSpace>
          <ElButton
            type="danger"
            :disabled="
              !(basicTableApi?.grid?.getCheckboxRecords?.()?.length > 0)
            "
            @click="deleteHandle"
            v-access:code="['system:notice:remove']"
          >
            删除
          </ElButton>
          <ElButton
            type="primary"
            @click="openDrawer"
            v-access:code="['system:notice:add']"
          >
            {{ $t('pages.common.add') }}
          </ElButton>
        </ElSpace>
      </template>
      <template #action="{ row }">
        <ElSpace v-if="row.roleId !== 1">
          <ElButton
            size="small"
            type="primary"
            plain
            @click="handleEdit(row)"
            v-access:code="['system:notice:edit']"
          >
            编辑
          </ElButton>
          <ElPopconfirm title="确认删除" @confirm="confirmEvent(row)">
            <template #reference>
              <ElButton
                size="small"
                type="danger"
                plain
                v-access:code="['system:notice:remove']"
              >
                删除
              </ElButton>
            </template>
          </ElPopconfirm>
        </ElSpace>
      </template>
    </BasicTable>
  </Page>
</template>
<style scoped lang="scss">
:deep(.el-tooltip__trigger:focus) {
  outline: none;
}
</style>
