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
package cn.autoform.util.tool.impl;
 
import cn.autoform.bean.CodeAndValueBean;
import cn.autoform.db.entity.FieldPropertyEntity;
import cn.autoform.db.entity.FormFieldEntity;
import cn.autoform.factory.FormFactory;
import cn.autoform.fw.utility.ConstMap;
import cn.autoform.util.tool.*;
import cn.autoform.web.service.datamanagement.DataManagementService;
import cn.autoform.web.service.datasource.DatasourceService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * 数据管理,查询列表,将code转换成name
 * @author yuezhw
 * @data 2017-10-20
 */
@SuppressWarnings("unchecked")
@Slf4j
@Component
public class CodeToNameToolImpl implements CodeToNameTool, ColumnConst {
    
    private final static  String TEXTCOLUMN            = "textcolumn";
    private final static  String VALUECOLUMN         = "valuecolumn";
    private final static  String DATASOURCETYPE        = "datasourcetype";
    private final static  String API_URL            = "apiUrl";
    private final static  String API_IDKEY            = "apiIdKey";
    private final static  String API_PIDKEY            = "apiPIdKey";
    private final static  String ITEM                 = "item_1";
    
    private static final Map<String ,WhereToGo> CHOOSE_DATASOURCETYPE = new HashMap<>();
    
    {
        //转换到主数据
        CHOOSE_DATASOURCETYPE.put(ConstMap.MASTERDATA, ()->{
            String code = this.fields.stream().
                    filter(o->"masterData".equals(o.getProperty())).
                        collect(Collectors.toList()).get(0).getValue();
            if(code == null)
                return null;
            String callbackId = ITEM;
            Map<String, List<CodeAndValueBean>> value;
            try {
                value = (Map<String, List<CodeAndValueBean>>) this.formFactory
                                            .createFormMethod()
                                                .getMasterBaseElementListServiceForNew(this.tenantID, code, callbackId,null,null,null);
                return value.get(ITEM);
            } catch (Exception e) {
                e.printStackTrace();
            }
            this.a++;
            System.out.println("------------------------------------------------------");
            System.out.println(this.a+"次");
            System.out.println("-------------------------------------------------------");
            return null;
        });
        
        //转换到数据源
        CHOOSE_DATASOURCETYPE.put(ConstMap.DATASOURCE, ()->{
            try {
                Map<String, FieldPropertyEntity> fieldPropertyMap = new HashMap<>();
                // 数据源
                this.fields.stream().filter(o->Objects.equals(o.getProperty(), ConstMap.DATASOURCE)//过滤出需要的参数
                                                ||Objects.equals(o.getProperty(),TEXTCOLUMN)
                                                    ||Objects.equals(o.getProperty(), TEXTCOLUMN))
                                            .forEach(o->{
                        fieldPropertyMap.put(o.getProperty(), o);
                        
                });
                String datasource = fieldPropertyMap.get(ConstMap.DATASOURCE).getValue();
                String text = fieldPropertyMap.get(TEXTCOLUMN).getValue();
                String value = fieldPropertyMap.get(VALUECOLUMN).getValue();
 
                StringBuilder sendSearchCol = new StringBuilder();
                sendSearchCol.append(text);
                sendSearchCol.append(ConstMap.COMMA);
                sendSearchCol.append(value);
 
                Map<String, List<String>> datasourceList = this.datasourceService.getColumnsValues(this.tenantID, this.formID, datasource,
                        sendSearchCol.toString());
                List<String> codeList = datasourceList.get(text);
                List<String> textList = datasourceList.get(value);
                List<CodeAndValueBean> addList = new ArrayList<>();
                for (int i = 0; i < codeList.size(); i++) {
                    CodeAndValueBean codeAndvaule = new CodeAndValueBean();
                    codeAndvaule.setCode(codeList.get(i));
                    codeAndvaule.setValue(textList.get(i));
                    addList.add(codeAndvaule);
                }
                return addList;
            } catch (Exception e) {
                log.error("---------> 数据源 ERROR!", e);
            }
            return null;
        });
        
        //转换到CUSTOM自定义
        CHOOSE_DATASOURCETYPE.put(ConstMap.CUSTOM, ()->{
            return null;
        });
        
        //转换到API
        CHOOSE_DATASOURCETYPE.put(ConstMap.APIURL, ()->{
            
            Map<String, FieldPropertyEntity> fieldPropertyMap = new HashMap<>();
            // 数据源
            this.fields.stream().filter(o->Objects.equals(o.getProperty(), API_URL)//过滤出需要的参数
                                            ||Objects.equals(o.getProperty(),API_IDKEY)
                                                ||Objects.equals(o.getProperty(), API_PIDKEY))
                                    .forEach(o->{
                                            fieldPropertyMap.put(o.getProperty(), o);
                    
            });
            
            String apiUrl = fieldPropertyMap.get(API_URL).getValue();
            String code = fieldPropertyMap.get(API_IDKEY).getValue();
            String text = fieldPropertyMap.get(API_PIDKEY).getValue();
            BufferedReader reader =null;
            try {
                URL url = new URL(apiUrl);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("GET");
                con.connect();
                reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
                String line;
                StringBuilder buffer = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }
                reader.close();
                con.disconnect();
                String res = buffer.toString();
                JSONArray jsonObjAPi = JSONArray.fromObject(res);
                if (jsonObjAPi.isEmpty()) {
                    List<CodeAndValueBean> addList = new ArrayList<>();
                    for (Object jsonObjSub : jsonObjAPi) {
                        JSONObject jsonObjSubcov = (JSONObject) jsonObjSub;
                        String codeRs = jsonObjSubcov.getString(code);
                        String textRs = jsonObjSubcov.getString(text);
                        CodeAndValueBean codeAndvaule = new CodeAndValueBean();
                        codeAndvaule.setCode(codeRs);
                        codeAndvaule.setValue(textRs);
                        addList.add(codeAndvaule);
                    }
                    return addList;
                }
            } catch (Exception e) {
                log.error("---------> API URL ERROR!", e);
 
            }finally{
                if(reader != null){
                    reader.close();
                }
            }
            return null;
        });
    }
    
    Integer a = 0;
    @Resource
    DataManagementService dataManagementService;
    
    @Autowired
    private DatasourceService datasourceService = null;
    
    @Autowired
    private  FormFactory formFactory;
    
    private String formID;
    
    private List<FieldPropertyEntity> fields;
    
    private String tenantID;
    
    //默认是不查
    private boolean queryMain = true;
    
    public void setQueryMain(boolean queryMain) {
        this.queryMain = queryMain;
    }
 
    @Override
    public void toDo(List<Map<String,Object>> resultList) {
        this.formID = RequestContext.getFormId();
        this.tenantID = RequestContext.getTenantId();
        List<FormFieldEntity> formMainField = null;
        if(queryMain){
            formMainField = this.queryFormMainField(formID, tenantID);
        }else{
            formMainField = this.queryFormSubField(formID, tenantID);
        }
        if(!formMainField.isEmpty())
            formMainField.stream().forEach(fromField ->{
                try {
                    //查询一列主数据
                    List<CodeAndValueBean> cANDv = checkData_1(getDataSourseType(queryFormFieldProperty(formID, tenantID ,fromField.getColumnOrderNum())));
                    if(cANDv != null){
                        resultList.stream() //把结果集按列替换
                        .filter(keyValue ->    // && Objects.equals(keyValue.get(PROCESS_STATE), "10")
                            keyValue.containsKey(fromField.getFieldKey()))
                        .forEach(result ->{
                            StringBuilder name = new StringBuilder();
                            if( !ObjectUtil.empty(result.get(fromField.getFieldKey()))
                                    && result.get(fromField.getFieldKey()).toString().contains(ConstMap.SPLITSTR)){
                                String[] codes = result.get(fromField.getFieldKey()).toString().split(ConstMap.SPLITSTR);
                                for(String cd : codes){
                                    name.append(returnName(cANDv, cd) + ",");
                                }
                                name.deleteCharAt(name.length() - 1);
                            }else{
                                if(result.get(fromField.getFieldKey()) != null){
                                    name.append(returnName(cANDv,result.get(fromField.getFieldKey()).toString()));
                                }
                            }
                            if(!ObjectUtil.empty(result.get(fromField.getFieldKey()))){
                                result.put(fromField.getFieldKey(), name.toString());
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        this.queryMain = true;
    }
    
    //查询主表中相关控件
    public List<FormFieldEntity> queryFormMainField(String formID, String tenantID){
        return dataManagementService.queryFormMainField(formID, tenantID);
    }
    
    //查询非主表中相关控件
    public List<FormFieldEntity> queryFormSubField(String formID, String tenantID){
        return dataManagementService.queryFormSubField(formID, tenantID);
    }
    
    //查询非主表中相关控件
    public List<FormFieldEntity> queryFormAllField(String formID, String tenantID){
        return dataManagementService.queryFormAllField(formID, tenantID);
    }
    
    //查询控件属性
    public List<FieldPropertyEntity> queryFormFieldProperty(String formID, String tenantID, Integer columnOrderNum){
        return dataManagementService.queryFormFieldProperty(formID, tenantID, columnOrderNum);
    }
    
    
    //检查数据格式  如果符合要求,那么就返回name 
    public List<CodeAndValueBean> checkData_1(String datasourseName) throws Exception{
        //控件绑定的数据源 : 主数据、API接口、自定义数据源
        List<CodeAndValueBean> cANDv = null;
        if(datasourseName != null){    
            cANDv = CHOOSE_DATASOURCETYPE.get(datasourseName).goGoGo();
        }
        return cANDv;
    }
    
    //返回需要的name
    @SuppressWarnings("unused")
    public String returnName(List<CodeAndValueBean> cANDv, String code){
        String name;
        if(StringUtils.isEmpty(code))
            return name = "";
        CodeAndValueBean codeAndValueBean = 
                cANDv
                .stream()
                .filter(codeV ->Objects.equals(code,codeV.getCode()))
                .findFirst()
                .orElse(null);
        name = codeAndValueBean != null ? codeAndValueBean.getValue():code;
        return name;
    }
    
    //获取选中数据类型
    public String getDataSourseType(List<FieldPropertyEntity> fields){
        this.fields = fields;
        Map<String, String> result = new HashMap<>();
        fields.stream()
            .filter(propery ->"datasourcetype".equals(propery.getProperty())) 
                .forEach(o ->{
                    result.put(DATASOURCETYPE, o.getValue());
                });
        
        return result.get(DATASOURCETYPE);
    } 
 
}
@FunctionalInterface
interface WhereToGo{
    
    List<CodeAndValueBean> goGoGo() throws IOException;
}