gerson
2024-09-08 18aeed6ed17a3aeacc157e0019159957aeaec556
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
<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>
 
        <div class="grid grid-cols-2 gap-2 h-full flex-auto">
            <div class="h-full overflow-auto">
                <el-table
                    ref="rsTableRef"
                    :data="configList"
                    row-class-name="cursor-pointer"
                    class="h-full"
                    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 prop="url" label="请求地址" /> -->
                </el-table>
                <!-- <codemirror
                    v-model="dockCode"
                    :style="{ height: '100%' }"
                    :autofocus="true"
                    :indent-with-tab="true"
                    :tab-size="2"
                    :extensions="dockEditorExtensions"
                    @change="log('change', $event)"
                    @focus="log('focus', $event)"
                    @blur="log('blur', $event)"
                /> -->
            </div>
            <div class="h-full overflow-auto" v-if="currentSql">
                <codemirror
                    class="h-full overflow-auto"
                    v-model="currentSql.sql"
                    :style="{ height: '100%' }"
                    :autofocus="true"
                    :indent-with-tab="true"
                    :tab-size="2"
                    :extensions="sqlEditorExtensions"
                    @change="sqlCodeChange"
                    @focus="log('focus', $event)"
                    @blur="log('blur', $event)"
                />
            </div>
        </div>
    </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 _, { debounce } from 'lodash';
import { onMounted, ref } from 'vue';
import { Codemirror } from 'vue-codemirror';
import * as codeExample from './testData';
import titleBox from '/@/components/titleBox.vue';
 
import type { TableInstance } from 'element-plus';
import { ElMessage } from 'element-plus';
import { v4 as uuid } from 'uuid';
import * as supervisorApi from '/@/api/supervisorAdmin';
import { updateSqlApi } from '/@/api/supervisorAdmin';
import { useCompRef } from '/@/utils/types';
import { SupervisorPublished } from '../types';
 
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 = '';
};
const backLastPage = () => {
    // setTimeout(() => {
    //     resetStatus();
    // }, 300);
    emit('backLastPage');
};
const currentRs = ref<AmisDockConfig>(null);
const dockRowChange = (row) => {
    currentRs.value = row;
    currentSql.value = sqlList.value.find((item) => item.id === currentRs.value.recordId) ?? {
        id: row.recordId,
        sql: '',
    };
};
const currentSql = ref(null);
/** @description 路径分隔符 */
const PATH_SEPARATOR = '/';
/** @description 1 退出所有循环 -1退出当次循环 0或其他值继续 */
const travelObj = (obj, callBack?: (key?: string, value?: any, path?: string) => 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);
        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 {
    Api,
}
type AmisDockApi = string;
type AmisDockValue = AmisDockApi;
type AmisDockConfig = {
    type?: AmisDockType;
    path: string;
    asyncId: string;
    recordId: string;
};
 
const configList = ref<AmisDockConfig[]>([]);
const parseJSONData = (obj: any, apiDataList) => {
    // 先清空
 
    const jsonConfigList = [];
    travelObj(obj, (key, value, path) => {
        if (key === 'api') {
            // const url = value.url;
            const urlPath = path + PATH_SEPARATOR + 'url';
            const randomStr = 'query_' + uuid().slice(0, 12);
            const foundItem = apiDataList.find((item) => item.path === urlPath);
            const asyncId = foundItem?.asyncId ?? randomStr;
            const recordId = foundItem?.recordId ?? randomStr;
            // const recordId = uniqueId()
            jsonConfigList.push({
                asyncId: asyncId,
                recordId: recordId,
                type: AmisDockType.Api,
                path: urlPath,
            });
        }
    });
 
    return jsonConfigList;
};
 
const updateSqlAndRs = (id?, sqlValue?: string) => {
    const apiConfig = configList.value.filter((item) => item.type === AmisDockType.Api);
    if (apiConfig.length === 0) return;
    const asyncRsList = apiConfig.map((item) => ({
        amis_path: item.path,
        async_id: item.asyncId,
        rec_id: item.recordId,
    }));
 
    if (id) {
        const found = sqlList.value?.find((item) => item.id === id);
        if (found) {
            found.sql = sqlValue;
        } else {
            if (!sqlList.value || sqlList.value.length === 0) {
                sqlList.value = [
                    {
                        id: id,
                        sql: sqlValue,
                    },
                ];
            } else {
                sqlList.value.push({
                    id: id,
                    sql: sqlValue,
                });
            }
        }
    }
 
    updateSqlApi(
        {
            id: props.supervisor.id,
            sql_json: sqlList.value.length === 0 ? null : JSON.stringify(sqlList.value),
            async_rs_json: asyncRsList.length === 0 ? null : JSON.stringify(asyncRsList),
        },
        {
            loading: false,
        }
    ).then(() => {
        emit('updatePublished', props.supervisor.id, SupervisorPublished.N);
    });
};
 
const sqlCodeChange = debounce((val) => {
    if (!currentRs.value.recordId) return;
    updateSqlAndRs(currentRs.value.recordId, val);
}, 1000);
const sqlList = 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]);
    });
};
onMounted(async () => {
    xmlJson = await supervisorApi.getLowCodeJson({
        id: props.supervisor.id,
    });
    if (!xmlJson?.amis_json) {
        ElMessage.warning('暂无SQL配置');
        return;
    }
    const originConfig =
        xmlJson.async_rs?.map(
            (item) =>
                ({
                    type: AmisDockType.Api,
                    asyncId: item.async_id,
                    recordId: item.rec_id,
                    path: item.amis_path,
                } as AmisDockConfig)
        ) ?? [];
    sqlList.value = xmlJson.sql ?? null;
 
    configList.value = parseJSONData(xmlJson.amis_json, originConfig);
 
    if (configList.value.length > 0) {
        rsTableRef.value.setCurrentRow(configList.value[0]);
        // dockRowChange(configList.value[0]);
    }
 
    if (checkRsUpdate(originConfig, configList.value)) {
        // 自动更新Rs
        updateSqlAndRs();
    }
});
</script>