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

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

import { onMounted, ref } from 'vue';

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

import { ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteRival,
  exportRival,
  rivalList,
} from '#/api/oilstation/rival/rival';
import { getDictOptions } from '#/utils/dict';
import { commonDownloadExcel } from '#/utils/file/download';

import { queryFormSchema, tableColumns } from './rival-data';
import RivalDrawerComp from './rival-drawer.vue';

// 字典标识常量
const DICT_KEYS = {
  // 竞争关系字典标识
  COMPETITIVE_RELATION: 'competitive_relation',
  // 油站性质字典标识
  GAS_STATION: 'gas_station',
  // 状态字典标识
  STATUS: 'status',
};

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 rivalList({
          ...formValues,
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        });
        return { items: resp.rows, total: resp.total };
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
  id: 'oilstation-rival-index',
};

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

const [RivalDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: RivalDrawerComp,
});

// 字典数据引用
const competitiveRelationOptions = ref<any[]>([]);
const gasStationOptions = ref<any[]>([]);
const statusOptions = ref<any[]>([]);

// 加载字典数据
onMounted(() => {
  competitiveRelationOptions.value = getDictOptions(
    DICT_KEYS.COMPETITIVE_RELATION,
  );
  gasStationOptions.value = getDictOptions(DICT_KEYS.GAS_STATION);
  statusOptions.value = getDictOptions(DICT_KEYS.STATUS) || [
    { label: '启用', value: '1' },
    { label: '禁用', value: '2' },
  ];
});

// 新增竞争对手
function openDrawer() {
  drawerApi.setData({ isUpdate: false }).open();
}

// 编辑竞争对手
function handleEdit(row: any) {
  drawerApi.setData({ ...row, isUpdate: true }).open();
}

// 单个删除竞争对手
async function confirmEvent(row: any) {
  await deleteRival([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 deleteRival(ids);
    await basicTableApi.reload();
  });
}

// 导出竞争对手数据
async function exportHandle() {
  await commonDownloadExcel(
    exportRival,
    '油站竞争对手数据',
    basicTableApi.formApi.form.values,
    {
      fieldMappingTime: formOptions.fieldMappingTime,
    },
  );
}
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="油站竞争对手列表">
      <template #toolbar-tools>
        <ElSpace>
          <ElButton
            @click="exportHandle"
            v-access:code="['oilstation:rival:export']"
          >
            导出
          </ElButton>
          <ElButton
            type="danger"
            :disabled="
              !(basicTableApi?.grid?.getCheckboxRecords?.()?.length > 0)
            "
            @click="deleteHandle"
            v-access:code="['oilstation:rival:remove']"
          >
            批量删除
          </ElButton>
          <ElButton
            type="primary"
            @click="openDrawer"
            v-access:code="['oilstation:rival:add']"
          >
            新增竞争对手
          </ElButton>
        </ElSpace>
      </template>
      <template #stationNatureCode="{ row }">
        <ElTag v-if="row.stationNatureCode">
          {{
            gasStationOptions.find(
              (item) => item.value === row.stationNatureCode,
            )?.label || row.stationNatureCode
          }}
        </ElTag>
      </template>
      <template #competitiveRelationCode="{ row }">
        <ElTag v-if="row.competitiveRelationCode">
          {{
            competitiveRelationOptions.find(
              (item) => item.value === row.competitiveRelationCode,
            )?.label || row.competitiveRelationCode
          }}
        </ElTag>
      </template>
      <template #statusCode="{ row }">
        <ElTag
          v-if="row.statusCode"
          :type="row.statusCode === '1' ? 'success' : 'danger'"
        >
          {{
            statusOptions.find((item) => item.value === row.statusCode)
              ?.label || row.statusCode
          }}
        </ElTag>
      </template>
      <template #action="{ row }">
        <ElSpace>
          <ElButton
            size="small"
            type="primary"
            plain
            @click="handleEdit(row)"
            v-access:code="['oilstation:rival:edit']"
          >
            编辑
          </ElButton>
          <ElPopconfirm title="确认删除" @confirm="confirmEvent(row)">
            <template #reference>
              <ElButton
                size="small"
                type="danger"
                plain
                v-access:code="['oilstation:rival:remove']"
              >
                删除
              </ElButton>
            </template>
          </ElPopconfirm>
        </ElSpace>
      </template>
    </BasicTable>
    <RivalDrawer @reload="basicTableApi.reload()" />
  </Page>
</template>

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