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

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

import { ref, reactive, watch } from 'vue';
import { useRouter } from 'vue-router';

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

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getCompetitorMarketingSurveyList } from '#/api/archive/operationsManagement/operationsManagement';

import {
  mapApiToView,
  mapFormToApi,
  querySchema,
} from './config-data';

const showSearchForm = ref(true) as any;
const router = useRouter();
const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
  // 日期选择格式化
  // fieldMappingTime: [
  //   [
  //     'createTime',
  //     ['params[beginTime]', 'params[endTime]'],
  //     ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
  //   ],
  // ],
};

// 动态列配置
const dynamicColumns = ref<any[]>([
  {
    field: 'action',
    fixed: 'left',
    slots: { default: 'action' },
    resizable: false,
    title: '操作',
    width: 180,
  },
]);

// 列表中显示配置
const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
    // 点击行选中
    trigger: 'default',
  },
  columns: dynamicColumns.value,
  size: 'medium',
  height: 'auto',
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const apiParams = mapFormToApi(formValues, page);
        const response = await getCompetitorMarketingSurveyList(apiParams);
        
        // 处理动态列
        if (response?.fieldMap) {
          // 清空现有列（保留操作列）
          dynamicColumns.value = [
            {
              field: 'action',
              fixed: 'left',
              slots: { default: 'action' },
              resizable: false,
              title: '操作',
              width: 180,
            },
          ];
          
          // 添加动态列
          response.fieldMap.forEach((field: any) => {
            // 跳过已经在操作列中的字段
            if (field.k === 'action') return;
            
            // 创建列配置
            const column = {
              title: field.v,
              field: field.k,
              minWidth: 130,
            };
            
            // 特殊处理某些字段
            if (field.k === 'isComment') {
              column.formatter = (cellValue: number) => {
                return cellValue === 1 ? '是' : '否';
              };
            }
            
            dynamicColumns.value.push(column);
          });
        }
        console.log(dynamicColumns.value);
        
        const items = mapApiToView(response?.data || []);
        return {
          items,
          total: response?.total || 0,
        };
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
  id: 'competitive-pricing-survey-index',
};
const [BasicTable, BasicTableApi] = useVbenVxeGrid({
  showSearchForm,
  formOptions,
  gridOptions,
});

// 监听动态列变化，更新表格配置
watch(dynamicColumns, (newColumns) => {
  if (BasicTableApi?.setGridOptions) {
    BasicTableApi.setGridOptions({
      columns: newColumns
    });
  }
}, { deep: true });

const handleTaskClick = (taskId: number) => {
  router.push(`/schedule/detail/${taskId}`);
};
</script>
<template>
  <Page :auto-content-height="true">
    <BasicTable>
      <template #toolbar-tools>
        <el-button @click="() => (showSearchForm = !showSearchForm)">
          展开/折叠
        </el-button>
      </template>
      <template #action="{ row }">
        <el-button
          size="small"
          type="primary"
          plain
          @click="() => handleTaskClick(row.taskId)"
        >
          查看
        </el-button>
      </template>
    </BasicTable>
  </Page>
</template>
<style scoped lang="scss">
:deep(.el-tooltip__trigger:focus) {
  outline: none;
}
</style>
