Helius
2022-02-21 f54f8a92c09a2cd76b3bbb796df680215b63ab8a
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
package com.xzx.gc.order.service;
 
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xzx.gc.common.constant.Constants;
import com.xzx.gc.common.constant.RedisKeyConstant;
import com.xzx.gc.common.exception.RestException;
import com.xzx.gc.common.utils.IdUtils;
import com.xzx.gc.common.utils.LocationUtils;
import com.xzx.gc.common.utils.RedisUtil;
import com.xzx.gc.entity.*;
import com.xzx.gc.order.dto.AddJhyOrderDto;
import com.xzx.gc.order.dto.JhyOrderConfirmDto;
import com.xzx.gc.order.dto.JhyOrderConfirmItemsDto;
import com.xzx.gc.order.dto.JhyOrderListDto;
import com.xzx.gc.order.mapper.*;
import com.xzx.gc.order.vo.JhyOrderDetailsVo;
import com.xzx.gc.order.vo.JhyOrderListVo;
import com.xzx.gc.order.vo.JhyStatusCountVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
 
@Slf4j
@Service
@Transactional
public class JhyOrderService {
 
    @Autowired
    private JhyOrderMapper jhyOrderMapper;
 
    @Autowired
    private AddressMapper addressMapper;
 
    @Autowired
    private SysEnvironmentalInfoMapper environmentalInfoMapper;
 
    @Autowired
    private JhyOrderItemsMapper jhyOrderItemsMapper;
 
    @Autowired
    private JhyInfoMapper jhyInfoMapper;
 
    @Autowired
    private AccountMapper accountMapper;
 
    @Autowired
    private ScoreDetailsMapper scoreDetailsMapper;
 
    @Autowired
    private IdUtils idUtils;
 
    @Autowired
    private DistribService distribService;
 
    @Autowired
    private RedisUtil redisUtil;
 
    public void addJhyOrder(AddJhyOrderDto orderDto) {
        JhyInfo jhyInfo = jhyInfoMapper.selectJhyInfoByUserId(orderDto.getUserId());
        if (jhyInfo != null && JhyInfo.CHECK_PASS.equals(jhyInfo.getStatus())) {
            if (JhyInfo.IS_JHY_Y.equals(jhyInfo.getIsJhy())) {
                throw new RestException(-3, "集货员不能下单");
            }
        }
 
        AddressInfo addressInfo = addressMapper.selectByPrimaryKey(orderDto.getAddressId());
 
        List<JhyInfo> jhyInfos = jhyInfoMapper.selectJhyInfoListInAddressRange(addressInfo.getAddressId());
        if (CollUtil.isEmpty(jhyInfos)) {
            throw new RestException(-3, "该区域暂无集物员");
        }
 
        String orderNo = idUtils.generate("JW", 10);
 
        JhyOrder jhyOrder = new JhyOrder();
 
        jhyOrder.setOrderNo(orderNo);
        jhyOrder.setArea(addressInfo.getAddressArea());
 
//        StringBuffer address = new StringBuffer();
//        address.append(addressInfo.getDetailAddress());
//        if (StrUtil.isNotBlank(addressInfo.getTagName())) {
//            address.append(StrUtil.isNotBlank(addressInfo.getHouseName()) ? addressInfo.getHouseName() : "");
//            if (Constants.ADDRESS_TYPE_HOME.equals(addressInfo.getTagName())) {
//                address.append(StrUtil.isNotBlank(addressInfo.getHouseNumber()) ? addressInfo.getHouseNumber() : "");
//                address.append(StrUtil.isNotBlank(addressInfo.getUnitName()) ? addressInfo.getUnitName() : "");
//            }
//        }
 
        List<JhyOrder> addressExist = jhyOrderMapper.selectJhyOrderListByStatus(StrUtil.split("1,2", ','), orderDto.getUserId());
        if (CollUtil.isNotEmpty(addressExist)) {
            for (JhyOrder order : addressExist) {
                String orderAddr = order.getArea()
                        + order.getAddress()
                        + (StrUtil.isEmpty(order.getUnitName())?"":order.getUnitName())
                        + (StrUtil.isEmpty(order.getHouseNumber())?"":order.getHouseNumber());
 
                if (orderAddr.equals(addressInfo.getAddressArea()
                        + addressInfo.getDetailAddress()
                        + (StrUtil.isEmpty(addressInfo.getHouseName())?"":addressInfo.getHouseName())
                        + (StrUtil.isEmpty(addressInfo.getUnitName())?"":addressInfo.getUnitName())
                        + (StrUtil.isEmpty(addressInfo.getHouseNumber())?"":addressInfo.getHouseNumber()))) {
                    throw new RestException(-3, "同一地址仅能有一单在进行中");
                }
            }
        }
 
        jhyOrder.setAddress(addressInfo.getDetailAddress()+(StrUtil.isEmpty(addressInfo.getHouseName())?"":addressInfo.getHouseName()));
        jhyOrder.setUnitName(StrUtil.isEmpty(addressInfo.getUnitName())?"":addressInfo.getUnitName());
        jhyOrder.setHouseNumber(StrUtil.isEmpty(addressInfo.getHouseNumber())?"":addressInfo.getHouseNumber());
        jhyOrder.setUsername(addressInfo.getRelaName());
        jhyOrder.setPhone(addressInfo.getMobilePhone());
        jhyOrder.setLongitude(addressInfo.getLongitude());
        jhyOrder.setLatitude(addressInfo.getLatitude());
        jhyOrder.setReserveDate(orderDto.getReserveDate());
        jhyOrder.setReserveTime(orderDto.getReserveTime());
        jhyOrder.setWeight(orderDto.getWeight());
        jhyOrder.setStatus(JhyOrder.ORDER_STATUS_WAITING);
        jhyOrder.setCreatedTime(new Date());
        jhyOrder.setUserId(orderDto.getUserId());
        jhyOrderMapper.insert(jhyOrder);
 
        long[] typeIds = StrUtil.splitToLong(orderDto.getTypeIds(), ",");
        for (long typeId : typeIds) {
            SysEnvironmentalInfo environmentalInfo = environmentalInfoMapper.selectByPrimaryKey(typeId);
 
            JhyOrderItems item = new JhyOrderItems();
            item.setOrderId(jhyOrder.getId());
            item.setPicture(environmentalInfo.getPicture());
            item.setItemType(typeId);
            item.setTitle(environmentalInfo.getTitle());
            item.setPrice(new BigDecimal(environmentalInfo.getPrice()));
            jhyOrderItemsMapper.insert(item);
        }
    }
 
    public PageInfo<JhyOrderListVo> orderList(JhyOrderListDto orderListDto) {
        PageHelper.startPage(orderListDto.getPageNo(), orderListDto.getPageSize());
        List<JhyOrderListVo> data = jhyOrderMapper.selectJhyOrderList(orderListDto);
        return new PageInfo<>(data);
    }
 
    public JhyOrderDetailsVo orderDetails(Long orderId, String userId) {
        JhyOrder order = jhyOrderMapper.selectByPrimaryKey(orderId);
        List<JhyOrderItems> items = jhyOrderItemsMapper.selectOrderItems(orderId);
 
        BigDecimal total = BigDecimal.ZERO;
        for (JhyOrderItems item : items) {
            item.setPrice(item.getPrice().multiply(BigDecimal.valueOf(Constants.PRICE_SCORE_EXCHANGE)));
            total = total.add(StrUtil.isNotBlank(item.getScore()) ? new BigDecimal(item.getScore()) : BigDecimal.ZERO);
        }
 
        JhyOrderDetailsVo detailsVo = new JhyOrderDetailsVo();
        BeanUtil.copyProperties(order, detailsVo);
 
        detailsVo.setLongitude(order.getLongitude());
        detailsVo.setLatitude(order.getLatitude());
        detailsVo.setAddress(order.getArea() + order.getAddress());
        detailsVo.setUnitName(order.getUnitName());
        detailsVo.setHouseNumber(order.getHouseNumber());
        detailsVo.setTotalPrice(total);
        detailsVo.setItems(items);
        return detailsVo;
    }
 
    public void grabOrder(Long orderId, String userId) {
        JhyInfo jhyInfo = jhyInfoMapper.selectJhyInfoByUserId(userId);
        if (jhyInfo == null || !JhyInfo.CHECK_PASS.equals(jhyInfo.getStatus())) {
            throw new RestException(-3, "不是集货员");
        }
 
        if (JhyInfo.IS_JHY_N.equals(jhyInfo.getIsJhy())) {
            throw new RestException(-3, "暂无法抢单");
        }
 
        JhyOrder order = jhyOrderMapper.selectByPrimaryKey(orderId);
        if (order == null) {
            throw new RestException(-3, "订单不存在");
        }
 
        if (order.getUserId().equals(jhyInfo.getUserId())) {
            throw new RestException(-3, "不能抢自己的单");
        }
 
        order.setJhyId(userId);
        order.setStatus(JhyOrder.ORDER_STATUS_IMG);
        jhyOrderMapper.updateByPrimaryKey(order);
    }
 
    public void cancelOrder(Long orderId, String userId) {
        JhyOrder order = jhyOrderMapper.selectByPrimaryKey(orderId);
 
        if (!userId.equals(order.getUserId()) && !userId.equals(order.getJhyId())) {
            throw new RestException(-3, "无权限操作");
        }
 
        if (userId.equals(order.getJhyId())) {
            order.setStatus(JhyOrder.ORDER_STATUS_WAITING);
        } else {
            order.setStatus(JhyOrder.ORDER_STATUS_CANCEL);
        }
 
        order.setJhyId(null);
        jhyOrderMapper.updateByPrimaryKey(order);
    }
 
    public void confirmOrder(JhyOrderConfirmDto confirmDto) {
        String key = RedisKeyConstant.ORDER_PAY + confirmDto.getOrderId();
        if (redisUtil.setnx(key, "0")) {
            try {
                JhyInfo jhyInfo = jhyInfoMapper.selectJhyInfoByUserId(confirmDto.getUserId());
                if (jhyInfo == null || !JhyInfo.CHECK_PASS.equals(jhyInfo.getStatus())) {
                    throw new RestException(-3, "不是集物员");
                }
 
                jhyOrderItemsMapper.deleteItemsByOrderId(confirmDto.getOrderId());
 
                BigDecimal totalScore = BigDecimal.ZERO;
                for (JhyOrderConfirmItemsDto item : confirmDto.getItems()) {
                    BigDecimal weight = StrUtil.isNotBlank(item.getWeight()) ? new BigDecimal(item.getWeight()) : BigDecimal.ZERO;
                    SysEnvironmentalInfo environmentalInfo = environmentalInfoMapper.selectByPrimaryKey(item.getId());
 
                    JhyOrderItems orderItems = new JhyOrderItems();
                    orderItems.setOrderId(confirmDto.getOrderId());
                    orderItems.setPicture(environmentalInfo.getPicture());
                    orderItems.setItemType(item.getId());
                    orderItems.setTitle(environmentalInfo.getTitle());
                    orderItems.setPrice(new BigDecimal(environmentalInfo.getPrice()));
                    BigDecimal total = orderItems.getPrice().multiply(BigDecimal.valueOf(Constants.PRICE_SCORE_EXCHANGE)).multiply(weight);
                    orderItems.setScore(total.setScale(0, BigDecimal.ROUND_DOWN).toString());
                    orderItems.setWeight(weight);
                    jhyOrderItemsMapper.insert(orderItems);
 
                    totalScore = totalScore.add(total);
                }
 
                JhyOrder order = jhyOrderMapper.selectByPrimaryKey(confirmDto.getOrderId());
                AccountInfo jhyAccount = accountMapper.selectAccountInfoByUserId(order.getJhyId());
                BigDecimal collectScore = StrUtil.isNotBlank(jhyAccount.getCollectScore()) ? new BigDecimal(jhyAccount.getCollectScore()) : BigDecimal.ZERO;
                log.info("===={}======{}====", collectScore, totalScore);
                if (totalScore.compareTo(collectScore) > 0) {
                    throw new RestException(-3, "剩余积分不足");
                }
 
                order.setStatus(JhyOrder.ORDER_STATUS_CONFIRM);
                order.setReceivingTime(new Date());
                jhyOrderMapper.updateByPrimaryKey(order);
 
                BigDecimal jhyScore = StrUtil.isBlank(jhyAccount.getCollectScore()) ? BigDecimal.ZERO : new BigDecimal(jhyAccount.getCollectScore());
                ScoreDetails jhyScoreDetail = new ScoreDetails();
                jhyScoreDetail.setOrderNo(order.getOrderNo());
                jhyScoreDetail.setUserId(order.getJhyId());
                jhyScoreDetail.setType(ScoreDetails.SCORE_TYPE_PAY);
                jhyScoreDetail.setChangeScore(totalScore.negate().setScale( 0, BigDecimal.ROUND_DOWN ));
                jhyScoreDetail.setOriginalScore(jhyScore.setScale( 0, BigDecimal.ROUND_DOWN ));
                jhyScoreDetail.setCurrentScore(jhyScore.subtract(totalScore).setScale( 0, BigDecimal.ROUND_DOWN ));
                jhyScoreDetail.setCreatedTime(new Date());
                scoreDetailsMapper.insert(jhyScoreDetail);
 
                jhyAccount.setCollectScore(jhyScore.subtract(totalScore).setScale( 0, BigDecimal.ROUND_DOWN ).toString());
                accountMapper.updateByPrimaryKey(jhyAccount);
 
                AccountInfo userAccount = accountMapper.selectAccountInfoByUserId(order.getUserId());
                BigDecimal userScore = StrUtil.isBlank(userAccount.getCollectScore()) ? BigDecimal.ZERO : new BigDecimal(userAccount.getCollectScore());
                ScoreDetails userScoreDetail = new ScoreDetails();
                userScoreDetail.setOrderNo(order.getOrderNo());
        //        userScoreDetail.setUserId(order.getJhyId());
                userScoreDetail.setUserId(order.getUserId());
                userScoreDetail.setType(ScoreDetails.SCORE_TYPE_EXCHANGE);
                userScoreDetail.setChangeScore(totalScore.setScale( 0, BigDecimal.ROUND_DOWN ));
                userScoreDetail.setOriginalScore(userScore.setScale( 0, BigDecimal.ROUND_DOWN ));
                userScoreDetail.setCurrentScore(userScore.add(totalScore).setScale( 0, BigDecimal.ROUND_DOWN ));
                userScoreDetail.setCreatedTime(new Date());
                scoreDetailsMapper.insert(userScoreDetail);
 
                userAccount.setCollectScore(userScore.add(totalScore).setScale( 0, BigDecimal.ROUND_DOWN ).toString());
                accountMapper.updateByPrimaryKey(userAccount);
 
                // 团长返利
                distribService.distribRecord(order.getId(), order.getUserId());
                // 推荐返利
                distribService.inviteAddOrderScore(order.getUserId(), order.getId().toString());
            } catch (RestException e) {
                throw new RestException(e.getMessage());
            } catch (Exception e) {
                log.error("异常", e);
                throw new RestException("支付失败");
            } finally {
                redisUtil.del(key);
            }
        } else {
            throw new RestException("支付中");
        }
 
    }
 
    public Map<Integer, Integer> orderStatusCount(Integer type, String userId) {
        List<JhyStatusCountVo> count = jhyOrderMapper.selectOrderStatusCount(type, userId);
 
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 1; i < 6; i++) {
            if (CollUtil.isNotEmpty(count)) {
                boolean flag = false;
                for (JhyStatusCountVo jhyStatusCountVo : count) {
                    if (i == jhyStatusCountVo.getStatus()) {
                        map.put(i, jhyStatusCountVo.getCnt());
                        flag = true;
                        break;
                    }
                }
 
                if (flag) {
                    continue;
                }
            }
 
            map.put(i, 0);
        }
 
        return map;
    }
 
    public List<JhyInfo> findJhyInfoInRange(Long addressId) {
        return jhyInfoMapper.selectJhyInfoListInAddressRange(addressId);
    }
}