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
<template>
    <div>
        <el-card class="box-card">
            <div slot="header" class="clearfix">
                <span>系统配置</span>
                <!-- <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button> -->
            </div>
 
            <el-tabs v-model="activeName" type="card" class="setupClass-tab" @tab-click="handleClick">
                <el-tab-pane v-for="(item, index) in tabList" :key="item.id" :label="item.paramGroupName"
                    :name="item.paramGroup">
 
                    <el-form :model="formModels[item.id]" :rules="formRules[item.id]" label-width="120px"
                        :ref="(el) => (formRefs[index] = el)" style="width: 100%">
 
                        <el-form-item v-for="(param) in item.paramList" :key="param.id" :label="param.paramName"
                            :prop="param.paramKey">
 
                            <el-input v-if="param.paramControlType === 'input'"
                                v-model="formModels[item.id][param.paramKey]" :placeholder="param.paramPlaceholder"
                                clearable />
 
                            <el-upload v-if="param.paramControlType === 'image'" :action="uploadUrl"
                                list-type="picture-card" :file-list="formModels[item.id][param.paramKey]"
                                :limit="param.paramLimit" 
                                :on-preview="handlePictureCardPreview"
                                :on-remove="(file) => handleRemove(file, param)"
                                :on-success="(response, file, fileList) => handleUploadSuccess(response, file, fileList, param)">
                                <i class="el-icon-plus"></i>
                            </el-upload>
                        </el-form-item>
 
                        <el-form-item v-if="item.paramList && item.paramList.length > 0">
                            <el-button type="primary" @click="submitForm(index)">提交</el-button>
                            <el-button @click="resetForm(index)">重置</el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
            </el-tabs>
        </el-card>
 
        <!-- 预览弹窗 -->
        <el-dialog :visible.sync="previewVisible">
            <img :src="previewImage" alt="Preview Image" style="width: 100%;" />
        </el-dialog>
    </div>
</template>
 
<script>
 
import utils from 'el-business-utils'
 
export default {
    data() {
        return {
            uploadUrl: '',
            activeName: 'first',
            tabList: [],
            previewVisible: false,
            previewImage: '',
            curTab: {},
            curIndex: 0,
            formRefs: [],
            formModels: {}, // 存储每个 tab 的 formModel
            srcFormModels: {}, // 原始表单数据
            formRules: {}, // 存储每个 tab 的 formRules
        };
    },
 
    created() {
        const config = process.env.config
        this.uploadUrl = utils.joinPath(config.httpBaseUri, `flower/api/upload/oss/file`)
    },
    async mounted() {
        await this.getConfigParamGroup();
    },
 
    methods: {
        handleClick(tab, event) {
            this.chooseTab(tab.index)
        },
 
        chooseTab(index) {
            this.curTab = this.tabList[index];
            this.curIndex = index;
            this.getConfigParam();
        },
 
        async getConfigParamGroup() {
            const { code, data } = await this.$elBusHttp.request('flower/v2/config-param-group/list', { params: {} });
            if (code === 0) {
                this.tabList = [...data];
                this.activeName = data[0]?.paramGroup || '';
                this.tabList.forEach(item => {
                    this.$set(this.formModels, item.id, {});
                    this.$set(this.srcFormModels, item.id, {}); // 初始化 srcFormModels
                    this.$set(this.formRules, item.id, {});
                });
                if (data[0]) {
                    this.curTab = this.tabList[0];
                    this.curIndex = 0;
                    this.getConfigParam();
                }
 
            }
        },
 
        createFormModel(paramList) {
            // 创建一个空的对象,用于存储参数
            const model = {};
            paramList.forEach(param => {
                // 如果param.paramControlType是image的话,则将值反序列化成ArrayList
                if (param.paramControlType === 'image') {
                    model[param.paramKey] = this.parseFileList(param.paramValue) || [];
                } else {
                    // 默认处理为字符串
                    model[param.paramKey] = param.paramValue || '';
                }
            });
            return model;
        },
 
        createFormRules(paramList) {
            const rules = {};
            paramList.forEach(param => {
                if (param.paramRequire) {
                    const trigger = param.paramControlType === 'input' ? 'blur' : 'change';
                    const rule = [
                        { required: true, message: `${param.paramPlaceholder}`, trigger }
                    ];
 
                    // 如果param_limit存在且不为null/undefined,添加最大值校验
                    if (param.paramLimit) {
                        // 如果paramControlType是'input',执行最大值校验
                        if (param.paramControlType !== 'image') {
                            rule.push({
                                max: param.paramLimit,
                                message: `${param.paramName}最大值为 ${param.paramLimit}!`,
                                trigger
                            });
                        } else {
                            // 如果是image类型,添加自定义验证,判断数组长度
                            rule.push({
                                validator: (rule, value, callback) => {
                                    if (Array.isArray(value) && value.length > param.paramLimit) {
                                        callback(new Error(`${param.paramName}最多上传 ${param.paramLimit} 张图片`));
                                    } else {
                                        callback();  // 验证通过
                                    }
                                },
                                trigger
                            });
                        }
                    }
 
                    rules[param.paramKey] = rule;
                }
            });
            return rules;
        },
 
        async getConfigParam() {
            const { code, data } = await this.$elBusHttp.request('flower/v2/config-param/list', {
                params: { paramGroupId: this.curTab.id },
            });
            if (code === 0) {
                this.tabList[this.curIndex].paramList = [...data];
 
                // 构造 formModel 和 formRules,并分别存储到对应的对象中
                const formData = this.createFormModel(data);
                this.$set(this.formModels, this.curTab.id, { ...formData });
                this.$set(this.srcFormModels, this.curTab.id, { ...formData }); // 初始化 srcFormModels
                this.$set(this.formRules, this.curTab.id, this.createFormRules(data));
            }
        },
 
        handleRemove(file, param) {
            const srcFormModel = this.srcFormModels[this.curTab.id];
            const currentFormModel = this.formModels[this.curTab.id];
            if (file?.response?.code === '0') {
                const data = file?.response?.data;
                if (data && data[0]) {
                    const removeFile = data[0]
                    const updatedFileList = currentFormModel[param.paramKey].filter(item => item.url !== removeFile.url);
                    // 保存原有的图片控件属性值
                    if (updatedFileList.length === 0) {
                        // 如果文件列表为空,设置为空字符串
                        this.$set(currentFormModel, param.paramKey, []);
                    } else {
                        // 否则,更新为新的文件列表 JSON 字符串
                        this.$set(currentFormModel, param.paramKey, updatedFileList);
 
                    }
 
                }
 
            } else if (file && file?.url) {
                const updatedFileList = currentFormModel[param.paramKey].filter(item => item.url !== file.url);
                // 保存原有的图片控件属性值
                if (updatedFileList.length === 0) {
                    // 如果文件列表为空,设置为空字符串
                    this.$set(currentFormModel, param.paramKey, []);
                } else {
                    // 否则,更新为新的文件列表 JSON 字符串
                    this.$set(currentFormModel, param.paramKey, updatedFileList);
 
                }
            }
 
        },
 
        parseFileList(fileListString) {
            try {
                return JSON.parse(fileListString || '[]');
            } catch (error) {
                console.error('Error parsing fileList JSON:', error);
                return [];
            }
        },
        parseFileListCompare(fileListString, groupId, paramKey) {
            console.log("parseFileListCompare")
            try {
                return JSON.parse(fileListString || '[]');
            } catch (error) {
                console.error('Error parsing fileList JSON:', error);
                return [];
            }
 
            // const newVal = this.formModels[groupId][paramKey]
            // const srcVal = this.srcFormModels[groupId][paramKey]
            // if (newVal !== srcVal) {
            //     try {
            //         return JSON.parse(fileListString || '[]');
            //     } catch (error) {
            //         console.error('Error parsing fileList JSON:', error);
            //         return [];
            //     }
            // }
        },
 
        handleUploadSuccess(response, file, fileList, param) {
            if (response.code === '0') {
                const currentFormModel = this.formModels[this.curTab.id];
                const existingFileList = currentFormModel[param.paramKey];
                const newFile = response.data[0];
                const updatedFileList = [...existingFileList, newFile];
                // this.$set(currentFormModel, param.paramKey, JSON.stringify(updatedFileList));
                currentFormModel[param.paramKey] = updatedFileList;
            } else {
                this.$message.error('文件上传失败');
            }
        },
 
        handlePictureCardPreview(file) {
            if (file.url) {
                this.previewImage = file.url;
                this.previewVisible = true;
            } else {
                this.$message.error('无法预览该文件');
            }
        },
 
        submitForm(index) {
            console.log("submitForm")
            console.log(this.formModels[this.curTab.id])
            console.log(this.formRules[this.curTab.id])
 
            const formRef = this.formRefs[index];
            if (formRef) {
                formRef.validate(async (valid) => {
                    if (valid) {
 
                        // 这里需要将表单的属性匹配到当前的tabList下的paramList的列
                        const tmpParamList = this.tabList[this.curIndex].paramList;
                        // 遍历
                        const submitFormModel = this.formModels[this.curTab.id]
                        // 遍历 submitFormModel 的属性
                        Object.keys(submitFormModel).forEach((key) => {
                            // 在 tmpParamList 中找到 paramKey 与当前属性 key 匹配的记录
                            const paramItem = tmpParamList.find((item) => item.paramKey === key);
                            if (paramItem) {
                                // 将 paramValue 设置为表单中对应属性的值
                                paramItem.paramValue = submitFormModel[key];
                            }
                        });
                        console.log("修改后的值")
                        console.log(tmpParamList)
                        const resultArray = tmpParamList
                            .filter((item) => item.id !== undefined) // 确保 id 存在
                            .map((item) => ({
                                id: item.id,
                                paramValue: item.paramControlType === 'image' ? JSON.stringify(item.paramValue) : item.paramValue
                            }));
 
                        await this.$elBusUtil.confirm('确定要提交吗?')
                        const { code } = await this.$elBusHttp.request(
                            'flower/v2/config-param/update/batch',
                            {
                                method: 'put',
                                data: {
                                    paramList: resultArray,
                                },
                            }
                        )
                        if (code === 0) {
                            await this.getConfigParam()
                            this.$message.success('更新成功')
 
                        }
 
 
                        // this.$message.success('表单校验成功!');
                        // console.log('提交的表单数据: ', this.formModels[this.tabList[index].id]);
                    } else {
                        this.$message.error('表单校验失败,请检查填写内容!');
                    }
                });
            } else {
                console.error(`表单引用未找到: formRefs[${index}]`);
            }
        },
 
        resetForm(index) {
            // console.log()
            // const formRef = this.formRefs[index];
            // if (formRef) {
            //     formRef.resetFields();
 
            //     this.$message.info('表单已重置');
            // } else {
            //     console.error(`未找到表单引用: formRefs[${index}]`);
            // }
            this.chooseTab(index)
            this.activeName = this.tabList[index]?.paramGroup
 
        },
    },
};
</script>