wujingjing
2024-09-20 924f3850b1295e5f699bea843fcee83ae860feb6
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
<template>
    <div class="h-full flex flex-col">
        <titleBox class="flex-0" style="background-color: #fff" :title="supervisor?.title">
            <template v-slot:left>
                <el-button
                    icon="ele-ArrowLeft"
                    link
                    style="margin-right: 10px; margin-left: 10px; width: 40px"
                    size="small"
                    @click="backLastPage"
                >
                </el-button>
            </template>
        </titleBox>
 
        <Splitpanes class="default-theme flex-auto" :horizontal="false">
            <Pane :size="40" class="flex-column">
                <div class="flex-0 flex justify-between items-center mb-1 ml-1 h-[36px]">
                    <span class="font-bold">配置项</span>
                </div>
                <el-table
                    ref="rsTableRef"
                    :data="configList"
                    row-class-name="cursor-pointer"
                    class="flex-auto"
                    highlight-current-row
                    @current-change="dockRowChange"
                >
                    <el-table-column prop="asyncId" label="查询 id" />
                    <el-table-column prop="path" label="配置路径" />
                    <el-table-column prop="recordId" label="SQL id" />
                    <!-- <el-table-column label="请求地址" ></el-table-column> -->
                </el-table></Pane
            >
            <Pane :size="60">
                <Splitpanes class="default-theme h100" :horizontal="true">
                    <Pane :size="35" class="flex-col flex">
                        <div class="flex-0 flex justify-between items-center mb-1 ml-1 h-[36px]">
                            <span class="font-bold">参数</span>
                            <el-button type="primary" @click="addArg">添加</el-button>
                        </div>
                        <el-table class="flex-auto" :data="args" border>
                            <el-table-column prop="name" width="150" label="名称" show-overflow-tooltip>
                                <template #default="scope">
                                    <el-input v-model="scope.row.name" @input="argsInput"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column prop="prompt" width="450" label="提示词" show-overflow-tooltip>
                                <template #default="scope">
                                    <el-input type="textarea" :rows="2" v-model="scope.row.prompt" @input="argsInput"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column prop="check" label="缺省值" show-overflow-tooltip>
                                <template #default="scope">
                                    <el-input v-model="scope.row.check" @input="argsInput"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column label="" width="55" fixed="right" show-overflow-tooltip>
                                <template #default="scope">
                                    <el-tooltip effect="dark" content="删除" placement="top">
                                        <i class="ywifont ywicon-shanchu !text-[17px] text-red-400 cursor-pointer" @click="deleteArg(scope.$index)"></i>
                                    </el-tooltip>
                                </template>
                            </el-table-column>
                        </el-table>
                    </Pane>
                    <Pane :size="65">
                        <div class="h-full">
                            <template v-if="currentDockConfig">
                                <div class="flex justify-between items-center my-1 ml-1 h-[36px]">
                                    <el-select class="w-52 font-bold" v-model="currentDockConfig.type">
                                        <el-option
                                            v-for="item in Object.keys(amisDockTypeMap)"
                                            :key="item"
                                            :value="item"
                                            :label="amisDockTypeMap[item]"
                                        ></el-option>
                                    </el-select>
 
                                    <el-select class="w-40" v-model="currentDockConfig.database" @change="databaseSelectChange">
                                        <el-option v-for="item in databaseList" :key="item.id" :value="item.id" :label="item.title"></el-option>
                                    </el-select>
                                </div>
                                <el-tabs v-model="sqlActiveTab" class="overflow-auto" style="height: calc(100% - 36px)">
                                    <el-tab-pane :label="sqlTabMap[SqlTabType.LinkSql]" :name="SqlTabType.LinkSql" class="h-full">
                                        <codemirror
                                            class="overflow-auto"
                                            style="height: 100%"
                                            v-model="currentDockConfig.sql"
                                            :autofocus="true"
                                            :indent-with-tab="true"
                                            :tab-size="2"
                                            :extensions="sqlEditorExtensions"
                                            @change="sqlCodeChange"
                                            @focus="log('focus', $event)"
                                            @blur="log('blur', $event)"
                                        />
                                    </el-tab-pane>
                                    <el-tab-pane :label="sqlTabMap[SqlTabType.Others]" :name="SqlTabType.Others">
                                        <div class="flex-column">
                                            <div class="flex-0 flex mb-3.5">
                                                <el-button class="ml-auto" type="danger" @click="deleteUnLinkSql">删除所有未使用</el-button>
                                            </div>
                                            <el-table
                                                ref="draggableTableRef"
                                                class="flex-auto"
                                                border
                                                row-class-name="cursor-pointer"
                                                :data="otherSqlList"
                                                highlight-current-row
                                            >
                                                
                                                <el-table-column prop="id" label="id" width="220" fixed="left" show-overflow-tooltip> </el-table-column>
                                                <el-table-column label="数据库" prop="database" show-overflow-tooltip>
                                                    
                                                        <template #default="scope">
                                                            {{ getMapDatabase(scope.row.database)?.title }}
                                                        </template>
                                                    
                                                </el-table-column>
 
                                                <el-table-column label="操作" width="120" fixed="right" show-overflow-tooltip>
                                                    <template #default="scope">
                                                        <div class="space-x-3 items-center flex">
                                                            <el-tooltip effect="dark" content="查看SQL" placement="top">
                                                                <i
                                                                    class="ywifont ywicon-didaima !text-[21px] text-blue-400 cursor-pointer"
                                                                    @click="openShowSqlDlg(scope.row)"
                                                                ></i>
                                                            </el-tooltip>
                                                            <el-tooltip effect="dark" content="删除" placement="top">
                                                                <i
                                                                    class="ywifont ywicon-shanchu !text-[17px] text-red-400 cursor-pointer"
                                                                    @click="deleteCurrentSql(scope.row)"
                                                                ></i>
                                                            </el-tooltip>
                                                        </div>
                                                    </template>
                                                </el-table-column>
                                            </el-table>
                                        </div>
                                    </el-tab-pane>
                                </el-tabs>
                            </template>
                        </div>
                    </Pane>
                </Splitpanes>
            </Pane>
        </Splitpanes>
 
        <SqlCodeViewDlg v-model="optDlgIsShow" :item="optDlgMapRow"></SqlCodeViewDlg>
    </div>
</template>
 
<script setup lang="ts">
import { json } from '@codemirror/lang-json';
import { sql } from '@codemirror/lang-sql';
import { xml } from '@codemirror/lang-xml';
import { vscodeDark } from '@uiw/codemirror-theme-vscode';
import type { TableInstance } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
import _, { debounce } from 'lodash';
import { Pane, Splitpanes } from 'splitpanes';
import 'splitpanes/dist/splitpanes.css';
import { v4 as uuid } from 'uuid';
import { onMounted, ref, watch } from 'vue';
import { Codemirror } from 'vue-codemirror';
import { SupervisorPublished } from '../types';
import * as codeExample from './testData';
import { amisDockTypeMap } from './types';
import * as supervisorApi from '/@/api/supervisorAdmin';
import { updateSqlApi } from '/@/api/supervisorAdmin';
import titleBox from '/@/components/titleBox.vue';
import { useCompRef } from '/@/utils/types';
import { computed } from 'vue';
import SqlCodeViewDlg from './optDlg/SqlCodeViewDlg.vue';
 
const props = defineProps(['supervisor']);
const emit = defineEmits(['backLastPage', 'updatePublished']);
const log = console.log;
const jsonCode = ref(codeExample.jsonCode);
const dockCode = ref(codeExample.dockCode);
const sqlCode = ref(codeExample.sqlCode);
 
const jsonEditorExtensions = [json(), vscodeDark];
const sqlEditorExtensions = [sql(), vscodeDark];
const dockEditorExtensions = [xml(), vscodeDark];
const sqlCodeEditorRef = useCompRef(Codemirror);
const resetStatus = () => {
    configList.value = [];
    sqlCode.value = '';
};
 
let defaultSelectDatabase = null;
const databaseSelectChange = (val) => {
    defaultSelectDatabase = val;
    if (currentDockConfig.value) {
        currentDockConfig.value.database = val;
    }
    sqlActiveTab.value = SqlTabType.LinkSql;
    updateSqlAndRs(currentDockConfig.value.id, currentDockConfig.value);
};
const backLastPage = () => {
    // setTimeout(() => {
    //     resetStatus();
    // }, 300);
    emit('backLastPage');
};
const currentRs = ref<AmisDockConfig>(null);
const otherSqlList = computed(() => {
    const sqlConfig = dockConfigList.value.filter((item) => {
        return item.type === AmisDockType.Sql;
    });
    if (!currentDockConfig.value) {
        return sqlConfig;
    }
    // 排除当前
    return sqlConfig.filter((item) => {
        return currentDockConfig.value.id !== item.id;
    });
});
const getWithTemplateDataCommentSql = (sql: string, data: any) => {
    const reg = new RegExp(`^\\s*(\\s*--\\s*".*"\\s*:.*\\n)+\\s*`);
    const isMatchReg = reg.test(sql);
    if (!Array.isArray(data)) {
        return isMatchReg ? sql.replace(reg, '') : sql;
    }
    const first = data[0];
    if (!_.isObjectLike(first)) {
        return isMatchReg ? sql.replace(reg, '') : sql;
    }
    const firstKeyList = Object.keys(first);
    // 值为对象
    if (_.isObjectLike(first[firstKeyList[0]])) {
        return isMatchReg ? sql.replace(reg, '') : sql;
    }
 
    let comment = '';
    firstKeyList.map((key, index, array) => {
        const value = JSON.stringify(first[key]);
        comment += `-- "${key}": ${value}\n`;
        // 最后一个再换行
        comment += index === array.length - 1 ? '\n' : '';
    });
 
    // 已经存在,一定要替换成最新的
    if (isMatchReg) {
        const replaceStr = sql.replace(reg, comment);
        return replaceStr;
    }
 
    const result = comment + sql;
    return result;
};
const dockRowChange = (row) => {
    currentRs.value = row;
    currentDockConfig.value = dockConfigList.value.find((item) => item.id === currentRs.value.recordId) ?? {
        id: row.recordId,
        type: AmisDockType.Sql,
        sql: '',
        database: defaultSelectDatabase ?? databaseList.value[0]?.id ?? null,
    };
    const templateData = extraInfoMap.value.get(row.recordId).templateData;
 
    currentDockConfig.value.sql = getWithTemplateDataCommentSql(currentDockConfig.value.sql, templateData);
};
const currentDockConfig = ref(null);
/** @description 路径分隔符 */
const PATH_SEPARATOR = '/';
/** @description 1 退出所有循环 -1退出当次循环 0或其他值继续 */
const travelObj = (
    obj,
    callBack?: (key?: string, value?: any, path?: string, item?: any) => 1 | -1 | undefined | void | 0,
    path = ''
) => {
    let entry = Object.entries(obj);
 
    let res;
 
    iterate: for (const item of entry) {
        const [key, value] = item;
        const currentPath = path ? path + PATH_SEPARATOR + key : key;
        res = callBack?.(key, value, currentPath, obj);
        switch (res) {
            case 1:
                break iterate;
            case -1:
                continue iterate;
            default:
                break;
        }
        if (!value) {
            continue;
        }
        if (_.isObjectLike(value)) {
            res = travelObj(value, callBack, currentPath);
            switch (res) {
                case 1:
                    break iterate;
                case -1:
                    continue iterate;
                default:
                    break;
            }
        }
    }
    return res;
};
 
const enum AmisDockType {
    Sql = 'SQL',
}
type AmisDockApi = string;
type AmisDockValue = AmisDockApi;
type AmisDockConfig = {
    type?: AmisDockType;
    path: string;
    asyncId: string;
    recordId: string;
    // url: string;
};
 
const configList = ref<AmisDockConfig[]>([]);
 
type ExtraInfo = {
    url: string;
    templateData: Array<any>;
};
const extraInfoMap = ref(new Map<string, ExtraInfo>());
 
const getAmisData = (data) => {
    if (!data) return null;
 
    const dataKeyList = Object.keys(data);
    if (dataKeyList.length === 0) return null;
    if (dataKeyList.length === 1) return data.items ?? data.rows ?? data;
 
    return data;
};
const parseJSONData = (obj: any, apiDataList) => {
    // 先清空
 
    const jsonConfigList = [];
    extraInfoMap.value.clear();
    travelObj(obj, (key, value, path, item) => {
        if (key === 'api') {
            // const url = value.url;
            const urlPath = path + PATH_SEPARATOR + 'url';
            const randomStr = 'q_' + value.url + '_' + uuid().slice(0, 12);
 
            const foundItem = apiDataList.find((item) => item.path === urlPath);
            const asyncId = foundItem?.asyncId ?? randomStr;
            const recordId = foundItem?.recordId ?? randomStr;
 
            extraInfoMap.value.set(recordId, {
                url: value.url,
                templateData: getAmisData(item.data),
            });
            // const recordId = uniqueId()
            jsonConfigList.push({
                asyncId: asyncId,
                recordId: recordId,
                type: AmisDockType.Sql,
                path: urlPath,
            });
        }
    });
 
    return jsonConfigList;
};
 
const checkValid = (showTip: boolean, tip?: string) => {
    if (!dockConfigList.value || dockConfigList.value.length === 0) return true;
    const foundWithNoDatabase = dockConfigList.value?.find((item) => !item.database);
    if (foundWithNoDatabase && showTip) {
        ElMessage.warning(tip ?? `【${foundWithNoDatabase.id}】未选择数据库`);
    }
    return !foundWithNoDatabase;
};
 
const updateSqlAndRs = (id?, sqlValue?: { database?: string; sql?: string; type?: AmisDockType }) => {
    const apiConfig = configList.value.filter((item) => item.type === AmisDockType.Sql);
 
    if (!checkValid(true)) {
        return;
    }
 
    const asyncRsList = apiConfig.map((item) => ({
        amis_path: item.path,
        async_id: item.asyncId,
        rec_id: item.recordId,
    }));
 
    if (id && sqlValue) {
        const foundIndex = dockConfigList.value?.findIndex((item) => item.id === id);
        if (foundIndex > -1) {
            dockConfigList.value[foundIndex] = {
                ...dockConfigList.value[foundIndex],
                ...sqlValue,
            };
        } else {
            if (!sqlValue.database) {
                ElMessage.warning('请先选择数据库');
                return;
            }
            const newSqlValue = {
                id: id,
                database: sqlValue.database ?? null,
                sql: sqlValue.sql ?? null,
                type: sqlValue.type ?? AmisDockType.Sql,
            };
            if (!dockConfigList.value || dockConfigList.value.length === 0) {
                dockConfigList.value = [newSqlValue];
            } else {
                dockConfigList.value.push(newSqlValue);
            }
        }
    }
 
    updateSqlApi(
        {
            id: props.supervisor.id,
            def_rs_json: dockConfigList.value.length === 0 ? null : JSON.stringify(dockConfigList.value),
            async_rs_json: asyncRsList.length === 0 ? null : JSON.stringify(asyncRsList),
            args: args.value.length === 0 ? null : JSON.stringify(args.value),
        },
        {
            loading: false,
        }
    ).then(() => {
        emit('updatePublished', props.supervisor.id, SupervisorPublished.N);
    });
};
 
const sqlCodeChange = debounce((val) => {
    if (!currentRs.value.recordId) return;
    if (currentDockConfig.value) {
        if (!currentDockConfig.value.database) {
            ElMessage.warning('请先选择数据库');
            return;
        }
    }
    updateSqlAndRs(currentDockConfig.value.id, currentDockConfig.value);
}, 1000);
const dockConfigList = ref([]);
const rsTableRef = ref<TableInstance>(null);
let xmlJson = null;
 
// 检查是否需要更新 rs
const checkRsUpdate = (originData: AmisDockConfig[], currentData: AmisDockConfig[]) => {
    // 都为空,不需要更新
    if ((!originData || originData.length === 0) && (!currentData || currentData.length === 0)) {
        return false;
    }
 
    // 存在一方为空,需要更新
    if (!originData || !currentData) {
        return true;
    }
 
    // 长度不一致,需要更新
    if (originData.length !== currentData.length) {
        return true;
    }
 
    return originData.some((originItem) => {
        const id = originItem.asyncId;
        const currentItem = currentData.find((item) => item.asyncId === id);
        // 没找到对应项,需要更新
        if (!currentItem) {
            return true;
        }
 
        // 对象项值不相等,需要更新
        return Object.keys(currentItem).some((item) => originItem[item] !== currentItem[item]);
    });
};
 
//#region ====================== 可编辑表格 ======================
const args = ref([]);
const debounceUpdateInput = debounce(() => {
    updateSqlAndRs();
}, 400);
const argsInput = (val) => {
    debounceUpdateInput();
};
const addArg = () => {
    const initData = {
        name: '',
        prompt: '',
        check: '',
    };
    if (!args.value || args.value.length === 0) {
        args.value = [initData];
    } else {
        args.value.push(initData);
    }
 
    updateSqlAndRs();
};
 
const deleteArg = (index) => {
    args.value.splice(index, 1);
    updateSqlAndRs();
};
 
const databaseList = ref([]);
 
const getMapDatabase = (id:string)=>{
    const foundItem = databaseList.value.find(item=>item.id===id);
    return foundItem;
}
//#endregion
onMounted(async () => {
    xmlJson = await supervisorApi.getLowCodeJson({
        id: props.supervisor.id,
    });
 
    const originConfig =
        xmlJson.async_rs?.map(
            (item) =>
                ({
                    type: AmisDockType.Sql,
                    asyncId: item.async_id,
                    recordId: item.rec_id,
                    path: item.amis_path,
                } as AmisDockConfig)
        ) ?? [];
    dockConfigList.value = xmlJson.def_rs_json ?? null;
    args.value = xmlJson.args ?? [];
 
    configList.value = parseJSONData(xmlJson.amis_json, originConfig);
    const res = await supervisorApi.getAmisDatabaseList();
    databaseList.value = res.values ?? [];
    if (configList.value.length > 0) {
        rsTableRef.value.setCurrentRow(configList.value[0]);
    }
 
    if (!configList || configList.value.length === 0) {
        ElMessage.warning('暂无对接配置');
    }
 
    const isRsUpdate = checkRsUpdate(originConfig, configList.value);
    if (isRsUpdate) {
        // 自动更新Rs
        updateSqlAndRs();
    }
});
//#region ====================== sql 保存历史 ======================
const enum SqlTabType {
    LinkSql = 'link-sql',
    Others = 'sql-list',
}
const sqlTabMap = {
    [SqlTabType.LinkSql]: '关联SQL',
    [SqlTabType.Others]: '其它',
};
const sqlActiveTab = ref<SqlTabType>(SqlTabType.LinkSql);
 
// 删除当前
const deleteCurrentSql = (row) => {
    ElMessageBox.confirm('确定要删除当前SQL吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        dockConfigList.value = dockConfigList.value.filter((item) => item.id !== row.id);
        updateSqlAndRs();
    });
};
// 删除未连接
const deleteUnLinkSql = () => {
    ElMessageBox.confirm('确定要删除所有未使用的SQL吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        const apiConfig = configList.value.filter((item) => item.type === AmisDockType.Sql);
        const recordIds = apiConfig?.map((item) => item.recordId) ?? [];
        // 过滤出 apiConfig 中有的record;
        dockConfigList.value = dockConfigList.value?.filter((item) => recordIds.includes(item.id)) ?? [];
        updateSqlAndRs();
    });
};
 
const optDlgIsShow = ref(false);
const optDlgMapRow = ref(null);
const openShowSqlDlg = (row?: any) => {
    optDlgMapRow.value = row;
    optDlgIsShow.value = true;
};
 
//#endregion
// watch(() => sqlCodemirrorRef.value, (codeMirrorRef) => {
//     codeMirrorRef.
// })
</script>