办学质量监测教学评价系统
康鲁杰
9 小时以前 904f065c338f925daf0dd3b0e5517479e5d5480d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
<template>
  <Page v-if="isAdmin && pageId" :auto-content-height="true">
    <BasicTable 
      :key="tableKey"
      :table-title="pageDesignDetail?.name || '模板列表'"
      :grid-options="gridOptions"
    >
      <template #toolbar-tools>
        <Space>
          <a-button v-if="showAction('add')" type="primary" @click="handleAdd">新增</a-button>
        </Space>
      </template>
      <template #action="{ row }">
        <Space>
          <ghost-button v-if="showAction('edit')" @click="handleEdit(row)">编辑</ghost-button>
          <Popconfirm v-if="showAction('delete')" :get-popup-container="getVxePopupContainer" placement="left" title="确认删除?" @confirm="handleDelete(row)">
            <ghost-button danger @click.stop="">删除</ghost-button>
          </Popconfirm>
        </Space>
      </template>
    </BasicTable>
    <TemplateDrawer ref="templateModalRef" @reload="tableApi.query()" />
  </Page>
  <Fallback v-else description="未指定 pageId,无法访问此页面" status="403" />
</template>
 
<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';
import type { VxeGridProps } from '#/adapter/vxe-table';
import { computed, ref, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useAccess } from '@vben/access';
import { Fallback, Page } from '@vben/common-ui';
import { getVxePopupContainer } from '@vben/utils';
import { Popconfirm, Space, Spin as ASpin } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { columns as baseColumns, querySchema } from './data';
import TemplateDrawer from './template-drawer.vue';
import { templateList, templateRemove } from '#/api/tool/template';
import { pageInfo } from '#/api/tool/page-designer';
 
const route = useRoute();
const router = useRouter();
const pageId = ref<string | number>('');
const pageDesignDetail = ref<any>(null); // 页面设计详情
const loading = ref(true); // 加载中
 
// 动态columns
const dynamicColumns = ref([
  { field: 'id', title: 'ID', width: 100 },
  { field: 'formData', title: '表单数据', minWidth: 160 },
  { field: 'action', title: '操作', width: 160, slots: { default: 'action' } }
]);
 
// 用于表格重新渲染的 key
const tableKey = ref(0);
 
// 更新动态列的函数
function updateDynamicColumns() {
  if (!pageDesignDetail.value || !pageDesignDetail.value.showColumn || !pageDesignDetail.value.formJson) {
    console.log('使用默认列');
    return;
  }
 
  try {
    const showFields = JSON.parse(pageDesignDetail.value.showColumn);
    const formFields = JSON.parse(pageDesignDetail.value.formJson);
    const cols = showFields.map(field => {
      const fieldDef = formFields.find(f => f.field === field);
      return {
        field: field,
        title: fieldDef ? fieldDef.title : field,
        minWidth: 120,
        align: 'center',
      };
    });
 
    cols.push({
      field: 'action',
      title: '操作',
      width: 160,
      slots: { default: 'action' },
    });
 
    dynamicColumns.value = cols;
    gridOptions.value = { ...gridOptions.value, columns: cols };
    tableKey.value++;
  } catch (error) {
    const fallbackCols = [
      { field: 'id', title: 'ID', width: 100 },
      { field: 'formData', title: '表单数据', minWidth: 160 },
      { field: 'action', title: '操作', width: 160, slots: { default: 'action' } }
    ];
    dynamicColumns.value = fallbackCols;
    gridOptions.value = { ...gridOptions.value, columns: fallbackCols };
    tableKey.value++;
  }
}
 
 
// 动态按钮
function showAction(action: string) {
  if (!pageDesignDetail.value || !pageDesignDetail.value.actionsFunc) {
    return true;
  }
  
  try {
    const actions = JSON.parse(pageDesignDetail.value.actionsFunc);
    if (!Array.isArray(actions)) {
      console.warn('actionsFunc 不是数组格式:', pageDesignDetail.value.actionsFunc);
      return true;
    }
    
    return actions.includes(action);
  } catch (error) {
    console.error('解析 actionsFunc 失败:', error);
    return true;
  }
}
 
// 获取 pageId,只用 params
function getPageId() {
  const segments = window.location.pathname.split('/');
  return segments[segments.length - 1] || '';
}
 
onMounted(() => {
  const initialPageId = getPageId();
  console.log('获取到的 pageId:', initialPageId);
  
  if (initialPageId) {
    pageId.value = initialPageId;
    handlePageIdChange();
  } else {
    loading.value = false;
  }
});
 
// 监听路由变化,自动更新 pageId
watch(
  () => [route.meta.pageId, route.params.pageId, route.query.pageId],
  (newValues, oldValues) => {
    // 只有当值真正变化时才处理
    if (JSON.stringify(newValues) !== JSON.stringify(oldValues)) {
      const newPageId = getPageId();
      console.log('路由变化后 pageId:', newPageId);
      
      // 只有当 pageId 真正变化时才更新
      if (newPageId !== pageId.value) {
        pageId.value = newPageId;
        handlePageIdChange();
        tableApi.query();
      }
    }
  },
  { deep: true }
);
 
// pageId变化时自动获取页面设计详情
async function handlePageIdChange() {
  loading.value = true;
  console.log(`[handlePageIdChange] 开始处理 pageId: ${pageId.value}`);
  try {
    if (pageId.value) {
      const detail = await pageInfo(pageId.value);
      console.log('[handlePageIdChange] 获取到的页面设计详情 (detail):', JSON.parse(JSON.stringify(detail)));
      
      // 处理数据,避免循环引用
      const safeDetail = {
        id: detail.id,
        name: detail.name,
        menuParentId: detail.menuId,
        status: detail.status,
        remark: detail.remark,
        formJson: detail.formJson,
        showColumn: detail.showColumn,
        actionsFunc: detail.actionsFunc,
        createTime: detail.createTime,
        updateTime: detail.updateTime,
        createBy: detail.createBy,
        updateBy: detail.updateBy,
        createDept: detail.createDept
      };
      
      pageDesignDetail.value = safeDetail;
      console.log('[handlePageIdChange] 设置的 pageDesignDetail.value:', JSON.parse(JSON.stringify(pageDesignDetail.value)));
      updateDynamicColumns();
    } else {
      pageDesignDetail.value = null;
      updateDynamicColumns();
    }
  } catch (error) {
    console.error('[handlePageIdChange] 获取页面设计详情失败:', error);
    pageDesignDetail.value = null;
    updateDynamicColumns();
  } finally {
    loading.value = false;
  }
}
 
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',
};
 
const gridOptions = ref<VxeGridProps>({
  columns: dynamicColumns.value,
  height: 'auto',
  keepSource: true,
  pagerConfig: {
    enabled: true,
  },
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        try {
          console.log('查询参数:', { page, formValues });
          const queryParams = {
            pageNum: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          };
          if (pageId.value) {
            queryParams.pageId = pageId.value;
          }
          const resp = await templateList(queryParams);
          // 处理每条 row 的 formData
          const rows = (resp.rows || []).map(row => {
            let formData = {};
            try {
              if (row.formData) {
                formData = JSON.parse(row.formData);
                console.log('解析后的 formData:', formData);
                // 删除原始的 formData 字段,因为我们已经展开它的内容
                const { formData: _, ...restRow } = row;
                // 返回展开后的数据
                return {
                  ...restRow,
                  ...formData
                };
              }
            } catch (e) {
              console.error('解析 formData 失败:', e);
            }
            return row;
          });
          console.log('处理后的 rows:', rows);
          return {
            rows,
            total: resp.total || 0,
          };
        } catch (error) {
          console.error('查询模板列表失败:', error);
          return {
            rows: [],
            total: 0,
          };
        }
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  id: 'tool-template-index',
  columnConfig: { resizable: true },
});
 
const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions: computed(() => ({
    ...gridOptions.value,
    columns: dynamicColumns.value
  })),
});
 
const templateModalRef = ref();
const generateModalRef = ref();
 
function handleAdd() {
  // 如果有 pageId,传递给新增
  const params: any = { update: false };
  if (pageId.value) {
    params.pageId = pageId.value;
  }
  // 动态传递formJson,先JSON.parse,保证是纯对象
  if (pageDesignDetail.value && pageDesignDetail.value.formJson) {
    try {
      const formJson = JSON.parse(pageDesignDetail.value.formJson);
      params.formJson = formJson;
      console.log('传递动态表单字段:', formJson);
    } catch (error) {
      console.error('解析 formJson 失败:', error);
      params.formJson = undefined;
    }
  }
  templateModalRef.value.open(params);
}
 
function handleEdit(record) {
  // 编辑时也传递formJson,先JSON.parse,保证是纯对象
  const params: any = { 
    id: record.id, 
    update: true,
    pageId: pageId.value,  // 传递页面设计ID
    record: record  // 传递完整的记录数据
  };
  
  if (pageDesignDetail.value && pageDesignDetail.value.formJson) {
    try {
      const formJson = JSON.parse(pageDesignDetail.value.formJson);
      params.formJson = formJson;
      console.log('编辑时传递数据:', { record, formJson, pageId: pageId.value });
    } catch (error) {
      console.error('解析 formJson 失败:', error);
      params.formJson = undefined;
    }
  }
  templateModalRef.value.open(params);
}
 
async function handleDelete(row: any) {
  try {
    await templateRemove([row.id]);
    await tableApi.query();
  } catch (error) {
    console.error('删除模板失败:', error);
  }
}
 
function handleGenerate(row) {
  try {
    generateModalRef.value.open(row);
  } catch (error) {
    console.error('打开生成页面失败:', error);
  }
}
 
function handlePreview(row) {
  try {
    // 打开预览窗口
    const url = `/tool/template/preview/${row.id}`;
    window.open(url, '_blank');
  } catch (error) {
    console.error('打开预览失败:', error);
  }
}
 
const { hasAccessByRoles } = useAccess();
const isAdmin = computed(() => {
  try {
    return hasAccessByRoles(['admin', 'superadmin']);
  } catch (error) {
    console.error('检查权限失败:', error);
    return false;
  }
});
 
const isReady = computed(() => {
  try {
    // 简化判断逻辑,减少不必要的计算
    return !!(pageDesignDetail.value && !loading.value);
  } catch (error) {
    console.error('检查页面准备状态失败:', error);
    return false;
  }
});
</script>
 
<style scoped>
.template-page {
  background: #f5f6fa;
  padding: 16px;
  min-height: 100vh;
  height: 100vh;
  overflow: hidden;
}
 
/* 确保表格容器高度稳定 */
:deep(.vxe-table--main-wrapper) {
  height: 600px !important;
}
 
/* 确保分页器位置固定 */
:deep(.vxe-pager) {
  position: sticky;
  bottom: 0;
  background: white;
  z-index: 10;
}
</style>