办学质量监测教学评价系统
康鲁杰
昨天 78314c7574a880a1bccbdf9a8a531d3cf025a6b4
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
<script setup lang="ts">
import { computed, ref, watch, nextTick, onMounted } from 'vue';
import { Modal, message, FormItem } from 'ant-design-vue';
import { $t } from '@vben/locales';
import { useVbenForm } from '#/adapter/form';
import { drawerSchema } from './data';
import FcDesigner from '@form-create/designer';
import { menuList } from '../../../api/system/menu';
import { listToTree, addFullName, getPopupContainer } from '@vben/utils';
import { pageAdd, pageUpdate, pageInfo } from '#/api/tool/page-designer';
 
interface ModalProps {
  id?: number | string;
  update: boolean;
}
 
const emit = defineEmits<{ reload: [] }>();
 
const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});
 
const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    formItemClass: 'col-span-1',
    labelWidth: 90,
  },
  schema: drawerSchema(),
  showDefaultActions: false,
  wrapperClass: 'grid-cols-5',
});
 
const designer = ref();
const selectedFields = ref([]); // 多选框选中的字段key
const fieldOptions = ref([]);   // 设计区所有字段
const modalVisible = ref(false);
const modalLoading = ref(false);
const currentEditId = ref<string | number>(''); // 当前编辑的ID
 
// 打开弹窗
const open = async (params: ModalProps = { update: false }) => {
  try {
    modalVisible.value = true;
    modalLoading.value = true;
    isUpdate.value = params.update;
    currentEditId.value = params.id || ''; // 保存当前编辑的ID
    await setupPageSelect();
    
    if (params.id) {
      await formApi.setFieldValue('menuId', params.id);
      if (params.update) {
        // 获取详情数据
        const record = await pageInfo(params.id);
        console.log('编辑数据:', record);
        
        // 设置基础表单数据
        await formApi.setValues({
          name: record.name,
          menuId: record.menuId || record.parentId || params.id,  // 优先使用menuId,其次parentId
          status: record.status,
          remark: record.remark,
          actionsFunc: record.actionsFunc ? JSON.parse(record.actionsFunc) : ['add', 'edit', 'delete', 'query']
        });
 
        // 加载表单设计数据
        if (record.formJson) {
          try {
            const formRule = JSON.parse(record.formJson);
            console.log('设计器规则:', formRule);
            designer.value.setRule(formRule);
            
            // 更新字段选项
            await nextTick();
            updateFieldOptions();
            
            // 恢复选中的字段
            if (record.showColumn) {
              selectedFields.value = JSON.parse(record.showColumn);
              console.log('恢复选中字段:', selectedFields.value);
            }
          } catch (e) {
            console.error('加载表单设计数据失败:', e);
            message.error('加载表单设计数据失败');
          }
        }
      }
    } else {
      // 新增时重置数据
      designer.value?.setRule([]);
      selectedFields.value = [];
      await formApi.resetForm();
    }
  } catch (error) {
    console.error('打开弹窗失败:', error);
    message.error('加载数据失败');
  } finally {
    modalLoading.value = false;
  }
};
const close = () => {
  modalVisible.value = false;
};
 
defineExpose({ open, close });
 
async function setupPageSelect() {
  // 获取菜单数据
  const menuArray = await menuList();
  // 过滤掉按钮类型
  const filteredList = menuArray.filter(item => item.menuType !== 'F' && item.menuType !== 'C');
  // 支持i18n
  filteredList.forEach(item => { item.menuName = $t(item.menuName); });
  // 转为树结构
  const menuTree = listToTree(filteredList, { id: 'menuId', pid: 'parentId' });
  // 加根节点
  const fullMenuTree = [
    {
      menuId: 0,
      menuName: $t('menu.root'),
      children: menuTree,
    },
  ];
  // 生成全路径名
  addFullName(fullMenuTree, 'menuName', ' / ');
 
  formApi.updateSchema([
    {
      componentProps: {
        fieldNames: {
          label: 'menuName',
          value: 'menuId',
          children: 'children'
        },
        getPopupContainer,
        listHeight: 300,
        showSearch: true,
        treeData: fullMenuTree,
        treeDefaultExpandAll: false,
        treeDefaultExpandedKeys: [0],
        treeLine: { showLeafIcon: false },
        treeNodeFilterProp: 'menuName',
        treeNodeLabelProp: 'fullName',
      },
      fieldName: 'menuId',
    },
  ]);
}
 
 
// 同步所有字段到选中状态
const syncAllFields = () => {
  // 获取表单组件的规则描述
  const formDesc = designer.value?.getFormDescription?.();
  console.log('表单组件描述:', formDesc);
  
  if (!formDesc || !Array.isArray(formDesc)) {
    message.warning('暂无设计数据');
    return;
  }
 
  // 提取字段信息
  const allFields = formDesc
    .filter(item => item && item.field && item.title)
    .map(item => ({
      title: item.title,
      field: item.field
    }));
  
  console.log('提取的字段:', allFields);
  
  if (allFields.length === 0) {
    message.warning('未找到可用字段');
    return;
  }
 
  // 更新字段选项
  fieldOptions.value = allFields.map(item => ({
    label: item.title,
    value: item.field
  }));
 
  // 选中所有字段
  selectedFields.value = allFields.map(item => item.field);
  message.success(`已同步 ${allFields.length} 个字段`);
};
 
// 处理设计器变化
const handleDesignerChange = () => {
  console.log('设计器内容变化');
  nextTick(() => {
    updateFieldOptions();
  });
};
 
// 当设计器内容变化时更新字段选项
const updateFieldOptions = () => {
  console.log('updateFieldOptions');
  console.log('designer.value', designer.value);
  
  // 获取表单组件的规则描述
  const formDesc = designer.value?.getFormDescription?.();
  if (!formDesc || !Array.isArray(formDesc)) return;
 
  const fields = formDesc
    .filter(item => item && item.field && item.title)
    .map(item => ({
      title: item.title,
      field: item.field
    }));
 
  fieldOptions.value = fields.map(item => ({
    label: item.title,
    value: item.field
  }));
  
  console.log('更新后的字段选项:', fieldOptions.value);
};
 
// 监听设计器内容变化
watch(() => modalVisible.value, (val) => {
  if (val) {
    nextTick(() => updateFieldOptions());
  }
});
 
async function handleOk() {
  try {
    modalLoading.value = true;
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    const data = await formApi.getValues();
    
    // 如果是编辑模式,添加id字段
    if (isUpdate.value) {
      data.id = currentEditId.value;
    }
    
    // 获取表单设计 JSON
    data.formJson = designer.value.getJson();
    // 添加选中的字段
    data.showColumn = JSON.stringify(selectedFields.value);
    // 转换启用功能为JSON字符串
    data.actionsFunc = JSON.stringify(data.actionsFunc);
 
    // 同步一次字段多选
    updateFieldOptions();
    await (isUpdate.value ? pageUpdate(data) : pageAdd(data));
    emit('reload');
    close();
    message.success('保存成功');
  } catch (error) {
    console.error(error);
  } finally {
    modalLoading.value = false;
  }
}
 
function handleCancel() {
  close();
}
</script>
 
<template>
  <a-modal
    v-model:open="modalVisible"
    :title="title"
    :width="'80vw'"
    :confirm-loading="modalLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    :bodyStyle="{ padding: '24px', minHeight: '60vh' }"
    destroyOnClose
    wrapClassName="page-designer-modal"
  > 
    <template #closeIcon>
      <span></span>
    </template>
    <BasicForm />
    <div style="margin-top: 16px;">
      <FcDesigner 
        ref="designer" 
        @update="handleDesignerChange"
        @change="handleDesignerChange"
        @add-rule="handleDesignerChange"
        @remove-rule="handleDesignerChange"
       
      />
      <div style="margin-top: 8px; display: flex; justify-content: flex-end;">
        <a-button type="primary" ghost @click="syncAllFields">
          同步设计字段到表格
        </a-button>
      </div>
    </div>
    <FormItem label="表格字段" style="margin-top: 24px;">
      <a-checkbox-group
        v-model:value="selectedFields"
        :options="fieldOptions"
        style="width:100%;display:flex;flex-wrap:wrap;gap:8px"
      />
    </FormItem>
    <template #empty>
      <div style="padding: 32px 0; color: #999; text-align: center;">
        暂无数据
      </div>
    </template>
  </a-modal>
</template>
 
<style scoped>
.page-designer-modal .ant-modal {
  max-width: 1200px;
}
 
 
</style>