李林
2023-10-07 658d4927d468c47208fd012d9128b09249c07eff
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
package com.chinaztt.mes.warehouse.service.impl;
 
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
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.chinaztt.mes.common.gsm.in.InStorageService;
import com.chinaztt.mes.common.gsm.in.InStorageSingleDeleteModel;
import com.chinaztt.mes.common.gsm.out.OutStorageService;
import com.chinaztt.mes.common.gsm.out.OutStorageSingleDeleteModel;
import com.chinaztt.mes.common.handler.StateMachineHandler;
import com.chinaztt.mes.common.numgen.NumberGenerator;
import com.chinaztt.mes.common.util.StateResult;
import com.chinaztt.mes.warehouse.dto.EscortDTO;
import com.chinaztt.mes.warehouse.dto.EscortDetailDTO;
import com.chinaztt.mes.warehouse.entity.Escort;
import com.chinaztt.mes.warehouse.entity.EscortDetail;
import com.chinaztt.mes.warehouse.entity.Stock;
import com.chinaztt.mes.warehouse.mapper.EscortDetailMapper;
import com.chinaztt.mes.warehouse.mapper.EscortMapper;
import com.chinaztt.mes.warehouse.mapper.JoinStockOrderMapper;
import com.chinaztt.mes.warehouse.service.EscortService;
import com.chinaztt.mes.warehouse.state.escort.EscortStateMachineConfig;
import com.chinaztt.mes.warehouse.state.escort.constant.EscortEvents;
import com.chinaztt.mes.warehouse.state.escort.constant.EscortStates;
import com.chinaztt.mes.warehouse.util.StockUtils;
import com.chinaztt.mes.warehouse.util.TransactionType;
import com.chinaztt.ztt.common.core.util.R;
import lombok.AllArgsConstructor;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.statemachine.config.StateMachineFactory;
import org.springframework.statemachine.persist.StateMachinePersister;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;
 
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
 
/**
 * 押运单主表
 *
 * @author cxf
 * @date 2021-07-23 14:32:00
 */
@Service
@AllArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class EscortServiceImpl extends ServiceImpl<EscortMapper, Escort> implements EscortService {
    private NumberGenerator<Escort> reportNumberGenerator;
    private StateMachineFactory<EscortStates, EscortEvents> escortStateMachineFactory;
    private StateMachinePersister<EscortStates, EscortEvents, Escort> persister;
    private EscortDetailMapper escortDetailMapper;
    private StockUtils stockUtils;
    @Override
    public List<EscortDetailDTO> exportList(QueryWrapper<EscortDetailDTO> gen) {
        return escortDetailMapper.exportList(gen);
    }
 
    @Override
    public List<Escort> getEscortInfoByOrder(List<Long> customerOrderIds) {
        return baseMapper.getEscortInfoByOrder(customerOrderIds);
    }
 
    @Override
    public boolean saveDto(EscortDTO escort) {
        try {// 1.保存主表
            checkEscortNo(escort);
            baseMapper.insert(escort);
            // 2.保存发货明细
            if (CollectionUtil.isNotEmpty(escort.getEscortDetailList())) {
                escort.getEscortDetailList().stream().forEach(escortDetail -> {
                    escortDetail.setEscortId(escort.getId());
                    escortDetailMapper.insert(escortDetail);
                    stockUtils.updateById(escortDetail.getStockId(), BigDecimal.ZERO, escortDetail.getDeliveryQty(), BigDecimal.ZERO, BigDecimal.ZERO, null, TransactionType.ESCORT_RESERVED.getValue());
                });
            }
        } catch (Exception ex) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new RuntimeException(ex.getMessage());
        }
        return true;
    }
 
    @Override
    public boolean updateDtoById(EscortDTO escort) {
        try {// 1.更新主表
            checkEscortNo(escort);
            baseMapper.updateById(escort);
            //修改 可能会新增发货明细 也可能删除  更改发货明细 相应的完成的时候需要判断 是否有gsm入库出库记录 没的话不需要删除 直接调gsm新增
            // 2.先删除后保存发货明细
 
            //找出前台删除的详情数据
            List<EscortDetail> databaseEscortDetails = escortDetailMapper.selectList(Wrappers.<EscortDetail>lambdaQuery()
                    .eq(EscortDetail::getEscortId, escort.getId()));
            List<EscortDetail> deleteEscortDetails = new ArrayList<>();
            List<EscortDetail> updateEscortDetails = new ArrayList<>();
            List<Long> oldEscortDetailIds = escort.getEscortDetailList().stream()
                    .filter(el -> null != el.getId()).map(EscortDetail::getId).collect(Collectors.toList());
 
            databaseEscortDetails.stream().forEach(e -> {
                if (!oldEscortDetailIds.contains(e.getId())) {
                    deleteEscortDetails.add(e);
                }else{
                    updateEscortDetails.add(e);
                }
            });
            if (!deleteEscortDetails.isEmpty()) {
                escortDetailMapper.deleteBatchIds(deleteEscortDetails.stream().map(EscortDetail::getId).collect(Collectors.toList()));
                //取消预留
                for(EscortDetail deleteEscortDetail:deleteEscortDetails){
                    stockUtils.updateById(deleteEscortDetail.getStockId(), BigDecimal.ZERO, deleteEscortDetail.getDeliveryQty().negate(),  BigDecimal.ZERO, BigDecimal.ZERO,null, TransactionType.ESCORT_CANCEL_RESERVED.getValue());
                }
            }
            if (CollectionUtil.isNotEmpty(escort.getEscortDetailList())) {
                escort.getEscortDetailList().forEach(escortDetail -> {
                    if (escortDetail.getId() != null) {
                        escortDetailMapper.activeById(escortDetail.getId());
                        escortDetailMapper.updateById(escortDetail);
                        //更新时,先取消预留,再进行预留
                        Optional<EscortDetail> updateEscortDetailOptional=updateEscortDetails.stream()
                                .filter(el -> escortDetail.getId()== el.getId()).findFirst();
                        if(updateEscortDetailOptional.isPresent()){
                            //存在
                            EscortDetail updateEscortDetail=updateEscortDetailOptional.get();
                            //取消预留
                            stockUtils.updateById(updateEscortDetail.getStockId(), BigDecimal.ZERO, updateEscortDetail.getDeliveryQty().negate(),  BigDecimal.ZERO, BigDecimal.ZERO,null, TransactionType.ESCORT_CANCEL_RESERVED.getValue());
                        }
                        //预留
                        stockUtils.updateById(escortDetail.getStockId(), BigDecimal.ZERO, escortDetail.getDeliveryQty(),  BigDecimal.ZERO, BigDecimal.ZERO,null, TransactionType.ESCORT_RESERVED.getValue());
                    } else {
                        escortDetail.setEscortId(escort.getId());
                        escortDetailMapper.insert(escortDetail);
                        //预留
                        stockUtils.updateById(escortDetail.getStockId(), BigDecimal.ZERO, escortDetail.getDeliveryQty(),  BigDecimal.ZERO, BigDecimal.ZERO,null, TransactionType.ESCORT_RESERVED.getValue());
                    }
                });
            } else {
                baseMapper.deleteById(escort.getId());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return true;
    }
 
    /**
     * 删除GSM的入库记录
     *
     * @param escort
     * @param escortDetail
     */
    public void deleteInStorage(EscortDTO escort, EscortDetail escortDetail) throws Exception {
        //查找发货绑定的客户订单的GSM的合同产品id
        Long id = getBaseMapper().selectCustomerOrder(escort.getCustomerOrderId());
        String inAutoId = String.valueOf(escortDetail.getEscortInAutoId());
        if (!StringUtils.isEmpty(inAutoId)) {
            InStorageService inStorageService = new InStorageService();
            InStorageSingleDeleteModel singleDeleteModel = new InStorageSingleDeleteModel();
            singleDeleteModel.setSalesServiceKey("5CEa1840tB4D8e83E1BA886FE42a60C7");
            singleDeleteModel.setAutoID(inAutoId);
            singleDeleteModel.setContractid(escort.getCustomerOrderNo());
            singleDeleteModel.setContractInfoProductAutoID(String.valueOf(id));
            singleDeleteModel.setEntryPeople(StringUtils.isBlank(escort.getSalesman()) ? "1" : escort.getSalesman());
            singleDeleteModel.setEntryPeopleWorkCode(escort.getSalesmanWorkCode() == null ? "1" : escort.getSalesmanWorkCode());
            singleDeleteModel.setIsJosn("0");
            Document deleteDocument = DocumentHelper.parseText(inStorageService.getInStorageServiceSoap().singleDelete(singleDeleteModel));
            Element deleteRootElement = deleteDocument.getRootElement();
            //错误代码
            String inErrorCode = deleteRootElement.element("miap_header").element("errorcode").getText();
            if (!inErrorCode.equals("0")) {
                //获取错误信息
                String deleteErrorMessage = deleteRootElement.element("miap_header").element("errormsg").getText();
                //抛出错误
                if (!inErrorCode.equals("90") && !inErrorCode.equals("88") && !inErrorCode.equals("89") && !inErrorCode.equals("87")) {
                    throw new RuntimeException("GSM入库记录删除失败,原因:" + deleteErrorMessage + "请手动删除");
                }
            }
        }
    }
 
    private void checkEscortNo(Escort escort) {
        if (StringUtils.isBlank(escort.getEscortNo())) {
            // 1. 自动生成编号
            escort.setEscortNo(reportNumberGenerator.generateNumberWithPrefix(Escort.DIGIT,
                    Escort.PREFIX + DateUtil.format(LocalDateTime.now(), DatePattern.PURE_DATE_PATTERN) + "-", Escort::getEscortNo));
        } else {
            // 2.判断是否重复
            List<Escort> repeatNos = baseMapper.selectList(Wrappers.<Escort>query().lambda().eq(Escort::getEscortNo, escort.getEscortNo()).ne(Escort::getId, escort.getId()));
            if (CollectionUtil.isNotEmpty(repeatNos)) {
                throw new RuntimeException("编号重复");
            }
        }
    }
 
    @Override
    public R<Boolean> changeState(List<Escort> escortList, String event) {
        for (Escort escort : escortList) {
            Message<EscortEvents> message = MessageBuilder.withPayload(EscortEvents.valueOf(event)).setHeader("escort", escort).build();
            StateMachineHandler handler = new StateMachineHandler(escortStateMachineFactory, persister, EscortStateMachineConfig.MACHINE_ID, escort);
            StateResult res = handler.sendEvent(message, escort.getId());
            if (!res.isSuccess()) {
                throw new RuntimeException(res.getMsg());
            }
        }
        return R.ok();
    }
 
    /**
     * 删除GSM的出库记录
     *
     * @param escort
     * @param escortDetail
     */
    public void deleteOutStorage(EscortDTO escort, EscortDetail escortDetail) throws Exception {
        //查找发货绑定的客户订单的GSM的合同行号
        Long id = getBaseMapper().selectCustomerOrder(escort.getCustomerOrderId());
        //发货明细的出库id
        String outAutoId = escortDetail.getEscortOutAutoId().toString();
        if (!StringUtils.isEmpty(outAutoId)) {
            OutStorageService outStorageService = new OutStorageService();
            OutStorageSingleDeleteModel singleDeleteModel = new OutStorageSingleDeleteModel();
            singleDeleteModel.setSalesServiceKey("5CEa1840tB4D8e83E1BA886FE42a60C7");
            singleDeleteModel.setAutoID(outAutoId);
            singleDeleteModel.setContractid(escort.getCustomerOrderNo());
            singleDeleteModel.setContractInfoProductAutoID(String.valueOf(id));
            singleDeleteModel.setEntryPeople(StringUtils.isBlank(escort.getSalesman()) ? "1" : escort.getSalesman());
            singleDeleteModel.setEntryPeopleWorkCode(escort.getSalesmanWorkCode() == null ? "1" : escort.getSalesmanWorkCode());
            singleDeleteModel.setIsJosn("0");
            Document deleteDocument = DocumentHelper.parseText(outStorageService.getOutStorageServiceSoap().singleDelete(singleDeleteModel));
            Element deleteRootElement = deleteDocument.getRootElement();
            //错误代码
            String outErrorCode = deleteRootElement.element("miap_header").element("errorcode").getText();
            if (!outErrorCode.equals("0")) {
                //获取错误信息
                String deleteErrorMessage = deleteRootElement.element("miap_header").element("errormsg").getText();
                //抛出错误
                if (!outErrorCode.equals("90") && !outErrorCode.equals("88") && !outErrorCode.equals("89") && !outErrorCode.equals("87")) {
                    throw new RuntimeException("GSM出库记录删除失败,原因:" + deleteErrorMessage + "请手动删除");
                }
            }
        }
    }
 
    @Override
    public IPage<EscortDetailDTO> getEscortDetailListComplete(Page page, QueryWrapper<EscortDetailDTO> gen) {
        return escortDetailMapper.getEscortDetailListComplete(page, gen);
    }
 
    @Override
    public List<EscortDetailDTO> getEscortDetailList(QueryWrapper<EscortDetailDTO> gen) {
        return escortDetailMapper.getEscortDetailList(gen);
    }
 
 
    @Override
    public boolean delById(Long id) {
        List<EscortDetail> escortDetails = escortDetailMapper.selectList(Wrappers.<EscortDetail>lambdaQuery().eq(EscortDetail::getEscortId, id));
        if (!CollectionUtils.isEmpty(escortDetails)) {
            throw new RuntimeException("存在押运单明细不可删除");
        }
        getBaseMapper().deleteById(id);
        return true;
    }
 
    @Override
    public boolean delDetailsByIds(List<Long> ids) {
        try{
            EscortDetail escortDetail =null;
            for(Long escortDetailId:ids){
                escortDetail = escortDetailMapper.selectById(escortDetailId);
                escortDetailMapper.deleteById(escortDetailId);
                //预留库存需返还
                stockUtils.updateById(escortDetail.getStockId(), BigDecimal.ZERO, escortDetail.getDeliveryQty().negate(),  BigDecimal.ZERO, BigDecimal.ZERO,null, TransactionType.ESCORT_CANCEL_RESERVED.getValue());
            }
 
        } catch (Exception ex) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new RuntimeException(ex.getMessage());
        }
        return true;
    }
 
}