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

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

import { computed, 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 {
  deleteStationInfo,
  selectAllSysStationAreaList,
  stationInfoList,
} from '#/api/system/infoEntry/stationInfo/stationInfo';
import { DictTag } from '#/components/dict/index';
import { getDictOptions } from '#/utils/dict';

import { queryFormSchema, tableColumns } from './stationInfo-data';
import StationInfoDrawerComp from './stationInfo-drawer.vue';

// 使用DictEnum常量，不再需要自定义DICT_KEYS

// 片区列表选项
const areaOptions = ref<any[]>([]);
// 场站类型选项
const stationTypeOptions = ref<any[]>([]);
// 状态选项
const statusOptions = ref<any[]>([]);

// 创建响应式的表单选项，方便后续更新
const formOptions = ref<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 = {}) => {
        try {
          const resp = await stationInfoList({
            ...formValues,
            pageNum: page.currentPage,
            pageSize: page.pageSize,
          });
          return {
            items: resp?.rows || [],
            total: resp?.total || 0,
          };
        } catch (error) {
          console.error('获取场站列表失败:', error);
          return { items: [], total: 0 };
        }
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
  id: 'system-infoEntry-stationInfo-index',
};

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

const [StationInfoDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: StationInfoDrawerComp,
  props: {
    areaOptions: computed(() => areaOptions.value),
  },
});

// 加载字典和片区数据
const loadData = async () => {
  try {
    // 获取片区列表
    const areaListResp: any = await selectAllSysStationAreaList();
    areaOptions.value = (areaListResp?.data || []).map((item: any) => ({
      label: item.areaName,
      value: item.id,
    }));

    // 更新表单中的片区选项
    // 使用响应式方式更新schema
    const updatedSchema = [...formOptions.value.schema];
    const areaFieldIndex = updatedSchema.findIndex(
      (item) => item.fieldName === 'areaId',
    );
    if (areaFieldIndex !== -1) {
      updatedSchema[areaFieldIndex] = {
        ...updatedSchema[areaFieldIndex],
        componentProps: {
          ...updatedSchema[areaFieldIndex].componentProps,
          options: areaOptions.value,
        },
      };
      formOptions.value = {
        ...formOptions.value,
        schema: updatedSchema,
      };
    }

    // 获取字典数据
    stationTypeOptions.value = getDictOptions(DictEnum.STATION_TYPE) || [];
    statusOptions.value = getDictOptions(DictEnum.SYS_NORMAL_DISABLE) || [];
  } catch (error) {
    console.error('加载数据失败:', error);
  }
};

onMounted(() => {
  loadData();
});

// 新增场站
function openDrawer() {
  drawerApi.setData({ isUpdate: false }).open();
}

// 编辑场站
function handleEdit(row: any) {
  drawerApi.setData({ ...row, isUpdate: true }).open();
}

// 单个删除场站
async function confirmEvent(row: any) {
  await deleteStationInfo([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 deleteStationInfo(ids);
    await basicTableApi.reload();
  });
}
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="场站信息列表">
      <template #toolbar-tools>
        <ElSpace>
          <!-- <ElButton
            @click="exportHandle"
            v-access:code="['system:infoEntry:stationInfo:export']"
          >
            导出
          </ElButton> -->
          <ElButton
            type="danger"
            :disabled="
              !(basicTableApi?.grid?.getCheckboxRecords?.()?.length > 0)
            "
            @click="deleteHandle"
            v-access:code="['system:infoEntry:stationInfo:remove']"
          >
            批量删除
          </ElButton>
          <ElButton
            type="primary"
            @click="openDrawer"
            v-access:code="['system:infoEntry:stationInfo:add']"
          >
            新增场站
          </ElButton>
        </ElSpace>
      </template>
      <template #typeCode="{ row }">
        <DictTag :value="row.typeCode" :dicts="stationTypeOptions" />
      </template>
      <template #status="{ row }">
        <DictTag :value="row.status" :dicts="statusOptions" />
      </template>
      <template #action="{ row }">
        <ElSpace>
          <ElButton
            size="small"
            type="primary"
            plain
            @click="handleEdit(row)"
            v-access:code="['system:infoEntry:stationInfo:edit']"
          >
            编辑
          </ElButton>
          <ElPopconfirm title="确认删除" @confirm="confirmEvent(row)">
            <template #reference>
              <ElButton
                size="small"
                type="danger"
                plain
                v-access:code="['system:infoEntry:stationInfo:remove']"
              >
                删除
              </ElButton>
            </template>
          </ElPopconfirm>
        </ElSpace>
      </template>
    </BasicTable>
    <StationInfoDrawer
      :area-options="areaOptions"
      @reload="basicTableApi.reload()"
    />
  </Page>
</template>

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