李林
2024-04-09 217f2eb09985a80f5d972a6fa1205806756711e1
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
package com.yuanchu.mom.service.impl;
 
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import com.deepoove.poi.data.*;
import com.deepoove.poi.data.style.TableStyle;
import com.deepoove.poi.render.Render;
import com.spire.doc.Table;
import com.yuanchu.mom.common.GetLook;
import com.yuanchu.mom.common.PrintChina;
import com.yuanchu.mom.dto.InsOrderPlanDTO;
import com.yuanchu.mom.dto.SampleProductDto;
import com.yuanchu.mom.mapper.*;
import com.yuanchu.mom.pojo.*;
import com.yuanchu.mom.exception.ErrorException;
import com.yuanchu.mom.service.InsOrderPlanService;
import com.yuanchu.mom.service.InsOrderService;
import com.yuanchu.mom.service.StandardTemplateService;
import com.yuanchu.mom.utils.GiveCode;
import com.yuanchu.mom.utils.QueryWrappers;
import com.yuanchu.mom.vo.InsOrderPlanVO;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
 
import javax.annotation.Resource;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
 
/**
 * 检验任务-业务实现层
 */
@Service
//@AllArgsConstructor
public class InsOrderPlanServiceImpl extends ServiceImpl<InsOrderMapper, InsOrder> implements InsOrderPlanService {
 
    @Resource
    private InsSampleMapper insSampleMapper;
    @Resource
    private InsSampleUserMapper insSampleUserMapper;
    @Resource
    private GetLook getLook;
    @Resource
    private InsOrderMapper insOrderMapper;
    @Resource
    private InsOrderService insOrderService;
    @Resource
    private StandardTemplateService standardTemplateService;
    @Resource
    private InsOrderStateMapper insOrderStateMapper;
    @Resource
    private InsProductMapper insProductMapper;
 
    @Value("${wordUrl}")
    private String wordUrl;
 
    @Resource
    private GiveCode giveCode;
 
    @Resource
    private InsReportMapper insReportMapper;
 
    @Resource
    private InsProductResultMapper insProductResultMapper;
 
    @Override
    public Map<String, Object> selectInsOrderPlanList(Page page, InsOrderPlanDTO insOrderPlanDTO) {
        Map<String, Object> map = new HashMap<>();
        map.put("head", PrintChina.printChina(InsOrderPlanVO.class));
        Map<String, Integer> map1 = getLook.selectPowerByMethodAndUserId(null);
        Integer userId = map1.get("userId");
        if (ObjectUtil.isNotEmpty(insOrderPlanDTO.getUserId())) {
            insOrderPlanDTO.setUserId(userId.longValue());
        }
        IPage<InsOrderPlanVO> insOrderPage = insSampleMapper.findInsSampleAndOrder(page, QueryWrappers.queryWrappers(insOrderPlanDTO), userId);
        map.put("body", insOrderPage);
        return map;
    }
 
    @Override
    public boolean claimInsOrderPlan(InsOrderPlanDTO entity) {
        if (Objects.isNull(entity)) {
            return false;
        }
        Map<String, Integer> map1 = getLook.selectPowerByMethodAndUserId(null);
        Integer userId = map1.get("userId");
        InsSampleUser insSampleUser = new InsSampleUser(entity.getInsSampleId().intValue(), userId, 1);
        return insSampleUserMapper.insert(insSampleUser) > 0;
    }
 
    @Override
    public Map<String, Object> doInsOrder(Integer id, String laboratory) {
        InsOrder insOrder = new InsOrder();
        insOrder.setId(id);
        insOrder.setInsState(1);
        InsOrder order = insOrderMapper.selectById(id);
        if (BeanUtil.isEmpty(order.getInsTime())) {
            insOrder.setInsTime(LocalDateTime.now());
            insOrderMapper.updateById(insOrder);
        }
        insOrderStateMapper.update(null, Wrappers.<InsOrderState>lambdaUpdate().eq(InsOrderState::getInsOrderId, id).eq(InsOrderState::getLaboratory, laboratory).set(InsOrderState::getInsTime, LocalDateTime.now()).set(InsOrderState::getInsState, 1));
        Map<String, Object> map = insOrderService.getInsOrderAndSample(id, laboratory);
        Set<Integer> set = new HashSet<>();
        Map<Integer, String> map2 = new HashMap<>();
        List<SampleProductDto> list = JSON.parseArray(JSON.toJSONString(map.get("sampleProduct")), SampleProductDto.class);
        for (SampleProductDto samples : list) {
            if (BeanUtil.isEmpty(samples.getInsProduct())) continue;
            getTemplateThing(set, map2, samples);
        }
        map.put("sampleProduct", list);
        return map;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveInsContext(Map<String, Object> insContext) {
        Integer userId = getLook.selectPowerByMethodAndUserId(null).get("userId");
        CompletableFuture.supplyAsync(() -> {
            AtomicInteger count = new AtomicInteger();
            insContext.forEach((k, v) -> {
                JSONObject jo = JSON.parseObject(JSON.toJSONString(v));
                InsProduct insProduct = new InsProduct();
                insProduct.setId(Integer.parseInt(k));
                InsProductResult result = insProductResultMapper.selectOne(Wrappers.<InsProductResult>lambdaQuery().eq(InsProductResult::getInsProductId, insProduct.getId()));
                if (BeanUtil.isEmpty(result)) {
                    result = new InsProductResult();
                }
                result.setInsProductId(Integer.parseInt(k));
                JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(jo.get("insValue")));
                List<Map<String, Object>> iv = new ArrayList<>();
                for (Object o : jsonArray) {
                    JSONObject insValue = JSON.parseObject(JSON.toJSONString(o));
                    Map<String, Object> map = new HashMap<>();
                    map.put("v", JSON.parseObject(JSON.toJSONString(insValue.get("v"))).get("v"));
                    if ((insValue.get("u") == null || insValue.get("u").equals("")) && StrUtil.isNotEmpty(JSON.parseObject(JSON.toJSONString(insValue.get("v"))).get("v").toString())) {
                        map.put("u", userId);
                    }else {
                        map.put("u", insValue.get("u"));
                    }
                    iv.add(map);
                }
                result.setInsValue(JSON.toJSONString(iv));
                JSONArray jsonArray2 = JSON.parseArray(JSON.toJSONString(jo.get("comValue")));
                List<Map<String, Object>> cv = new ArrayList<>();
                for (Object o : jsonArray2) {
                    JSONObject comValue = JSON.parseObject(JSON.toJSONString(o));
                    Map<String, Object> map = new HashMap<>();
                    map.put("v", JSON.parseObject(JSON.toJSONString(comValue.get("v"))).get("v"));
                    cv.add(map);
                }
                result.setComValue(JSON.toJSONString(cv));
                JSONObject resValue = JSON.parseObject(JSON.toJSONString(jo.get("resValue")));
                insProduct.setLastValue(JSON.parseObject(JSON.toJSONString(resValue.get("v"))).get("v") + "");
                JSONObject equipValue = JSON.parseObject(JSON.toJSONString(jo.get("equipValue")));
                try {
                    result.setEquipValue(JSON.parseObject(JSON.toJSONString(equipValue.get("v"))).get("v") + "");
                }catch (Exception ignored){
                    result.setEquipValue(null);
                }
                JSONObject insResult = JSON.parseObject(JSON.toJSONString(jo.get("insResult")));
                insProduct.setInsResult(Integer.parseInt(JSON.parseObject(JSON.toJSONString(insResult.get("v"))).get("v") + ""));
                if (BeanUtil.isEmpty(result.getId())) {
                    result.setCreateUser(userId);
                    result.setUpdateUser(userId);
                    insProductResultMapper.insert(result);
                } else {
                    result.setUpdateUser(userId);
                    result.setUpdateTime(LocalDateTime.now());
                    insProductResultMapper.updateById(result);
                }
                insProduct.setUpdateUser(userId);
                insProductMapper.updateById(insProduct);
                if(count.get() == 0){
                    InsSample insSample = insSampleMapper.selectById(insProductMapper.selectById(insProduct.getId()).getInsSampleId());
                    insSample.setInsState(1);
                    count.addAndGet(1);
                }
            });
            return null;
        }).thenAccept(res -> {
        }).exceptionally(e -> {
            e.printStackTrace();
            return null;
        });
    }
 
    @Override
    public int upPlanUser(Integer userId, Integer orderId) {
        InsSampleUser insSampleUser = new InsSampleUser();
        insSampleUser.setUserId(userId);
        insSampleUser.setInsSampleId(orderId);
        insSampleUser.setState(0);
        return insSampleUserMapper.insert(insSampleUser);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int verifyPlan(Integer orderId, String laboratory, Integer type, String tell) {
        Integer num = (type == 1 ? 5 : 4);
        insOrderStateMapper.update(null, Wrappers.<InsOrderState>lambdaUpdate().eq(InsOrderState::getInsOrderId, orderId).eq(InsOrderState::getLaboratory, laboratory).set(InsOrderState::getInsTime, LocalDateTime.now()).set(InsOrderState::getInsState, num).set(InsOrderState::getVerifyTell, tell).set(InsOrderState::getVerifyUser, getLook.selectPowerByMethodAndUserId(null).get("userId")));
        List<InsOrderState> insOrderStates = insOrderStateMapper.selectList(Wrappers.<InsOrderState>lambdaQuery().eq(InsOrderState::getInsOrderId, orderId));
        long count = insOrderStates.stream().filter(a -> a.getInsState() == 5).count();
        if (count == insOrderStates.size() && num == 5) {
            InsOrder insOrder = insOrderMapper.selectById(orderId);
            Map<String, String> user = insProductMapper.selectUserById(insOrder.getUserId());
            List<SampleProductDto> samples = insSampleMapper.selectSampleProductListByOrderId(orderId);
            Set<Integer> set = new HashSet<>();
            Map<Integer, String> map2 = new HashMap<>();
            samples.forEach(a->{
                getTemplateThing(set, map2, a);
                TableRenderData tableRenderData = new TableRenderData();
                TableStyle tableStyle = new TableStyle();
                tableStyle.setWidth("14.63");
                tableRenderData.setTableStyle(tableStyle);
                a.getInsProduct().forEach(b->{
                    System.out.println(b.getTemplate());
                    System.out.println(b.getStyle());
                    RowRenderData rowRenderData = new RowRenderData();
                    CellRenderData cellRenderData = new CellRenderData();
                    for (JSONObject jo1 : b.getTemplate()) {
                        ParagraphRenderData paragraphRenderData = new ParagraphRenderData();
                        List<RenderData> contents = new ArrayList<>();
                        /*if(Integer.parseInt(jo1.get("r")+"") == r){
                            if(Integer.parseInt(jo1.get("r")+"") == c){
                                JSONObject jo2 = JSONObject.parseObject(JSONObject.toJSONString(jo1.get("v")));
                                TextRenderData textRenderData = new TextRenderData();
                                textRenderData.setText(jo2.get("v")+"");
                                contents.add(textRenderData);
                                paragraphRenderData.setContents(contents);
                            }
                        }else if (Integer.parseInt(jo1.get("r")+"") > r){
                        }*/
                    }
                });
            });
            InsReport insReport = new InsReport();
            insReport.setCode(giveCode.giveCode("JCZX/TX-", "ins_report", "-", "yyMMdd"));
            insReport.setInsOrderId(orderId);
            String url;
            try {
                url = ResourceUtils.getURL("classpath:static/report-template.docx").getPath();
            } catch (FileNotFoundException e) {
                throw new ErrorException("找不到模板文件");
            }
            XWPFTemplate template = XWPFTemplate.compile(url).render(
                    new HashMap<String, Object>() {{
                        put("order", insOrder);
                        put("report", insReport);
                        put("user", user);
                        put("samples", samples);
                        put("sampleSize", samples.size() + samples.get(0).getUnit());
                    }});
            try {
                String name = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yy_MM_dd_HH_mm_ss")) + ".docx";
                template.writeAndClose(Files.newOutputStream(Paths.get(wordUrl + "/" + name)));
                insReport.setUrl("/word/"+ name);
                insReportMapper.insert(insReport);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return 1;
    }
 
    private void getTemplateThing(Set<Integer> set, Map<Integer, String> map2, SampleProductDto a) {
        for (InsProduct product : a.getInsProduct()) {
            if (product.getTemplateId() == null) {
                product.setTemplate(new ArrayList<>());
                continue;
            }
            if (set.add(product.getTemplateId())) {
                map2.put(product.getTemplateId(), standardTemplateService.getStandTempThingById(product.getTemplateId()) + "");
            }
            String thing = map2.get(product.getTemplateId());
            if (StrUtil.isNotEmpty(thing)) {
                JSONObject sheet = JSON.parseObject(JSON.toJSONString(JSON.parseArray(JSON.toJSONString(JSON.parseObject(thing).get("data"))).get(0)));
                JSONObject config = JSON.parseObject(JSON.toJSONString(sheet.get("config")));
                List<JSONObject> cellData = JSON.parseArray(JSON.toJSONString(sheet.get("celldata")), JSONObject.class);
                List<JSONObject> tableData = new ArrayList<>();
                Map<String, Object> style = new HashMap<>();
                style.put("rowlen", config.get("rowlen"));
                style.put("columnlen", config.get("columnlen"));
                int r = -1;
                if (BeanUtil.isNotEmpty(cellData)) {
                    for (JSONObject o : cellData) {
                        JSONObject v = JSON.parseObject(JSON.toJSONString(o.get("v")));
                        if (BeanUtil.isNotEmpty(v.get("ps"))) {
                            JSONObject ps = JSON.parseObject(JSON.toJSONString(v.get("ps")));
                            if (ps.get("value").equals("检验项") && v.get("v").equals(product.getInspectionItem())) {
                                tableData.add(o);
                                r = Integer.parseInt(o.get("r") + "");
                                continue;
                            }
                        }
                        if (tableData.size() > 0) {
                            if ((Integer.parseInt(o.get("r") + "") == r + 1 || Integer.parseInt(o.get("r") + "") == r) && !(o.get("v") + "").equals("{\"ht\":\"0\"}")) {
                                r = Integer.parseInt(o.get("r") + "");
                                tableData.add(o);
                            } else {
                                break;
                            }
                        }
                    }
                }
                product.setTemplate(tableData);
                product.setStyle(style);
            }
        }
    }
 
    @Override
    public int submitPlan(Integer orderId, String laboratory) {
        List<InsSample> insSamples = insSampleMapper.selectList(Wrappers.<InsSample>lambdaQuery().eq(InsSample::getInsOrderId, orderId).select(InsSample::getId));
        List<Integer> ids = insSamples.stream().map(a -> a.getId()).collect(Collectors.toList());
        List<InsProduct> insProducts = insProductMapper.selectList(Wrappers.<InsProduct>lambdaQuery().in(InsProduct::getInsSampleId, ids).eq(InsProduct::getSonLaboratory, laboratory).isNotNull(InsProduct::getInsResult));
        if (insProducts.size() == 0) {
            return 0;
        }
        insOrderStateMapper.update(null, Wrappers.<InsOrderState>lambdaUpdate().eq(InsOrderState::getInsOrderId, orderId).eq(InsOrderState::getLaboratory, laboratory).set(InsOrderState::getInsTime, LocalDateTime.now()).set(InsOrderState::getInsState, 3));
        return 1;
    }
}