xiaoyong931011
2021-07-02 abf323cc9a96877ead8aa5e5caacff8c75e4d2e7
gc-shop/src/main/java/com/xzx/gc/shop/service/OrderService.java
@@ -3,19 +3,19 @@
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xzx.gc.common.utils.StringUtils;
import com.xzx.gc.common.constant.Constants;
import com.xzx.gc.common.exception.RestException;
import com.xzx.gc.common.utils.IdUtils;
import com.xzx.gc.entity.*;
import com.xzx.gc.shop.dto.AddGoodsOrderDto;
import com.xzx.gc.shop.dto.DeliverGoodsDto;
import com.xzx.gc.shop.dto.InsureOrderDto;
import com.xzx.gc.shop.dto.QueryOrderListDto;
import com.xzx.gc.shop.dto.*;
import com.xzx.gc.shop.mapper.*;
import com.xzx.gc.shop.vo.ExpressInfoVo;
import com.xzx.gc.shop.vo.QueryOrderListVo;
import com.xzx.gc.shop.vo.ViewOrderVo;
import com.xzx.gc.shop.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@@ -23,10 +23,8 @@
import tk.mybatis.mapper.entity.Example;
import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.math.BigDecimal;
import java.util.*;
@Service
@Transactional
@@ -56,15 +54,50 @@
    @Autowired
    private ScoreGoodsMapper scoreGoodsMapper;
    @Autowired
    private ScoreDetailsMapper scoreDetailsMapper;
    @Autowired
    private IdUtils idUtils;
    public Map<String, Object> queryOrderList(QueryOrderListDto model) {
        String name = model.getName();
        String name = StrUtil.isEmpty(model.getName())?model.getName():StringUtils.encode(model.getName());
        String orderNo = model.getOrderNo();
        Integer status = model.getStatus() == null ? 0 : model.getStatus();
        Date createdTimeStart = model.getCreatedTimeStart();
        Date createdTimeEnd = model.getCreatedTimeEnd();
        PageHelper.startPage(model.getPage(), model.getLimit());
        List<QueryOrderListVo> maps = scoreOrderMapper.queryOrderList(name,orderNo,status,createdTimeStart,createdTimeEnd);
        if(CollUtil.isNotEmpty(maps)){
            for(QueryOrderListVo queryOrderListVo : maps){
                String decode = StringUtils.decode(queryOrderListVo.getName());
                queryOrderListVo.setName(decode);
                BigDecimal totalPrice = new BigDecimal(StrUtil.isEmpty(queryOrderListVo.getTotalPrice()) ? "0" : queryOrderListVo.getTotalPrice())
                        .setScale( 2, BigDecimal.ROUND_DOWN );
                queryOrderListVo.setTotalPrice(totalPrice.toString());
                Long id = queryOrderListVo.getId();
                Example example = new Example(ScoreOrderDetails.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("orderId",id);
                List<ScoreOrderDetails> scoreOrderDetails = scoreOrderDetailsMapper.selectByExample(example);
                if(CollUtil.isNotEmpty(scoreOrderDetails)){
                    queryOrderListVo.setOrderDetails(scoreOrderDetails);
//                    StringBuffer stringBuffer = new StringBuffer();
//                    for(ScoreOrderDetails scoreOrderDetail : scoreOrderDetails){
//                        String goodsName = scoreOrderDetail.getGoodsName();
//                        BigDecimal unitPrice = scoreOrderDetail.getUnitPrice();
//                        String sku = scoreOrderDetail.getSku();
//                        Integer cnt = scoreOrderDetail.getCnt();
//                        BigDecimal totalPriceOrderDetail = scoreOrderDetail.getTotalPrice();
//                        stringBuffer = stringBuffer.append(goodsName+"(")
//                                .append("规格:"+sku+","+unitPrice.setScale( 2, BigDecimal.ROUND_DOWN ).toString()+"*"+cnt.toString()+",")
//                                .append("总价:"+totalPriceOrderDetail.setScale( 2, BigDecimal.ROUND_DOWN ).toString()+";)");
//                    }
//                    queryOrderListVo.setOrderDetails(stringBuffer.toString());
                }
            }
        }
        PageInfo pageInfo = new PageInfo(maps);
        int count = Convert.toInt(pageInfo.getTotal());
        Map<String, Object> map = new HashMap<>();
@@ -86,19 +119,23 @@
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            viewOrderVo = objectMapper.convertValue(scoreOrder, ViewOrderVo.class);
//            String voucherImg = viewOrderVo.getVoucherImg();
            String voucherImg = scoreOrder.getVoucherImg();
            List<String> lists = StrUtil.splitTrim(voucherImg, ",");
            viewOrderVo.setVoucherImgs(lists);
            //2-待收货3-已收货4-已完成5-已评价,获取物流信息
            Integer status = scoreOrder.getStatus() == null ? 0:scoreOrder.getStatus();
            if(ScoreOrder.STATUS_DOING == status
                    || ScoreOrder.STATUS_DONE == status
                    || ScoreOrder.STATUS_ON == status
                    || ScoreOrder.STATUS_EVALUATE == status){
//            if(ScoreOrder.STATUS_DOING == status
//                    || ScoreOrder.STATUS_DONE == status
//                    || ScoreOrder.STATUS_ON == status
//                    || ScoreOrder.STATUS_EVALUATE == status){
                Example exampleExpress = new Example(ScoreExpressInfo.class);
                Example.Criteria criteriaExpress = exampleExpress.createCriteria();
                criteriaExpress.andEqualTo("orderId",id);
                ScoreExpressInfo scoreExpressInfo = scoreExpressInfoMapper.selectOneByExample(exampleExpress);
                ExpressInfoVo expressInfoVo = objectMapper.convertValue(scoreExpressInfo, ExpressInfoVo.class);
                viewOrderVo.setExpressInfoVo(expressInfoVo);
            }
//            }
            //订单详情
            Example exampleDetails = new Example(ScoreOrderDetails.class);
            Example.Criteria criteriaDetails = exampleDetails.createCriteria();
@@ -133,13 +170,15 @@
            scoreOrder.setStatus(ScoreOrder.STATUS_ON);
            scoreOrderMapper.updateByPrimaryKeySelective(scoreOrder);
        }
        return scoreExpressInfo.getId();
        return id;
    }
    public Long insureOrder(InsureOrderDto model) {
        ScoreOrder scoreOrder = new ScoreOrder();
        scoreOrder.setId(model.getId());
        scoreOrder.setVoucherImg(model.getVoucherImgs().toString());
//        scoreOrder.setStatus(ScoreOrder.STATUS_DONE);
        scoreOrder.setIsFinish(ScoreOrder.ISFINISH_YES);
        scoreOrder.setVoucherImg(CollUtil.join(model.getVoucherImgs(),","));
        scoreOrderMapper.updateByPrimaryKeySelective(scoreOrder);
        return scoreOrder.getId();
    }
@@ -148,9 +187,242 @@
        ScoreGoodsStyle style = scoreGoodsStyleMapper.selectByPrimaryKey(addGoodsOrderDto.getStyleId());
        ScoreGoodsSku sku = scoreGoodsSkuMapper.selectByPrimaryKey(addGoodsOrderDto.getSkuId());
        ScoreGoods goods = scoreGoodsMapper.selectByPrimaryKey(style.getGoodsId());
        if (goods == null || ScoreGoods.ISSALE_NO.equals(goods.getIsSale())) {
            throw new RestException(-3, "商品不存在或已下架");
        }
        if (ScoreGoods.ISQG_YES.equals(goods.getIsQg())) {
            if (new Date().before(goods.getQgStartTime())) {
                throw new RestException(-3, "抢购未开始");
            }
            if (new Date().after(goods.getQgEndTime())) {
                throw new RestException(-3, "抢购已结束");
            }
        }
        if (addGoodsOrderDto.getCnt() > sku.getStock()) {
            throw new RestException(-3, "库存不足");
        }
        AccountInfo accountInfo = accountInfoMapper.selectAccountInfoByUserId(addGoodsOrderDto.getUserId());
        if (accountInfo.getCollectScore() == null) {
            throw new RestException(-3, "积分不足");
        }
        BigDecimal totalPrice = sku.getPresentPrice().multiply(BigDecimal.valueOf(addGoodsOrderDto.getCnt()));
        BigDecimal score = new BigDecimal(accountInfo.getCollectScore());
        if (score.compareTo(totalPrice) < 0) {
            throw new RestException(-3, "积分不足");
        }
        ScoreOrder order = new ScoreOrder();
        order.setOrderNo(idUtils.generate("JF", 9));
        order.setCnt(addGoodsOrderDto.getCnt());
        order.setTotalPrice(totalPrice);
        order.setCreatedTime(new Date());
        order.setUserId(addGoodsOrderDto.getUserId());
        order.setStatus(ScoreOrder.STATUS_READY);
        order.setGoodsName(goods.getName());
        order.setRemark(addGoodsOrderDto.getRemark());
        scoreOrderMapper.insert(order);
        ScoreOrderDetails orderDetails = new ScoreOrderDetails();
        orderDetails.setGoodsName(goods.getName());
        orderDetails.setStyle(style.getName());
        orderDetails.setSku(sku.getName());
        orderDetails.setOrderId(order.getId());
        orderDetails.setCnt(addGoodsOrderDto.getCnt());
        orderDetails.setTotalPrice(totalPrice);
        orderDetails.setUnitPrice(sku.getPresentPrice());
        orderDetails.setGoodsId(goods.getId());
        orderDetails.setThumb(goods.getThumb());
        scoreOrderDetailsMapper.insert(orderDetails);
        AddressInfo addressInfo = addressInfoMapper.selectByPrimaryKey(addGoodsOrderDto.getAddressId());
        AccountInfo accountInfo = accountInfoMapper.selectAccountInfoByUserId(addGoodsOrderDto.getUserId());
        ScoreExpressInfo expressInfo = new ScoreExpressInfo();
        expressInfo.setUsername(addressInfo.getRelaName());
        expressInfo.setPhone(addressInfo.getMobilePhone());
        expressInfo.setUserId(addressInfo.getUserId());
        expressInfo.setOrderId(order.getId());
        StringBuffer address = new StringBuffer();
        address.append(addressInfo.getAddressArea());
        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() : "");
            }
        }
        expressInfo.setAddress(address.toString());
        expressInfo.setCreatedTime(new Date());
        scoreExpressInfoMapper.insert(expressInfo);
        BigDecimal remianScore = score.subtract(totalPrice).setScale(0, BigDecimal.ROUND_DOWN);
        accountInfo.setCollectScore(remianScore.toString());
        accountInfoMapper.updateByPrimaryKey(accountInfo);
        ScoreDetails scoreDetails = new ScoreDetails();
        scoreDetails.setOrderNo(order.getOrderNo());
        scoreDetails.setUserId(addGoodsOrderDto.getUserId());
        scoreDetails.setType(ScoreDetails.SCORE_TYPE_SHOPPING);
        scoreDetails.setOriginalScore(score);
        scoreDetails.setCurrentScore(remianScore);
        scoreDetails.setChangeScore(totalPrice);
        scoreDetails.setCreatedTime(new Date());
        scoreDetailsMapper.insert(scoreDetails);
        sku.setStock(sku.getStock() - addGoodsOrderDto.getCnt());
        sku.setQuantity(sku.getQuantity() - addGoodsOrderDto.getCnt());
        scoreGoodsSkuMapper.updateByPrimaryKey(sku);
    }
    public Long cancelOrder(CancelOrderDto model) {
        /**
         * 更新订单状态
         * 增加一条取消订单积分退回的记录
         * 查询所有的订单详情,依次库存增加,销量减少
         */
        ScoreOrder scoreOrder = new ScoreOrder();
        scoreOrder.setId(model.getId());
        scoreOrder.setStatus(ScoreOrder.STATUS_CANCEL);
        scoreOrderMapper.updateByPrimaryKeySelective(scoreOrder);
        ScoreOrder order = scoreOrderMapper.selectByPrimaryKey(model.getId());
        Example exampleDetails = new Example(ScoreDetails.class);
        Example.Criteria criteriaDetails = exampleDetails.createCriteria();
        criteriaDetails.andEqualTo("orderNo",order.getOrderNo());
        criteriaDetails.andEqualTo("userId",order.getUserId());
        criteriaDetails.andEqualTo("type",ScoreDetails.SCORE_TYPE_SHOPPING);
        ScoreDetails scoreDetails = scoreDetailsMapper.selectOneByExample(exampleDetails);
        if(ObjectUtil.isNotEmpty(scoreDetails)){
            AccountInfo accountInfo = accountInfoMapper.selectAccountInfoByUserId(order.getUserId());
            BigDecimal score = new BigDecimal(accountInfo.getCollectScore());
            BigDecimal remianScore = score.add(scoreDetails.getChangeScore()).setScale(0, BigDecimal.ROUND_DOWN);
            ScoreDetails scoreDetailsRet = new ScoreDetails();
            scoreDetailsRet.setOrderNo(scoreDetails.getOrderNo());
            scoreDetailsRet.setUserId(scoreDetails.getUserId());
            scoreDetailsRet.setType(ScoreDetails.SCORE_TYPE_SHOPPING_RETURN);
            scoreDetailsRet.setOriginalScore(score);
            scoreDetailsRet.setCurrentScore(remianScore);
            scoreDetailsRet.setChangeScore(scoreDetails.getChangeScore());
            scoreDetailsRet.setCreatedTime(new Date());
            scoreDetailsMapper.insert(scoreDetailsRet);
        }
        Example exampleScoreOrderDetails = new Example(ScoreOrderDetails.class);
        Example.Criteria criteriaScoreOrderDetails = exampleScoreOrderDetails.createCriteria();
        criteriaScoreOrderDetails.andEqualTo("orderId",order.getId());
        List<ScoreOrderDetails> scoreOrderDetails = scoreOrderDetailsMapper.selectByExample(exampleScoreOrderDetails);
        if(CollUtil.isNotEmpty(scoreOrderDetails)){
            for(ScoreOrderDetails scoreOrderDetail : scoreOrderDetails){
                ScoreGoodsSku scoreGoodsSku = scoreGoodsSkuMapper.selectByPrimaryKey(scoreOrderDetail.getSkuId());
                if(ObjectUtil.isNotEmpty(scoreGoodsSku)){
                    scoreGoodsSku.setStock(scoreGoodsSku.getStock() + scoreOrderDetail.getCnt());
                    scoreGoodsSku.setQuantity(scoreGoodsSku.getQuantity() - scoreOrderDetail.getCnt());
                    scoreGoodsSkuMapper.updateByPrimaryKey(scoreGoodsSku);
                }
            }
        }
        return scoreOrder.getId();
    }
    public PageInfo<XcxOrderListVo> orderList(XcxOrderListDto xcxOrderListDto) {
        PageHelper.startPage(xcxOrderListDto.getPageNo(), xcxOrderListDto.getPageSize());
        List<XcxOrderListVo> data = scoreOrderMapper.selectXcxOrderList(xcxOrderListDto);
        return new PageInfo<>(data);
    }
    public XcxOrderDetailsVo orderDetails(Long id) {
        return scoreOrderMapper.selectXcxOrderDetails(id);
    }
    public void confirmOrder(Long id, String userId) {
        ScoreOrder order = scoreOrderMapper.selectByPrimaryKey(id);
        if (order == null) {
            throw new RestException(-3, "订单不存在");
        }
        if (!order.getUserId().equals(userId)) {
            throw new RestException(-3, "订单不存在");
        }
        if (!ScoreOrder.STATUS_ON.equals(order.getStatus())) {
            throw new RestException(-3, "暂不能确认收货");
        }
        scoreOrderMapper.updateOrderStatus(id, ScoreOrder.STATUS_DOING, userId);
    }
    public void cancelOrder(Long id, String userId) {
        ScoreOrder order = scoreOrderMapper.selectByPrimaryKey(id);
        if (order == null) {
            throw new RestException(-3, "订单不存在");
        }
        if (!order.getUserId().equals(userId)) {
            throw new RestException(-3, "订单不存在");
        }
        if (!ScoreOrder.STATUS_READY.equals(order.getStatus())) {
            throw new RestException(-3, "订单不能取消");
        }
        scoreOrderMapper.updateOrderStatus(id, ScoreOrder.STATUS_CANCEL, userId);
        // 退积分
        AccountInfo accountInfo = accountInfoMapper.selectAccountInfoByUserId(userId);
        BigDecimal score = new BigDecimal(accountInfo.getCollectScore()).add(order.getTotalPrice()).setScale(0, BigDecimal.ROUND_DOWN);
        ScoreDetails scoreDetails = new ScoreDetails();
        scoreDetails.setOriginalScore(new BigDecimal(accountInfo.getCollectScore()));
        scoreDetails.setCurrentScore(score);
        scoreDetails.setChangeScore(order.getTotalPrice());
        scoreDetails.setOrderNo(order.getOrderNo());
        scoreDetails.setType(ScoreDetails.SCORE_TYPE_SHOPPING_RETURN);
        scoreDetails.setCreatedTime(new Date());
        scoreDetails.setUserId(userId);
        scoreDetailsMapper.insert(scoreDetails);
        accountInfo.setCollectScore(score.toString());
        accountInfoMapper.updateByPrimaryKey(accountInfo);
        // 减销量 加库存
        List<ScoreOrderDetails> details = scoreOrderDetailsMapper.selectOrderDetailsByOrderId(order.getId());
        if (CollUtil.isNotEmpty(details)) {
            for (ScoreOrderDetails detail : details) {
                ScoreGoodsSku sku = scoreGoodsSkuMapper.selectByPrimaryKey(detail.getSkuId());
                if (sku == null) {
                    continue;
                }
                sku.setQuantity(sku.getQuantity() - detail.getCnt());
                sku.setStock(sku.getStock() + detail.getCnt());
                scoreGoodsSkuMapper.updateByPrimaryKey(sku);
            }
        }
    }
    public StatisticsVo orderStatistics(String userId) {
        BigDecimal score = scoreDetailsMapper.selectTotalScoreByUserId(userId, ScoreDetails.SCORE_TYPE_EXCHANGE);
        Map<String, Object> userData = scoreOrderMapper.selectOrderStastics(userId);
        Map<String, Object> allData = scoreOrderMapper.selectOrderStastics(null);
        StatisticsVo statisticsVo = new StatisticsVo();
        statisticsVo.setScore(score);
        BigDecimal userPrice = (BigDecimal) userData.get("totalPrice");
        statisticsVo.setReduceCarbon(userPrice.divide(BigDecimal.TEN, 2, BigDecimal.ROUND_DOWN));
        statisticsVo.setOrderCnt(Integer.parseInt(userData.get("totalOrder").toString()));
        BigDecimal totalPrice = (BigDecimal) allData.get("totalPrice");
        statisticsVo.setTotalReduceCarbon(totalPrice.divide(BigDecimal.TEN, 2, BigDecimal.ROUND_DOWN));
        statisticsVo.setTotalOrderCnt(Integer.parseInt(allData.get("totalOrder").toString()));
        statisticsVo.setTotalBuyCnt(Integer.parseInt(allData.get("totalBuy").toString()));
        return statisticsVo;
    }
}