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
package com.changhong.epc.form.service.budget.tool.impl;
 
import com.changhong.autoform.entity.BudgetData;
import com.changhong.autoform.entity.BudgetTitle;
import com.changhong.epc.bean.admin.CorresElField;
import com.changhong.epc.bean.form.FormBaseEntity;
import com.changhong.epc.bean.form.FormKey;
import com.changhong.epc.bean.tenant.system.SystemConfig;
import com.changhong.epc.bean.tenant.system.SystemForm;
import com.changhong.epc.constter.base.Context;
import com.changhong.epc.constter.system.businesscode.BudgetBusinessMeaningCode;
import com.changhong.epc.form.filter.data.impl.FormDataCodeToNameFilter;
import com.changhong.epc.form.mapper.tenant.FormDataMapper;
import com.changhong.epc.form.service.budget.tool.ISelectFormFun;
import com.changhong.epc.form.service.budget.tool.entity.SelectFormResult;
import com.changhong.epc.form.service.field.FormFieldService;
import com.changhong.epc.rely.api.epc.admin.CorresElFieldApi;
import com.changhong.epc.rely.api.epc.tenant.SystemConfigApi;
import com.github.pagehelper.Page;
import com.iemsoft.framework.cloud.core.tools.JSONTool;
import com.iemsoft.framework.cloud.core.tools.ObjectUtil;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;
 
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
 
import static com.changhong.epc.constter.form.extend.FunctionConst.SUPER_ORG_BUDGET_KEY;
 
@Service
public class SuperBudgetSelectForm implements ISelectFormFun, BudgetBusinessMeaningCode {
 
    @Resource
    private FormDataMapper formDataMapper;
 
    @Resource
    private CorresElFieldApi corresElFieldApi;
 
    @Resource
    private SystemConfigApi systemConfigApi;
 
    @Resource
    private FormDataCodeToNameFilter formDataCodeToNameFilter;
 
    @Resource
    private FormFieldService formFieldService;
 
    @Override
    public String getName() {
        return SUPER_ORG_BUDGET_KEY;
    }
 
    public static final List<String> TITLES = Collections.unmodifiableList(Arrays.asList(
            NUMBER_BUDGET
            , BUDGET_TYPE
            , BUDGET_START_DATE
            , BUDGET_END_DATE
            , BUDGET_STATEMENT
    ));
 
    @Override
    public List<BudgetTitle> getTitles(String key) {
        String formId = systemConfigApi.getVal(SystemConfig.ofKey(FORM_INFO, SystemForm.BUDGET_FORM_ID.name()), SystemConfig::getCvalue);
        FormBaseEntity formBaseEntity = formFieldService.selectFormFieldProperty(new FormKey(formId, Context.getToken(), Context.getTenantIdStr()));
        List<BudgetTitle> titles = new ArrayList<>();
        Optional.ofNullable(JSONTool.toObj(formBaseEntity.getFieldset(), Map.class))
                .orElse(Collections.EMPTY_MAP)
                .values()
                .stream()
                .filter(map->map instanceof Map)
                .map(map->((Map) map).get("tag_Attribute"))
                .filter(map->map instanceof Map)
                .forEach(map->{
                    TITLES.stream()
                            .filter(titleKey->Objects.equals(titleKey, ((Map) map).get("alias")))
                            .forEach(titleKey->
                                titles.add(new BudgetTitle(Objects.toString(((Map) map).get("title")), titleKey, ""))
                            );
                });
        return titles;
    }
 
    @Override
    public SelectFormResult getData(BudgetData budgetData) {
        if(ObjectUtil.notEmpty(budgetData.getDataRowNum())){
            return new SelectFormResult(1L,
                    formDataMapper.searchBudget(
                            new ModelMap("dataRowNum", budgetData.getDataRowNum())
                                .addAttribute("formId", budgetData.getFormID())
                    )
            );
        }
        Map<String, Object> data = budgetData.getFormData();
        String budgetStartDate  = Optional.ofNullable(data).map(d->d.get(BUDGET_START_DATE)).map(this::toStr).orElse("");
        String budgetEndDate    = Optional.ofNullable(data).map(d->d.get(BUDGET_END_DATE)).map(this::toStr).orElse("");
        String currency         = Optional.ofNullable(data).map(d->d.get(CURRENCY)).map(this::toStr).orElse("");
        String budgetType       = Optional.ofNullable(data).map(d->d.get(BUDGET_TYPE)).map(this::toStr).orElse("");
        // 验证参数
        if(ObjectUtil.empty(budgetStartDate)
                || ObjectUtil.empty(budgetEndDate)
                || ObjectUtil.empty(currency)
                || ObjectUtil.empty(budgetType)){
            return new SelectFormResult();
        }
        // 是否跨级占用
        String crossLevel = systemConfigApi.getVal(SystemConfig.ofKey("crossLevel", "crossLevel"), SystemConfig::getCvalue);
        boolean isCrossLevel = Objects.equals("C00001", crossLevel);
//        boolean isCrossLevel = Objects.equals("C00001", "C00001");
        List<Map<String, Object>> paramSubData =
                Optional.ofNullable(data)
                .map(d->d.get(BUDGET_SUB_FROM))
                .map(this::to)
                .orElse(new ArrayList<>());
        List<Map<String, Object>> subData =
                paramSubData
                .stream()
                .filter(line->ObjectUtil.notEmpty(toStr(line.get(COST_TYPE)))
                        || ObjectUtil.notEmpty(toStr(line.get(BUDGET_ITEM_DEPARTMENT))))
                .map(line->{
                    Map<String, Object> lineInfo = new HashMap<>();
                    lineInfo.put(COST_TYPE, toStr(line.get(COST_TYPE)));
 
                    lineInfo.put(BUDGET_ITEM_DEPARTMENT,
                            Optional.ofNullable(line.get(BUDGET_ITEM_DEPARTMENT))
                                    .map(this::toStr)
                                    .map(code->{
                                        // 跨级
                                        if(isCrossLevel) {
                                            return code.substring(0, 9);
                                        }
                                        // 逐级
                                        else{
                                            return getParentCode(code);
                                        }
                                    }).orElse("")
                    );
                    lineInfo.put(BUDGET_ITEM_DEPARTMENT+"_length", Optional.ofNullable(line.get(BUDGET_ITEM_DEPARTMENT)).map(this::toStr).map(String::length).orElse(0));
                    lineInfo.put(BUDGET_ITEM_DEPARTMENT+"_crossLevel", isCrossLevel);
 
                    return lineInfo;
                })
                .collect(Collectors.toList());
        Page page = new Page(budgetData.getPageNum(), budgetData.getPageSize());
        // 预算使用code,因为只存了使用code,所以sql中相反匹配
        String occupyCode = corresElFieldApi.getVal(OCCUPY, CorresElField::getMdCode);
//        String occupyCode = "YSCZ000002";
        Map<String, Object> param = new ModelMap("budgetStartDate", budgetStartDate)
                .addAttribute("budgetEndDate", budgetEndDate)
                .addAttribute("currency", currency)
                .addAttribute("occupy", occupyCode)
                .addAttribute("budgetType", budgetType)
                .addAttribute("subData", subData)
                .addAttribute("pageN", page.getStartRow())
                .addAttribute("pageS", page.getEndRow())
                .addAttribute("formId", budgetData.getFormID());
        List<Map<String, Object>> result = formDataMapper.searchSuperBudget(param);
        // 过滤返回值,把选择的子表单参数合并到返回值中
        filterResult(result, paramSubData, isCrossLevel);
        return new SelectFormResult(formDataMapper.searchSuperBudgetCount(param)
                , result);
    }
 
    public static String getParentCode(String code){
        code = code.replaceAll("[1-9]+$", "");
        code = code.replaceAll("0+$", "");
        return code;
    }
 
    public void filterResult(List<Map<String, Object>> result, List<Map<String, Object>> paramSubData, boolean isCrossLevel){
        // {"count":1,"list":[{"number_budget":"B00000773","budget_subfrom":{"budget_superDepartement":" ","C_Type":"51","budget_itemBalance":"500.00","budget_itemMoney":"500.00","budget_project":"","budget_itemDepartment":"010100001","budget_superMoney":"0.00"},"budgetEndDate":"2019-01-05","budgetStartDate":"2019-01-05","budget_type":"F000001"}]}
        List<Map<String, Object>> copyParamSubData = new ArrayList<>(paramSubData);
        result.stream()
              .forEach(line->{
                  // 合并子表单数据
                  magerSub((List<Map<String, Object>>) Optional.ofNullable(line.get(BUDGET_SUB_FROM)).orElse(Collections.EMPTY_LIST)
                          , copyParamSubData
                          , isCrossLevel);
                  // code 转 name
                  formDataCodeToNameFilter.accept(line);
                });
    }
 
    private void magerSub(List<Map<String,Object>> sub, List<Map<String, Object>> paramSubData, boolean isCrossLevel) {
        sub.stream()
                .forEach(line->{
                    String cType            = Optional.ofNullable(line.get(COST_TYPE)).map(Object::toString).orElse("");
                    String budgetDepartment = Optional.ofNullable(line.get(BUDGET_ITEM_DEPARTMENT)).map(Object::toString).orElse("");
                    Map<String, Object> likeSubLine =
                    paramSubData.stream().filter(subParamLine->{
                        String subCType            = Optional.ofNullable(subParamLine.get(COST_TYPE)).map(this::toStr).orElse("");
                        String subBudgetDepartment = Optional.ofNullable(subParamLine.get(BUDGET_ITEM_DEPARTMENT)).map(this::toStr).orElse("");
                        if(!Objects.equals(cType, subCType)){
                            return false;
                        }
                        if(isCrossLevel){
                            return subBudgetDepartment.startsWith(budgetDepartment)
                                    && budgetDepartment.length() <= budgetDepartment.length();
                        }else{
                            return Objects.equals(budgetDepartment, getParentCode(subBudgetDepartment));
                        }
                    }).findFirst().orElse(null);
                    line.put(BUDGET_SUPER_DEPARTEMENT, budgetDepartment);
                    line.put(BUDGET_SUPER_MONEY, line.get(BUDGET_ITEM_BALANCE));
                    line.remove(BUDGET_ITEM_BALANCE);
                    line.remove(BUDGET_ITEM_DEPARTMENT);
                    line.remove(BUDGET_ITEM_MONEY);
                    if(likeSubLine != null){
                        paramSubData.remove(likeSubLine);
                        line.put(BUDGET_ITEM_DEPARTMENT, Optional.ofNullable(likeSubLine.get(BUDGET_ITEM_DEPARTMENT)).map(this::toStr).orElse(""));
                        line.put(BUDGET_ITEM_MONEY, likeSubLine.get(BUDGET_ITEM_MONEY));
                        line.put(BUDGET_ITEM_BALANCE, likeSubLine.get(BUDGET_ITEM_BALANCE));
                    }
                });
    }
 
    public List<Map<String, Object>> to(Object o){
        if(o == null || !(o instanceof List)){
            return Collections.EMPTY_LIST;
        }
        return (List<Map<String, Object>>) o;
    }
 
    public String toStr(Object o){
        if(o instanceof List){
            return ((List)o).stream().findFirst().map(Object::toString).orElse("").toString();
        }else{
            return Objects.toString(o, "");
        }
    }
}