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

import type { VxeGridProps } from '#/adapter/vxe-table';
import type { DictOption } from '#/store/dict';

import { onMounted, ref } from 'vue';

import { Page, useVbenDrawer } from '@vben/common-ui';
import { DictEnum } from '@vben/constants';

import { ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteDistrictInfo,
  districtInfoList,
  exportDistrictInfo,
} from '#/api/system/infoEntry/districtInfo/districtInfo';
import { DictTag } from '#/components/dict/index';
import { getDictOptions } from '#/utils/dict';
import { commonDownloadExcel } from '#/utils/file/download';

import { queryFormSchema, tableColumns } from './districtInfo-data';
import DistrictInfoDrawerComp from './districtInfo-drawer.vue';

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

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    highlight: true,
    reserve: true,
    trigger: 'default',
  },
  columns: tableColumns,
  size: 'medium',
  height: 'auto',
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const resp = await districtInfoList({
          ...formValues,
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        });
        return {
          items: resp.data?.rows || resp.rows || [],
          total: resp.data?.total || resp.total || 0,
        };
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
  id: 'system-districtInfo-index',
};

const [BasicTable, basicTableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

const [DistrictInfoDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: DistrictInfoDrawerComp,
});
// 新增片区
function openDrawer() {
  drawerApi.setData({ isUpdate: false }).open();
}

// 编辑片区
function handleEdit(row: any) {
  // 转换状态为字符串
  drawerApi.setData({ ...row, isUpdate: true }).open();
}

// 单个删除片区
async function confirmEvent(row: any) {
  await deleteDistrictInfo([row.id]);
  await basicTableApi.reload();
}

// 批量删除片区
function deleteHandle() {
  const checkRecords = basicTableApi.grid.getCheckboxRecords();
  const ids = checkRecords.map((item: any) => item.id);
  if (ids.length <= 0) {
    return;
  }

  ElMessageBox.confirm(`确认删除选中的${ids.length}条数据吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await deleteDistrictInfo(ids);
    await basicTableApi.reload();
  });
}

// 导出片区数据
async function exportHandle() {
  await commonDownloadExcel(
    exportDistrictInfo,
    '片区信息数据',
    basicTableApi.formApi.form.values,
  );
}
// 获取状态字典值
const dictStatusRef = ref<DictOption[]>([]);
onMounted(() => {
  dictStatusRef.value = getDictOptions(DictEnum.SYS_NORMAL_DISABLE);
});
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="片区信息列表">
      <template #toolbar-tools>
        <el-space>
          <!-- <el-button
            @click="exportHandle"
            v-access:code="['system:districtInfo:export']"
          >
            导出
          </el-button> -->
          <el-button
            type="danger"
            :disabled="
              !(basicTableApi?.grid?.getCheckboxRecords?.()?.length > 0)
            "
            @click="deleteHandle"
            v-access:code="['system:districtInfo:remove']"
          >
            批量删除
          </el-button>
          <el-button
            type="primary"
            @click="openDrawer"
            v-access:code="['system:districtInfo:add']"
          >
            新增片区
          </el-button>
        </el-space>
      </template>
      <template #action="{ row }">
        <el-space>
          <el-button
            size="small"
            type="primary"
            plain
            @click="handleEdit(row)"
            v-access:code="['system:districtInfo:edit']"
          >
            编辑
          </el-button>
          <el-popconfirm title="确认删除" @confirm="confirmEvent(row)">
            <template #reference>
              <el-button
                size="small"
                type="danger"
                plain
                v-access:code="['system:districtInfo:remove']"
              >
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </el-space>
      </template>
      <template #status="{ row }">
        <div>
          <DictTag :value="row.status" :dicts="dictStatusRef" />
        </div>
      </template>
    </BasicTable>
    <DistrictInfoDrawer @reload="basicTableApi.reload()" />
  </Page>
</template>

<style scoped lang="scss">
:deep(.el-tooltip__trigger:focus) {
  outline: none;
}
</style>
