zm
2020-05-18 a18bfacbf56b401f6e0fdae8710fbca4df8cff77
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
package com.changhong.autoform.mapper.table.impl;
 
import com.alibaba.fastjson.JSON;
import com.changhong.autoform.constant.ConstMap;
import com.changhong.autoform.core.exception.RowOverLengthException;
import com.changhong.autoform.core.mapper.BaseMapper;
import com.changhong.autoform.entity.ColunmsFieldEntity;
import com.changhong.autoform.entity.SubTableStructure;
import com.changhong.autoform.entity.TableStructure;
import com.changhong.autoform.entity.sql.create.CreateTable;
import com.changhong.autoform.entity.sql.insert.Insert;
import com.changhong.autoform.entity.sql.update.UpdateTable;
import com.changhong.autoform.mapper.table.TableMapper;
import com.iemsoft.framework.cloud.core.tools.ObjectUtil;
import org.springframework.stereotype.Component;
import org.springframework.ui.ModelMap;
 
import java.util.*;
import java.util.stream.Collectors;
 
@Component("simpleTableMapper")
public class TableMapperImpl extends BaseMapper implements TableMapper{
 
    private static final Map<String, String> DBTYPE = new HashMap<>();
 
    private static final List<String> FIELDLIST = new ArrayList<>();
 
    private static final Map<String, Integer> DBTYPELENGTH = new HashMap<>();
 
 
    static {
        // 单行文本
        DBTYPE.put("text", ConstMap.VARCHAR150);
        // 单选按钮
        DBTYPE.put("radio", ConstMap.VARCHAR50);
        // 下拉列表框
        DBTYPE.put("dropdownlist", ConstMap.LONGTEXT);
        // 日期控件
        DBTYPE.put("calendar", ConstMap.VARCHAR30);
        // 复选框
        DBTYPE.put("checkbox", ConstMap.LONGTEXT);
        // 子表单
        DBTYPE.put("subform", ConstMap.VARCHAR30);
        // 数字
        DBTYPE.put("number", ConstMap.VARCHAR30);
        // 多行文本
        DBTYPE.put("textarea", ConstMap.LONGTEXT);
        // HTML
        DBTYPE.put("htmlediter", ConstMap.LONGTEXT);
        // 条码
        DBTYPE.put("barcode", ConstMap.VARCHAR30);
        // 二维码
        DBTYPE.put("qrcode", ConstMap.VARCHAR200);
        // 图片
        DBTYPE.put("image", ConstMap.LONGTEXT);
        // 文件上传
        DBTYPE.put("fileupload", ConstMap.LONGTEXT);
        // 数型控件
        DBTYPE.put("tree", ConstMap.LONGTEXT);
        // 金额组件
        DBTYPE.put("amount", ConstMap.LONGTEXT);
        //自定义控件
        DBTYPE.put("mytext",ConstMap.VARCHAR150);
        //自动生成编号控件
        DBTYPE.put("auto",ConstMap.VARCHAR150);
 
        
        // 单行文本
        DBTYPELENGTH.put("text", 150);
        // 单选按钮
        DBTYPELENGTH.put("radio", 50);
        // 日期控件
        DBTYPELENGTH.put("calendar", 30);
        // 复选框
        // 子表单
        DBTYPELENGTH.put("subform", 30);
        // 数字
        DBTYPELENGTH.put("number", 30);
        // 条码
        DBTYPELENGTH.put("barcode", 30);
        // 二维码
        DBTYPELENGTH.put("qrcode", 200);
 
        // 表单固定字段
        FIELDLIST.add("DATAROWNUM");
        FIELDLIST.add("TENANTID");
        FIELDLIST.add("PARENTDATAROWNUM");
        FIELDLIST.add("DELETEFLG");
        FIELDLIST.add("CREATEUSER");
        FIELDLIST.add("CREATEDATETIME");
        FIELDLIST.add("UPDATEUSER");
        FIELDLIST.add("UPDATEDATETIME");
        FIELDLIST.add("PROCESSINSTID");
        
    }
 
    //创建表结构
    @Override
    public int createTable(TableStructure tableStructure) {
        int count = 0;
        count = update(new CreateTable(String.format(tableStructure.getTableName())
                , new ModelMap().addAllAttributes(tableStructure.getFields())));
        //添加记录到formDataManager表中
        Insert insert = new Insert("FORMDATAMANAGER"
                ,new ModelMap("FORMDATATABLE", tableStructure.getTableName())
                .addAttribute("FORMID", tableStructure.getFormId())
                .addAttribute("SUBFORMFLG", 0)
                .addAttribute("CREATEUSER", tableStructure.getCreatUser())
                .addAttribute("UPDATEUSER", tableStructure.getCreatUser())
                .addAttribute("FORMDATANUM", 0)
                .addAttribute("DELETEFLG", 0)
                .addAttribute("TENANTID", tableStructure.getTenantId()));
        execute(insert);
        List<SubTableStructure> subTableList = tableStructure.getSubTableList();
        if(subTableList != null && subTableList.size()>0){
            for (SubTableStructure subTableStructure : subTableList) {
                String subTableName = subTableStructure.getTableName();
                Map<String, Integer> subFormNameAndFormDataNum = subTableStructure.getSubFormNameAndFormDataNum();
                count += update(new CreateTable(subTableName
                        ,new ModelMap().addAllAttributes(subTableStructure.getFields())));
 
                Insert subInsert = new Insert("FORMDATAMANAGER"
                        ,new ModelMap("FORMDATATABLE", subTableStructure.getTableName())
                        .addAttribute("FORMID", tableStructure.getFormId())
                        .addAttribute("SUBFORMFLG", 1)
                        .addAttribute("CREATEUSER", subTableStructure.getCreatUser())
                        .addAttribute("UPDATEUSER", subTableStructure.getCreatUser())
                        .addAttribute("FORMDATANUM", subFormNameAndFormDataNum.get(subTableName))
                        .addAttribute("DELETEFLG", 0)
                        .addAttribute("TENANTID", tableStructure.getTenantId()));
                execute(subInsert);
            }
        }
        return count;
    }
 
    //修改表结构
    @Override
    public int updateTable(TableStructure tableStructure) {
        System.out.println("updateTable请求参数:"+JSON.toJSONString(tableStructure));
        // 获取现有主表字段
        alterTableCols(tableStructure.getTableName(), tableStructure.getAliasValuesMap());
        /*
            处理子表单
        */
        if(ObjectUtil.empty(tableStructure.getSubTableList())){
            return 1;
        }
        tableStructure.getSubTableList().stream().forEach(subTableStructure ->{
            if(ObjectUtil.notEmpty(subTableStructure.getFields())){
                update(new CreateTable(subTableStructure.getTableName()
                        ,new ModelMap().addAllAttributes(subTableStructure.getFields())));
                return;
            }
            alterTableCols(subTableStructure.getTableName()
                    , Optional.ofNullable(subTableStructure.getAliasSubValuesMap().get(subTableStructure.getSubFormNameAndFormDataNum().values().stream().findFirst().orElse(0)))
                            .orElse(Collections.EMPTY_MAP)
            );
        });
        return 1;
    }
 
    protected void alterTableCols(String tableName, Map<String, String> aliasValues){
        List<ColunmsFieldEntity> mainCols = getColunmsField(tableName);
        Set<String> cols = mainCols.stream().map(ColunmsFieldEntity::getField).collect(Collectors.toSet());
        Map<String, Object> alterFields = new HashMap<>();
        aliasValues.entrySet().stream()
                .filter(val->!cols.contains(val.getKey()))
                .forEach(val->alterFields.put(val.getKey()
                        , Optional.ofNullable(DBTYPE.get(aliasValues.get(val.getValue())))
                                .orElse(ConstMap.VARCHAR50)
                ));
 
        if(ObjectUtil.notEmpty(alterFields)) {
            // 添加字段
            update(new UpdateTable(tableName, alterFields));
        }
 
    }
    
//    public static void main(String... args){
//        String v = "DATAROWNUM\tint(11)\n" +
//                "TENANTID\tchar(50)\n" +
//                "PARENTDATAROWNUM\tint(11)\n" +
//                "journey\tvarchar(30)\n" +
//                "单行文本56\tvarchar(150)\n" +
//                "子表单49\tvarchar(30)\n" +
//                "DELETEFLG\tchar(1)\n" +
//                "CREATEUSER\tvarchar(50)\n" +
//                "CREATEDATETIME\ttimestamp\n" +
//                "UPDATEUSER\tvarchar(50)\n" +
//                "UPDATEDATETIME\ttimestamp\n" +
//                "PROCESSINSTID\tdecimal(20,0)\n" +
//                "orderCode\tvarchar(50)\n" +
//                "orderStatus\tvarchar(2)\n" +
//                "processState\tvarchar(2)\n" +
//                "processLog\tvarchar(255)\n" +
//                "processTask\tvarchar(255)\n" +
//                "processUser\tvarchar(20)\n" +
//                "processFlag\tvarchar(20)\n" +
//                "solidification\tlongtext\n" +
//                "voucherCode\tvarchar(20)\n" +
////                "C_Type\tlongtext\n" +
//                "Amount\tvarchar(30)\n" +
//                "toWriteBudget\tlongtext\n" +
//                "payinfo\tvarchar(30)\n" +
//                "budgetStartDate\tvarchar(30)\n" +
//                "Remark\tvarchar(150)\n" +
//                "budget_itemBalance\tvarchar(30)\n" +
//                "reimburseMan\tlongtext\n" +
//                "expend_department\tlongtext\n" +
//                "expendUseMoney\tvarchar(30)\n" +
//                "netMoneyAll\tvarchar(30)\n" +
//                "debitItem\tvarchar(150)\n" +
//                "expenDesc\tvarchar(150)\n" +
//                "currency\tlongtext\n" +
//                "单行文本38\tvarchar(150)\n" +
//                "number_business\tvarchar(50)";
//        List<ColunmsFieldEntity> mainCols = new ArrayList<>();
//        for(String col : v.split("\n")){
//            ColunmsFieldEntity c = new ColunmsFieldEntity();
//            c.setField(col.split("\t")[0]);
//            c.setType(col.split("\t")[1]);
//            mainCols.add(c);
//        }
//        Set<String> cols = mainCols.stream().map(ColunmsFieldEntity::getField).collect(Collectors.toSet());
//        Map<String, Object> alterFields = new HashMap<>();
//        Map<String, Object> aliasValues = JSONTool.toObj("{\n" +
//                "        \"C_Type\":\"tree\",\n" +
//                "        \"journey\":\"subform\",\n" +
//                "        \"toWriteBudget\":\"mytext\",\n" +
//                "        \"payinfo\":\"subform\",\n" +
//                "        \"budgetStartDate\":\"calendar\",\n" +
//                "        \"Remark\":\"text\",\n" +
//                "        \"budget_itemBalance\":\"number\",\n" +
//                "        \"reimburseMan\":\"dropdownlist\",\n" +
//                "        \"expend_department\":\"tree\",\n" +
//                "        \"expendUseMoney\":\"number\",\n" +
//                "        \"netMoneyAll\":\"number\",\n" +
//                "        \"debitItem\":\"text\",\n" +
//                "        \"expenDesc\":\"text\",\n" +
//                "        \"currency\":\"dropdownlist\",\n" +
//                "        \"单行文本38\":\"text\",\n" +
//                "        \"number_business\":\"auto\"\n" +
//                "    }", Map.class);
//        aliasValues.entrySet().stream()
//                .filter(val->!cols.contains(val.getKey()))
//                .forEach(val->alterFields.put(val.getKey()
//                        , Optional.ofNullable(DBTYPE.get(aliasValues.get(val.getValue())))
//                                .orElse(ConstMap.VARCHAR50)
//                ));
//        System.out.println(alterFields);
//    }
 
    protected List<ColunmsFieldEntity> getColunmsField(String tableName) {
        return showColumn(" show columns from "+tableName);
    }
 
    @SuppressWarnings("unused")
    private Map<String,Object> alterTable(String tableName, 
            List<String> fieldtypeList, Map<String, String> fieldsLength, List<String> aliasValues,
            List<String> oldField, Map<String,String> aliasValuesMap) throws RowOverLengthException {
 
        Map<String, List<String>> optionColumns = genAddAndDelColumns(aliasValues, fieldtypeList, oldField);
        List<String> deleteList = optionColumns.get("DELETE");
        List<String> addList = optionColumns.get("ADD"); 
 
        int maxLengthDel = 0;
        for (String delObj : deleteList) {
            if (fieldsLength.get(delObj) != null) {
                String length = fieldsLength.get(delObj).replaceAll("[^0-9]", "");
                if (!fieldsLength.get(delObj).equals("longtext")) {
                    maxLengthDel += Integer.parseInt(length);  //数据类型大小150  varchar(150)
                }
            }
        }
 
        if (!checkRowLength(fieldtypeList, maxLengthDel)) {
            throw new RowOverLengthException();
        }
        Map<String,Object> data = new HashMap<>();
 
        for (int i = 0; i < addList.size(); i++) {
            String field = addList.get(i);
            String type = aliasValuesMap.get(field);
            if (DBTYPE.containsKey(type)) {
                data.put(field, DBTYPE.get(type));
            }
        }
 
        // 表结构没有更改
        if (deleteList.isEmpty() && addList.isEmpty()) {
            return null;
        }
        return data;
    }
 
    private Map<String, Object> alterSubTable(String subTableName, List<String> subFormObjcloumn,  List<String> fieldtypeList,
            Map<String, String> fieldsLength, List<String> oldField, Map<String, String> subFormNameAndColumnsMap )
                    throws RowOverLengthException {
 
        Map<String, List<String>> optionColumns = genAddAndDelColumns(subFormObjcloumn, fieldtypeList, oldField);
        List<String> deleteList = optionColumns.get("DELETE");
        List<String> addList = optionColumns.get("ADD");
 
        int maxLengthDel = 0;
        for (String delObj : deleteList) {
            if (fieldsLength.get(delObj) != null) {
                if (!fieldsLength.get(delObj).equals("longtext")) {
                    Integer length = Integer.parseInt(fieldsLength.get(delObj).replaceAll("[^0-9]", ""));
                    maxLengthDel += length;
                }
            }
        }
        if (!checkRowLength(fieldtypeList, maxLengthDel)) {
            throw new RowOverLengthException();
        }
        Map<String,Object> data = new HashMap<>();
        StringBuilder alterTableSql = new StringBuilder(
                "/*!mycat:sql=select tenantid from FORMDATAMANAGER WHERE TENANTID = '%s' AND FORMID = '%s' */ alter table ");
        alterTableSql.append(subTableName);
        // 表单数据表列增加
        for (int i = 0; i < addList.size(); i++) {
            String field = addList.get(i);
            if("DATAROWNUM".equals(field))
                continue;
            String type = subFormNameAndColumnsMap.get(field);
            if (DBTYPE.containsKey(type)) {
                alterTableSql.append(" ADD COLUMN ");
                alterTableSql.append(field);
                alterTableSql.append(DBTYPE.get(type));
                data.put(field,DBTYPE.get(type));
                alterTableSql.append(" NULL AFTER SUBDATAROWNUM");
                alterTableSql.append(ConstMap.COMMA);
            }
        }
        if (!addList.isEmpty()) {
            alterTableSql.deleteCharAt(alterTableSql.length() - 1);
        }
        // 表结构没有更改
        if (deleteList.isEmpty() && addList.isEmpty()) {
            return null;
        }
        alterTableSql.append(";");
        return data;
    }
 
    private boolean checkRowLength(List<String> fieldtypeList, Integer oldLength) {
        int rowLength = 0;
        for (String type : fieldtypeList) {
            if (DBTYPELENGTH.containsKey(type)) {
                rowLength += DBTYPELENGTH.get(type);
            }
        }
        if ((rowLength + oldLength) > ConstMap.MAXROWLENGTH) {
            return false;
        }
        return true;
    }
 
    private Map<String, List<String>> genAddAndDelColumns(List<String> aliasValues,
            List<String> fieldtypeList,List<String> oldField) {
 
        Map<String, List<String>> map = new HashMap<>();
        List<String> needToDel = new ArrayList<>();
        List<String> needToAdd = new ArrayList<>();
        List<String> needToUpd = new ArrayList<>();
        int count = 0;
        for (String alias : aliasValues) {
            if (DBTYPE.containsKey(fieldtypeList.get(count))) {
                if (!oldField.contains(alias)) {
                    needToAdd.add(alias);
                } else {
                    needToUpd.add(alias);
                }
            }
            count++;
        }
        for (String old : oldField) {
            if (!aliasValues.contains(old)) {
                needToDel.add(old);
            }
        }
        map.put("DELETE", needToDel);
        map.put("ADD", needToAdd);
        map.put("UPDATE", needToUpd);
        return map;
    }
 
}