package com.ruoyi.mall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.ApiResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.mall.domain.*;
import com.ruoyi.mall.domain.VO.SeckillGoodsVO;
import com.ruoyi.mall.domain.dto.MallOrderOrderDTO;
import com.ruoyi.mall.domain.vo.GoodsProductVO;
import com.ruoyi.mall.domain.vo.MallOrderGoodsExportVO;
import com.ruoyi.mall.domain.vo.MallOrderGoodsVO;
import com.ruoyi.mall.mapper.*;
import com.ruoyi.mall.service.*;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 订单Service业务层处理
 *
 * @author chang
 * @date 2021-11-25
 */
@Service
public class MallOrderOrderServiceImpl implements IMallOrderOrderService {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private MallOrderOrderMapper mallOrderOrderMapper;

    @Resource
    IMallGoodsGoodsService goodsService;

    @Resource
    IMallGoodsProductService productService;

    @Resource
    IMallMemberAddressService addressService;

    @Resource
    private IMallMemberUserService memberUserService;
    @Resource
    private MallOrderbackGoodsMapper mallOrderbackGoodsMapper;
    @Resource
    private MallOrderBackMapper mallOrderbackMapper;

    @Resource
    IMallOrderGoodsService orderGoodsService;

    @Resource
    IMallMemberCartService memberCartService;

    @Resource
    IMallOrderBackService backService;

    @Resource
    private MallSeckillGoodsMapper mallSeckillGoodsMapper;

    @Resource
    private RedisCache redisCache;

    @Resource
    private MallOrderGoodsMapper mallOrderGoodsMapper;

    @Resource
    private MallCombineGoodsMapper mallCombineGoodsMapper;

    @Resource
    private MallGoodsProductMapper mallGoodsProductMapper;

    @Resource
    private MallShopShopMapper mallShopShopMapper;

    @Resource
    private MallMeetAddressMapper mallMeetAddressMapper;

    @Resource
    private MallGoodsGoodsMapper mallGoodsGoodsMapper;


    @Resource
    private IMallSalesmanAchievementService mallSalesmanAchievementService;

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public MallOrderOrder selectMallOrderOrderById(Long id) {
        MallOrderGoods mallOrderGoods = new MallOrderGoods();
        mallOrderGoods.setOrderId(id);
        List<MallOrderGoods> mallOrderGoodsList = mallOrderGoodsMapper.selectMallOrderGoodsList(mallOrderGoods);

        // 商品数量
        Integer totalCount = 0;

        // 商品数量
        BigDecimal totalprice = new BigDecimal("0");

        if (mallOrderGoodsList.size() > 0) {
            for (MallOrderGoods orderGoods : mallOrderGoodsList) {
                // 单商品数量
                Integer total = orderGoods.getTotal();
                // 单商品总价
                BigDecimal multiply = orderGoods.getPrice().multiply(new BigDecimal(total));
                totalCount += total;
                totalprice = totalprice.add(multiply);
            }
        }

        MallOrderOrder mallOrderOrder = mallOrderOrderMapper.selectMallOrderOrderById(id);
        mallOrderOrder.setTotalCount(totalCount);
        mallOrderOrder.setTotalPrice(totalprice);

        return mallOrderOrder;
    }

    /**
     * 合单号查询订单集合
     *
     * @param totalOrderSn
     * @return
     */
    @Override
    public List<MallOrderOrder> selectMallOrderOrderByTotalOrderSn(String totalOrderSn) {
        return mallOrderOrderMapper.selectOrderListByTotalOrderSn(totalOrderSn);
    }

    /**
     * 订单超时一天自动收货
     *
     * @return 订单
     */
    @Override
    public void orderTimeout(String redisKey) {
        try {
            List<MallOrderOrder> mallOrderOrders = mallOrderOrderMapper.orderTimeout();
            if (mallOrderOrders.size() > 0) {
                for (MallOrderOrder mallOrderOrder : mallOrderOrders) {
                    mallOrderOrder.setStatus("4");
                    mallOrderOrder.setOrderStatus("5");
                    mallOrderOrderMapper.updateMallOrderOrder(mallOrderOrder);

                    // 修改业务员收益状态
                    mallSalesmanAchievementService.insertOrUpdateMallSalesmanAchievement(mallOrderOrder.getId(), 1);

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            redisCache.deleteObject(redisKey);
        }
    }

    /**
     * 订单超时未支付取消
     * 每分钟执行一次
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void orderCancel(String redisKey) {
        try {
            List<MallOrderOrder> orderCancelList = mallOrderOrderMapper.orderCancelList();
            if (!orderCancelList.isEmpty()) {
                // redis锁
                redisCache.setCacheObject(redisKey, 0);

                for (MallOrderOrder orderOrder : orderCancelList) {
                    Long id = orderOrder.getId();

                    MallOrderOrder order = mallOrderOrderMapper.selectMallOrderOrderById(id);
                    Boolean isAccept = this.orderStatusRoute(Integer.parseInt("8"), id.toString());
                    if (isAccept) {
                        order.setStatus("8");
                        order.setOrderStatus("8");
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        order.setCompleteAt(formatter.format(new Date()));
                        this.updateMallOrderOrderByCancle(order);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(DateUtils.getNowDate() + "->定时任务执行异常：" + "订单超时未支付取消");
        } finally {
            logger.info(DateUtils.getNowDate() + "->定时任务执行结束：" + "订单超时未支付取消");
            // 释放锁
            redisCache.deleteObject(redisKey);
        }
    }

    /**
     * 查询订单列表
     *
     * @param mallOrderOrder 订单
     * @return 订单
     */
    @Override
    public List<MallOrderOrder> selectMallOrderOrderList(MallOrderOrder mallOrderOrder) {

        return mallOrderOrderMapper.selectMallOrderOrderList(mallOrderOrder);
    }

    /**
     * 新增订单
     *
     * @param mallOrderOrder 订单
     * @return 结果
     */
    @Override
    public int insertMallOrderOrder(MallOrderOrder mallOrderOrder) {
        return mallOrderOrderMapper.insertMallOrderOrder(mallOrderOrder);
    }

    /**
     * 批量配送
     *
     * @return 结果
     */
    @Override
    public AjaxResult deliveryByOrderIds(Integer[] orderIds) {

        List<MallOrderOrder> mallOrderOrders = mallOrderOrderMapper.selectByOrderIds(orderIds);

        List<Long> integers = new ArrayList<>();

        // 过滤订单状态
        mallOrderOrders.stream().filter(item -> "1".equals(item.getStatus())).forEach(item -> {
            integers.add(item.getId());
        });

        int i = 0;

        if (integers.size() > 0) {
            i = mallOrderOrderMapper.deliveryByOrderIds(integers);
        }
        return AjaxResult.success(i + "个订单批量配送成功");
    }

    /**
     * 批量配送
     *
     * @return 结果
     */
    @Override
    public AjaxResult batchPrintData(Long[] orderIds) {

        List<Map<String, Object>> returnDataList = new ArrayList<>();

        if (orderIds.length > 0) {
            for (Long orderId : orderIds) {
                MallOrderOrder mallOrderOrder = this.selectMallOrderOrderById(orderId);
                MallOrderGoods mallOrderGoods = new MallOrderGoods();
                mallOrderGoods.setOrderId(orderId);
                List<MallOrderGoods> mallOrderGoodsList = orderGoodsService.selectMallOrderGoodsList(mallOrderGoods);
                Map<String, Object> map = new HashMap<>();
                map.put("orderObj", mallOrderOrder);
                map.put("orderGoodsList", mallOrderGoodsList);
                returnDataList.add(map);
            }
        }

        return AjaxResult.success(returnDataList);
    }

    /**
     * 修改订单
     *
     * @param mallOrderOrder 订单
     * @return 结果
     */
    @Override
    public int updateMallOrderOrder(MallOrderOrder mallOrderOrder) {
        return mallOrderOrderMapper.updateMallOrderOrder(mallOrderOrder);
    }

    /**
     * 批量删除订单
     *
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteMallOrderOrderByIds(Long[] ids) {
        for (Long id : ids) {
            List<MallOrderGoodsVO> list = orderGoodsService.selectMallOrderGoodsByOrderId(id);
            for (MallOrderGoodsVO vo : list) {
                orderGoodsService.deleteMallOrderGoodsById(vo.getId());
            }
        }
        return mallOrderOrderMapper.deleteMallOrderOrderByIds(ids);
    }

    /**
     * 删除订单信息
     *
     * @param id 订单主键
     * @return 结果
     */
    @Override
    public int deleteMallOrderOrderById(Long id) {
        return mallOrderOrderMapper.deleteMallOrderOrderById(id);
    }

    /**
     * 再来一单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResult oneMoreOrder(Map<String, Object> params) {
        Long orderId = MapUtils.getLong(params, "orderId");

        //查询订单信息
        MallOrderOrder mallOrderOrder = mallOrderOrderMapper.selectMallOrderOrderById(orderId);

        if (ObjectUtils.isNotEmpty(mallOrderOrder)) {
            Long userId = mallOrderOrder.getUserId();
            //订单-商品列表
            List<MallOrderGoodsVO> goodsList = orderGoodsService.selectMallOrderGoodsByOrderId(orderId);
            if (goodsList.size() > 0) {
                for (MallOrderGoodsVO mallOrderGoodsVO : goodsList) {
                    MallMemberCart cart = new MallMemberCart();
                    cart.setGoodsId(Long.parseLong(mallOrderGoodsVO.getGoodsId().toString()));
                    cart.setProductId(Long.parseLong(mallOrderGoodsVO.getProductId().toString()));
                    cart.setUserId(Long.parseLong(userId.toString()));

                    //查询购物车是否已添加此商品
                    MallMemberCart orgCart = memberCartService.selectMallMemberCartByCart(cart);
                    cart.setUpdateAt(DateUtils.getTime());
                    if (ObjectUtils.isNotEmpty(orgCart)) {
                        //添加商品数量
                        orgCart.setTotal(orgCart.getTotal() + mallOrderGoodsVO.getTotal());
                        memberCartService.updateMallMemberCart(orgCart);
                    } else {
                        //添加商品
                        cart.setTotal(mallOrderGoodsVO.getTotal());
                        memberCartService.insertMallMemberCart(cart);
                    }
                }
            }
            return ApiResult.ok();
        } else {
            return ApiResult.error("订单信息异常");
        }
    }

    /**
     * 生成订单
     */
    @Transactional
    @Override
    public MallOrderOrder creatOrderByGoods(Map<String, Object> params) {
        // MallGoodsProduct pro = productService.selectMallGoodsProductById(Long.valueOf(params.get("productId").toString()));

        //创建order Model
        MallOrderOrder order = new MallOrderOrder();

        MallMemberUser memberUser = memberUserService.selectMallMemberUserById(Long.valueOf(params.get("userId").toString()));
        order.setSalesmanId(memberUser.getSalesmanId());
        int deliveryType = Integer.parseInt(params.get("deliveryType").toString());
        order.setDeliveryType(deliveryType);
        order.setUserId(Long.valueOf(params.get("userId").toString()));
        order.setPostFee(BigDecimal.valueOf(0));
        String orderNo = orderIdGenerator();
        order.setOrderNo(orderNo);
        // 生成合单号
        order.setTotalOrderSn(IdUtils.fastSimpleUUID());
        String couponId = "";
        if (params.containsKey("couponId")) {
            couponId = params.get("couponId").toString();
        }

        //数量
        Integer count = MapUtils.getInteger(params, "count");

        MallGoodsGoods goods = goodsService.selectMallGoodsGoodsById(Long.valueOf(params.get("goodId").toString()));
        order.setShopId(goods.getShopId());
        order.setIntegral(goods.getIntegral());
        BigDecimal price = new BigDecimal(0);
        // 商品规格
        List<GoodsProductVO> goodsProductVOList = mallGoodsProductMapper.selectMallGoodsProductByGoodsIdVO(Long.valueOf(params.get("goodId").toString()));
        if (goodsProductVOList.size() > 0) {
            for (GoodsProductVO productVO : goodsProductVOList) {
                if (count.equals(productVO.getNum()) || count > productVO.getNum()) {

                    if ("1".equals(memberUser.getVip())) {
                        price = productVO.getPriceVip();
                    } else {
                        price = productVO.getPrice();
                    }

                }
            }
            if (price.compareTo(BigDecimal.ZERO) == 0) {
                return null;
            }
        }

        //订单原价
        BigDecimal bigDecimal = price.multiply(new BigDecimal(count));

        //订单类型（0-普通订单，1-秒杀订单，2-拼团订单）
        Integer orderType = null;

        //秒杀
        if (params.containsKey("seckillGoodsId") && MapUtils.getInteger(params, "seckillGoodsId") != null) {
            //秒杀订单
            orderType = 1;
            SeckillGoodsVO goodId = mallSeckillGoodsMapper.seckillGoodsInfo(params);
            if (ObjectUtils.isNotEmpty(goodId)) {
                //总支付价格
                BigDecimal payPrice = goodId.getSeckillPrice().multiply(new BigDecimal(count));
                order.setPayment(payPrice);
            } else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return null;
            }
        } else {
            orderType = 0;
            //总支付价格
            BigDecimal payPrice = price.multiply(new BigDecimal(count));

            //如果使用优惠券
            if (!StringUtils.isEmpty(couponId)) {
                Map<String, Object> map = memberUserService.checkCouponUsed(couponId, Long.valueOf(params.get("userId").toString()));
                memberUserService.updateCouponUsed(couponId, Long.valueOf(params.get("userId").toString()));
                //优惠金额
                BigDecimal discountPrice = new BigDecimal(map.get("price").toString());
                BigDecimal payment = payPrice.subtract(discountPrice);
                order.setPayment(payment.compareTo(new BigDecimal(0)) > 0 ? payment : new BigDecimal(0));
                order.setDiscountPrice(discountPrice);
                order.setMemberCouponId(Long.valueOf(params.get("memberCouponId").toString()));
            } else {
                order.setPayment(payPrice);
            }
        }

        // 拼团
        if (params.containsKey("orderType") && MapUtils.getInteger(params, "orderType") != null && MapUtils.getInteger(params, "orderType") == 2) {
            // 拼团订单
            orderType = 2;
            MallCombineGoods combineGoods = mallCombineGoodsMapper.selectCombineGoodsByGoodsId(Long.valueOf(params.get("goodId").toString()));
            if (ObjectUtils.isNotEmpty(combineGoods)) {
                //总支付价格
                BigDecimal payPrice = combineGoods.getPrice().multiply(new BigDecimal(count));
                order.setPayment(payPrice);
            } else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return null;
            }
        } else {
            orderType = 0;
            //总支付价格
            BigDecimal payPrice = price.multiply(new BigDecimal(count));

            //如果使用优惠券
            if (!StringUtils.isEmpty(couponId)) {
                // Map<String, Object> map = memberUserService.checkCouponUsed(couponId,Long.valueOf(params.get("userId").toString()));
                memberUserService.updateCouponUsed(couponId, Long.valueOf(params.get("userId").toString()));
                //优惠金额
                BigDecimal discountPrice = new BigDecimal(params.get("couponPrice").toString());
                BigDecimal payment = payPrice.subtract(discountPrice);
                order.setPayment(payment.compareTo(new BigDecimal(0)) > 0 ? payment : new BigDecimal(0));
                order.setDiscountPrice(discountPrice);
                order.setMemberCouponId(Long.valueOf(params.get("memberCouponId").toString()));
            } else {
                order.setPayment(payPrice);
            }
        }

        if (params.containsKey("teamId") && MapUtils.getLong(params, "teamId") != null) {
            order.setTeamId(Long.valueOf(params.get("teamId").toString()));
        }


        order.setOrderType(orderType);
        order.setOrderPrice(bigDecimal);

        if (order.getPayment().compareTo(new BigDecimal(0)) > 0) {
            order.setStatus("0");
        } else {
            order.setPayType("1");
            order.setPayAt(DateUtils.getTime());
            //  配送方式：0-快递，1-自提
            if (order.getDeliveryType() == 0) {
                order.setStatus("1");
            } else {
                order.setStatus("2");
            }
        }

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        order.setCreateAt(formatter.format(new Date()));
        order.setBuyerMsg(params.get("buyerMsg").toString());


        if (deliveryType == 0) {
            MallMemberAddress address = addressService.selectMallMemberAddressById(Long.valueOf(params.get("addressId").toString()));
            order.setReceiverName(address.getName());
            order.setReceiverPhone(address.getPhone());
            order.setReceiverProvince(address.getProvince());
            order.setReceiverCity(address.getCity());
            order.setReceiverArea(address.getArea());
            // order.setReceiverAddress(address.getAddress());

            order.setReceiverAddress(address.getAddress());
        } else {
            MallShopShop shopShop = mallShopShopMapper.selectMallShopShopByShopId(Long.valueOf(params.get("shopId").toString()));
            order.setReceiverName(shopShop.getShopName());
            order.setReceiverPhone(shopShop.getShopPhone());
            order.setReceiverProvince(shopShop.getProvinceName());
            order.setReceiverCity(shopShop.getCityName());
            order.setReceiverArea(shopShop.getAreaName());
            order.setReceiverAddress(shopShop.getAddress());
        }
        this.insertMallOrderOrder(order);


        if (goods.getStock() >= Integer.parseInt(params.get("count").toString())) {
            // 库存够，修改库存
            goodsService.updateMallGoodsGoodsStock(goods.getId().intValue(), count);

            // 库存够，修改销量
            goodsService.updateMallGoodsGoodsSaleNum(goods.getId().intValue(), count);

        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return null;
        }
        //修改库存、插入订单
        // productService.updateMallGoodsProduct(pro);

        //秒杀库存
        if (orderType == 1) {
            mallSeckillGoodsMapper.editSeckillGoodsInfo(MapUtils.getLong(params, "goodId"), 0, count);
        }
        // 拼团库存
        if (orderType == 2) {
            mallCombineGoodsMapper.editCombineGoodsInfo(MapUtils.getLong(params, "goodId"), 0, count);
        }

        //创建订单-商品 model
        MallOrderGoods orderGoods = new MallOrderGoods();
        orderGoods.setGoodsId(Long.valueOf(params.get("goodId").toString()));
        orderGoods.setOrderId(order.getId());
        // orderGoods.setProductId(pro.getId());
        orderGoods.setGoodsName(goods.getGoodsName());
        orderGoods.setGoodsImg(goods.getGoodsImg());
        orderGoods.setProductName(goods.getSpec());
        orderGoods.setPrice(price);
        orderGoods.setIntegral(goods.getIntegral());
        orderGoods.setTotal(Integer.parseInt(params.get("count").toString()));
        orderGoods.setCommission(goods.getCommission());
        orderGoods.setReturnableQuantity(Integer.parseInt(params.get("count").toString()));
        orderGoodsService.insertMallOrderGoods(orderGoods);
        return order;
    }

    @Override
    public MallOrderOrder queryByOrderSn(String orderNo) {
        return mallOrderOrderMapper.queryByOrderSn(orderNo);
    }

    /*
     * 购物车生成订单
     * */
    @Transactional
    @Override
    public List<MallOrderOrder> creatOrderByCartIds(Map<String, Object> params) {
        String userId = params.get("userId").toString();
        String cartIds = params.get("cartIds").toString();
        String addressId = params.get("addressId").toString();

        MallMemberUser memberUser = memberUserService.selectMallMemberUserById(Long.parseLong(userId));

        // 合单号
        String totalOrderSn = IdUtils.fastSimpleUUID();

        String[] cartIdList = cartIds.split(",");

        Integer goodsCounts = 0;

        //List<Map<String, List<MallMemberCart>>> list = new ArrayList<>();
        HashMap<String, List<Map<String, Object>>> map = new HashMap<>();

        for (String cartId : cartIdList) {
            MallMemberCart memberCart = memberCartService.selectMallMemberCartById(Long.parseLong(cartId));
            goodsCounts = goodsCounts + memberCart.getTotal();
            MallGoodsGoods goods = goodsService.selectMallGoodsGoodsById(memberCart.getGoodsId());
            Long shopId = goods.getShopId();
            if (!map.containsKey(String.valueOf(shopId))) {
                // 不包含key ,加入map
                List<Map<String, Object>> list = new ArrayList<>();
                Map<String, Object> data = new HashMap<>();
                data.put("cart", memberCart);
                data.put("goods", goods);
                list.add(data);
                map.put(String.valueOf(shopId), list);
            } else {
                // 包含key
                List<Map<String, Object>> list = map.get(String.valueOf(shopId));
                Map<String, Object> data = new HashMap<>();
                data.put("cart", memberCart);
                data.put("goods", goods);
                list.add(data);
                map.put(String.valueOf(shopId), list);
            }
        }
        // 遍历map生成订单
        Set<String> strings = map.keySet();
        List<MallOrderOrder> orderList = new ArrayList<>();

        String couponId = "";
        BigDecimal discountPrice = BigDecimal.ZERO;
        if (params.containsKey("couponId")) {
            couponId = params.get("couponId").toString();
        }
        //如果使用优惠券
        if (!StringUtils.isEmpty(couponId)) {
            Map<String, Object> couponMap = memberUserService.checkCouponUsed(couponId, Long.valueOf(params.get("userId").toString()));
            memberUserService.updateCouponUsed(couponId, Long.valueOf(params.get("userId").toString()));
            //优惠金额
            discountPrice = new BigDecimal(couponMap.get("price").toString());

        }

        List<MallMemberCart> memberCartList = new ArrayList<>();

        for (String shopId : strings) {

            BigDecimal totlePrice = new BigDecimal(0);
            BigDecimal totleIntegral = new BigDecimal(0);
            BigDecimal totlePriceN = new BigDecimal(0);

            //创建order Model
            MallOrderOrder order = new MallOrderOrder();

            order.setTotalOrderSn(totalOrderSn);
            order.setShopId(Long.parseLong(shopId));
            order.setSalesmanId(memberUser.getSalesmanId());
            int deliveryType = Integer.parseInt(params.get("deliveryType").toString());
            order.setDeliveryType(deliveryType);

            order.setUserId(Long.parseLong(userId));
            order.setPostFee(BigDecimal.valueOf(0));
            String orderNo = orderIdGenerator();
            order.setOrderNo(orderNo);
            order.setStatus("0");
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            order.setCreateAt(formatter.format(new Date()));
            order.setBuyerMsg(params.get("buyerMsg").toString());

            if (deliveryType == 0) {
                MallMemberAddress address = addressService.selectMallMemberAddressById(Long.valueOf(addressId));
                order.setReceiverName(address.getName());
                order.setReceiverPhone(address.getPhone());
                order.setReceiverProvince(address.getProvince());
                order.setReceiverCity(address.getCity());
                order.setReceiverArea(address.getArea());
                // order.setReceiverAddress(address.getAddress());

                order.setReceiverAddress(address.getAddress());
            } else {
                MallShopShop shopShop = mallShopShopMapper.selectMallShopShopByShopId(Long.valueOf(params.get("shopId").toString()));
                order.setReceiverName(shopShop.getShopName());
                order.setReceiverPhone(shopShop.getShopPhone());
                order.setReceiverProvince(shopShop.getProvinceName());
                order.setReceiverCity(shopShop.getCityName());
                order.setReceiverArea(shopShop.getAreaName());
                order.setReceiverAddress(shopShop.getAddress());
            }

            this.insertMallOrderOrder(order);

            Integer orderGoodsCounts = 0;

            List<Map<String, Object>> cartData = map.get(shopId);
            for (Map<String, Object> data : cartData) {
                MallMemberCart cart = (MallMemberCart) data.get("cart");
                MallGoodsGoods goods = (MallGoodsGoods) data.get("goods");
                orderGoodsCounts = orderGoodsCounts + cart.getTotal();
                BigDecimal price = new BigDecimal(0);
                // 商品规格
                List<GoodsProductVO> goodsProductVOList = mallGoodsProductMapper.selectMallGoodsProductByGoodsIdVO(cart.getGoodsId());
                if (goodsProductVOList.size() > 0) {
                    for (GoodsProductVO productVO : goodsProductVOList) {
                        if (cart.getTotal().equals(productVO.getNum()) || cart.getTotal() > productVO.getNum()) {

                            if ("1".equals(memberUser.getVip())) {
                                price = productVO.getPriceVip();
                            } else {
                                price = productVO.getPrice();
                            }

                        }
                    }
                }
                if (price.compareTo(BigDecimal.ZERO) == 0) {
                    return null;
                }

                // MallGoodsProduct pro = productService.selectMallGoodsProductById(memberCart.getProductId());
                if (goods.getStock() >= cart.getTotal() && "0".equals(goods.getStatus()) && goods.getCheckStatus() == 1) {
                    MallMemberCart memberCart = new MallMemberCart();
                    memberCart.setGoodsId(goods.getId());
                    memberCart.setTotal(cart.getTotal());
                    memberCartList.add(memberCart);
                    // // 库存够，修改库存
                    // goodsService.updateMallGoodsGoodsStock(goods.getId().intValue(), cart.getTotal());
                    //
                    // // 库存够，修改销量
                    // goodsService.updateMallGoodsGoodsSaleNum(goods.getId().intValue(), cart.getTotal());

                } else {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return null;
                }
                //修改库存、插入订单
                // productService.updateMallGoodsProduct(pro);

                //创建订单-商品 model
                MallOrderGoods orderGoods = new MallOrderGoods();
                orderGoods.setGoodsId(cart.getGoodsId());
                orderGoods.setOrderId(order.getId());
                // orderGoods.setProductId(pro.getId());
                orderGoods.setGoodsName(goods.getGoodsName());
                orderGoods.setGoodsImg(goods.getGoodsImg());
                orderGoods.setProductName(goods.getSpec());
                orderGoods.setPrice(price);
                orderGoods.setIntegral(goods.getIntegral());
                orderGoods.setTotal(cart.getTotal());
                orderGoods.setCommission(goods.getCommission());
                orderGoods.setReturnableQuantity(cart.getTotal());
                orderGoodsService.insertMallOrderGoods(orderGoods);


                //总金额计算
                totlePrice = totlePrice.add(price.multiply(new BigDecimal(Integer.valueOf(cart.getTotal()))));
                totlePriceN = totlePrice.add(price.multiply(new BigDecimal(Integer.valueOf(cart.getTotal()))));
                if (goods.getIntegral() != null) {
                    totleIntegral = totleIntegral.add(goods.getIntegral().multiply(new BigDecimal(Integer.valueOf(cart.getTotal()))));
                }
            }
            order.setOrderPrice(totlePrice);
            order.setPayment(totlePrice.compareTo(new BigDecimal(0)) > 0 ? totlePrice : new BigDecimal(0));

            // 如果使用优惠券
            if (discountPrice.compareTo(BigDecimal.ZERO) > 0) {
                // 按比例分配优惠金额
                // BigDecimal rate = BigDecimal.valueOf(orderGoodsCounts).divide(BigDecimal.valueOf(goodsCounts), 2, RoundingMode.HALF_UP);
                // BigDecimal dPrice = discountPrice.multiply(rate).setScale(2, RoundingMode.HALF_UP);
                BigDecimal payment = totlePrice.subtract(discountPrice);
                order.setPayment(payment.compareTo(new BigDecimal(0)) > 0 ? payment : new BigDecimal(0));
                order.setDiscountPrice(payment);
                order.setMemberCouponId(Long.valueOf(params.get("memberCouponId").toString()));
            }

            if (order.getPayment().compareTo(new BigDecimal(0)) < 1) {
                order.setPayType("1");
                order.setPayAt(DateUtils.getTime());
                //  配送方式：0-快递，1-自提
                if (order.getDeliveryType() == 0) {
                    order.setStatus("1");
                } else {
                    order.setStatus("2");
                }
            }

            this.updateMallOrderOrder(order);
            orderList.add(order);
        }

        if (memberCartList.size() > 0) {
            for (MallMemberCart cart : memberCartList) {
                // 库存够，修改库存
                goodsService.updateMallGoodsGoodsStock(cart.getGoodsId().intValue(), cart.getTotal());

                // 库存够，修改销量
                goodsService.updateMallGoodsGoodsSaleNum(cart.getGoodsId().intValue(), cart.getTotal());
            }
            for (String s : cartIdList) {
                //下单成功 删除购物车
                memberCartService.deleteMallMemberCartById(Long.valueOf(s));
            }
        }

        return orderList;
    }


    /// *
    //* 购物车生成订单
    //* */
    //@Transactional
    //@Override
    //public MallOrderOrder creatOrderByCartIds(Map<String, Object> params) {
    //    String userId = params.get("userId").toString();
    //    String cartIds = params.get("cartIds").toString();
    //    String addressId = params.get("addressId").toString();
    //
    //    //创建order Model
    //    MallOrderOrder order =  new MallOrderOrder();
    //
    //    MallMemberUser memberUser = memberUserService.selectMallMemberUserById(Long.parseLong(userId));
    //    order.setSalesmanId(memberUser.getSalesmanId());
    //    int deliveryType = Integer.parseInt(params.get("deliveryType").toString());
    //    order.setDeliveryType(deliveryType);
    //
    //    order.setUserId(Long.parseLong(userId));
    //    order.setPostFee(BigDecimal.valueOf(0));
    //    String orderNo = orderIdGenerator();
    //    order.setOrderNo(orderNo);
    //    order.setStatus("0");
    //    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    //    order.setCreateAt(formatter.format(new Date()));
    //    order.setBuyerMsg(params.get("buyerMsg").toString());
    //
    //    if (deliveryType == 0) {
    //        MallMemberAddress address =  addressService.selectMallMemberAddressById(Long.valueOf(addressId));
    //        order.setReceiverName(address.getName());
    //        order.setReceiverPhone(address.getPhone());
    //        order.setReceiverProvince(address.getProvince());
    //        order.setReceiverCity(address.getCity());
    //        order.setReceiverArea(address.getArea());
    //        // order.setReceiverAddress(address.getAddress());
    //
    //        order.setReceiverAddress(address.getAddress());
    //    } else {
    //        MallShopShop shopShop = mallShopShopMapper.selectMallShopShopByShopId(Long.valueOf(params.get("shopId").toString()));
    //        order.setReceiverName(shopShop.getShopName());
    //        order.setReceiverPhone(shopShop.getShopPhone());
    //        order.setReceiverProvince(shopShop.getProvinceName());
    //        order.setReceiverCity(shopShop.getCityName());
    //        order.setReceiverArea(shopShop.getAreaName());
    //        order.setReceiverAddress(shopShop.getAddress());
    //    }
    //
    //    this.insertMallOrderOrder(order);
    //
    //    String[] cartIdList = cartIds.split(",");
    //
    //    BigDecimal totlePrice = new BigDecimal(0);
    //    BigDecimal totlePriceN = new BigDecimal(0);
    //
    //    for (String cartId : cartIdList) {
    //        MallMemberCart memberCart = memberCartService.selectMallMemberCartById(Long.parseLong(cartId));
    //
    //        MallGoodsGoods goods = goodsService.selectMallGoodsGoodsById(memberCart.getGoodsId());
    //
    //        BigDecimal price = new BigDecimal(0);
    //        // 商品规格
    //        List<GoodsProductVO> goodsProductVOList = mallGoodsProductMapper.selectMallGoodsProductByGoodsIdVO(memberCart.getGoodsId());
    //        if (goodsProductVOList.size() > 0) {
    //            for (GoodsProductVO productVO : goodsProductVOList) {
    //                if (memberCart.getTotal().equals(productVO.getNum()) || memberCart.getTotal() > productVO.getNum()) {
    //
    //                    if ("1".equals(memberUser.getVip())) {
    //                        price = productVO.getPriceVip();
    //                    } else {
    //                        price = productVO.getPrice();
    //                    }
    //
    //                }
    //            }
    //        }
    //
    //        // MallGoodsProduct pro = productService.selectMallGoodsProductById(memberCart.getProductId());
    //        if (goods.getStock() >= memberCart.getTotal()){
    //            // 库存够，修改库存
    //            goodsService.updateMallGoodsGoodsStock(goods.getId().intValue(), memberCart.getTotal());
    //
    //            // 库存够，修改销量
    //            goodsService.updateMallGoodsGoodsSaleNum(goods.getId().intValue(), memberCart.getTotal());
    //
    //        }else {
    //            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    //            return null;
    //        }
    //        //修改库存、插入订单
    //        // productService.updateMallGoodsProduct(pro);
    //
    //        //创建订单-商品 model
    //        MallOrderGoods orderGoods = new MallOrderGoods();
    //        orderGoods.setGoodsId(memberCart.getGoodsId());
    //        orderGoods.setOrderId(order.getId());
    //        // orderGoods.setProductId(pro.getId());
    //        orderGoods.setGoodsName(goods.getGoodsName());
    //        orderGoods.setGoodsImg(goods.getGoodsImg());
    //        orderGoods.setProductName(goods.getSpec());
    //        orderGoods.setPrice(price);
    //        orderGoods.setTotal(memberCart.getTotal());
    //        orderGoods.setCommission(goods.getCommission());
    //
    //        orderGoodsService.insertMallOrderGoods(orderGoods);
    //
    //        //下单成功 删除购物车
    //        memberCartService.deleteMallMemberCartById(Long.parseLong(cartId));
    //
    //        //总金额计算
    //        totlePrice = totlePrice.add(price.multiply(new BigDecimal(Integer.valueOf(memberCart.getTotal()))));
    //        totlePriceN = totlePrice.add(price.multiply(new BigDecimal(Integer.valueOf(memberCart.getTotal()))));
    //    }
    //    order.setOrderPrice(totlePrice);
    //    order.setPayment(totlePrice);
    //    String couponId = "";
    //    if (params.containsKey("couponId")){
    //        couponId = params.get("couponId").toString();
    //    }
    //    //如果使用优惠券
    //    if (!StringUtils.isEmpty(couponId)){
    //        Map<String, Object> map = memberUserService.checkCouponUsed(couponId,Long.valueOf(params.get("userId").toString()));
    //        memberUserService.updateCouponUsed(couponId,Long.valueOf( params.get("userId").toString()));
    //        //优惠金额
    //        BigDecimal discountPrice = new BigDecimal(map.get("price").toString());
    //        BigDecimal payment = totlePrice.subtract(discountPrice);
    //        order.setPayment(payment.compareTo(new BigDecimal(0)) == 1 ? payment : new BigDecimal(0.01));
    //        order.setDiscountPrice(discountPrice);
    //    }else {
    //        order.setPayment(totlePrice);
    //    }
    //    this.updateMallOrderOrder(order);
    //
    //    return order;
    //}
    public static String orderIdGenerator() {
        String time = DateUtils.dateTimeNow();
        String randomString = RandomStringUtils.randomNumeric(8);
        return time + randomString;
    }

    //订单状态0=待支付,1=待发货,2=待收货,3=待评论,4=已完成,5=退货中,6=退货成功,7=换货中,8=已取消
    @Override
    public Boolean orderStatusRoute(int nowStatus, String orderId) {

        MallOrderOrder order = this.selectMallOrderOrderById(Long.parseLong(orderId));
        switch (nowStatus) {
            case 1:
                return "0".equals(order.getStatus()) ? true : false;
            case 2:
                if ("1".equals(order.getStatus()) || "5".equals(order.getStatus())) {
                    return true;
                } else {
                    return false;
                }
            case 3:
                if ("2".equals(order.getStatus()) || "5".equals(order.getStatus())) {
                    return true;
                } else {
                    return false;
                }
            case 4:
                return "3".equals(order.getStatus()) ? true : false;
            case 5:
                if ("1".equals(order.getStatus()) || "2".equals(order.getStatus())) {
                    return true;
                } else {
                    return false;
                }
            case 6:
                return "5".equals(order.getStatus()) ? true : false;
            case 8:
                return "0".equals(order.getStatus()) ? true : false;
            default:
                return false;
        }
    }

    //状态: 0=退款中,1=退款成功,2=取消退款,3=拒绝退款
    @Override
    public Boolean refundStatusRoute(int nowStatus, String refundId) {
        //订单状态0=待支付,1=待发货,2=待收货,3=待评论,4=已完成,5=退货中,6=退货成功,7=换货中,8=已取消
        MallOrderBack back = backService.selectMallOrderBackById(Long.parseLong(refundId));
        MallOrderOrder order = this.selectMallOrderOrderById(back.getOrderId());

        switch (nowStatus) {
            case 0:
                if ("1".equals(order.getStatus()) || "2".equals(order.getStatus())) {
                    return true;
                } else {
                    return false;
                }
            case 1:
                if ("5".equals(order.getStatus()) && "0".equals(back.getStatus())) {
                    return true;
                } else {
                    return false;
                }
            case 2:
                if ("5".equals(order.getStatus()) && "0".equals(back.getStatus())) {
                    return true;
                } else {
                    return false;
                }
            case 3:
                if ("5".equals(order.getStatus()) && "0".equals(back.getStatus())) {
                    return true;
                } else {
                    return false;
                }
            default:
                return false;
        }
    }

    @Override
    public PageInfo<MallOrderOrder> selectOrdersByType(String pageNum, String pageSize, String type, String userId, Integer deliveryType) {
        PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        List<MallOrderOrder> list = new ArrayList<>();
        if ("0".equals(type)) {
            String sqlStr = "('" + type + "')";
            list = mallOrderOrderMapper.selectOrdersByStatus(sqlStr, userId);
        }
        if ("1".equals(type) || "2".equals(type)) {
            String sqlStr = "('" + type + "')";
            list = mallOrderOrderMapper.selectOrdersByreturnStatus(sqlStr, userId);
        }
        if ("12".equals(type)) {
            String sqlStr = "('" + type + "')";
            list = mallOrderOrderMapper.selectOrdersByreturnStatus(sqlStr, userId);
        }

        if ("3".equals(type)) {
            String sqlStr = "('3','4')";
            list = mallOrderOrderMapper.selectOrdersByStatus(sqlStr, userId);
        }
        if ("4".equals(type)) {
            String sqlStr = "('3','4')";
            list = mallOrderOrderMapper.selectOrdersByStatus(sqlStr, userId);
        }
        if ("-1".equals(type)) {
            MallOrderOrder orderOrder = new MallOrderOrder();
            orderOrder.setUserId(Long.parseLong(userId));
            list = mallOrderOrderMapper.selectMallOrderOrderList(orderOrder);
        }
        if ("5".equals(type)) {
            list = mallOrderOrderMapper.selectOrdersByStatus("('5','6')", userId);
        }
        for (MallOrderOrder orderOrder : list) {
            List<MallOrderGoodsVO> orderGoodsVOList = orderGoodsService.selectMallOrderGoodsByOrderId(orderOrder.getId());
            orderOrder.setGoodsVOList(orderGoodsVOList);
            if ("6".equals(orderOrder.getStatus())) {
                orderOrder.setReturnPrice(backService.getReturnPrice(orderOrder.getId(), orderOrder.getStatus()));
            }
        }

        PageInfo<MallOrderOrder> page = new PageInfo<>(list);
        return page;
    }

    @Override
    public PageInfo<MallOrderBackDto> selectBackOrdersByType(String pageNum, String pageSize, String type, String userId, int deliveryType) {
        PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        List<MallOrderOrder> list = new ArrayList<>();
        List<MallOrderBackDto> mallorderbacks = new ArrayList<>();
        if ("5".equals(type)) {
            list = mallOrderOrderMapper.selectOrdersByUserid(userId);
        }
        for (MallOrderOrder orderOrder : list) {
            List<MallOrderBackDto> mallOrderBackDtos = mallOrderbackMapper.selectMallOrderBackByOrderIdDto(orderOrder.getId());

            mallorderbacks.addAll(mallOrderBackDtos);
        }
        for (MallOrderBackDto mallOrderBack : mallorderbacks) {
            if (mallOrderBack.getRefundNo() != null&&!mallOrderBack.getRefundNo().isEmpty()) {
                BigDecimal Sumtotal = BigDecimal.valueOf(0);
                List<MallOrderbackGoods> mallOrderbackGoods = mallOrderbackGoodsMapper.selectMallOrderbackGoodsByrefundno(mallOrderBack.getRefundNo());
                MallOrderOrder mallOrderOrder = mallOrderOrderMapper.selectMallOrderOrderById(mallOrderBack.getOrderId());
                for (MallOrderbackGoods rbackGoods : mallOrderbackGoods) {
                    Sumtotal = Sumtotal.add(rbackGoods.getPrice());
                }
                mallOrderBack.setMallOrderbackGoodsList(mallOrderbackGoods);
                mallOrderBack.setBackorderNo(mallOrderOrder.getOrderNo());
                mallOrderBack.setSumtotal(Sumtotal);
            }
        }

        PageInfo<MallOrderBackDto> page = new PageInfo<>(mallorderbacks);
        return page;
    }

    @Transactional
    @Override
    public void cancelOrder() {
        String compareTime = DateUtils.getBeforeTime(30);

        //订单列表
        List<MallOrderOrder> orderList = mallOrderOrderMapper.selectMallOrderByTime(compareTime);
        if (orderList.size() > 0) {
            for (MallOrderOrder order : orderList) {
                //订单-商品列表
                List<MallOrderGoodsVO> goodsList = orderGoodsService.selectMallOrderGoodsByOrderId(order.getId());
                for (MallOrderGoodsVO goodsVO : goodsList) {
                    //商品-规格列表，恢复库存和销量
//                    MallGoodsProduct product = productService.selectMallGoodsProductById(goodsVO.getProductId());
//                    product.setStock(product.getStock() + goodsVO.getTotal());
//                    product.setNumSale(product.getNumSale() - goodsVO.getTotal());
//                    productService.updateMallGoodsProduct(product);

                    productService.updateMallGoodsProductByParams(goodsVO.getProductId(), goodsVO.getTotal());
                }
            }
        }
        mallOrderOrderMapper.taskCancleOrder(compareTime);
    }

    @Transactional
    @Override
    public void updateRefundRestlt(MallOrderBack orderBack, MallOrderOrder orderOrder) {
        backService.updateMallOrderBack(orderBack);
        updateMallOrderOrder(orderOrder);
    }

    @Transactional
    @Override
    public ApiResult updateMallOrderOrderByCancle(MallOrderOrder order) {
        try {
            this.updateMallOrderOrder(order);
            //改库存
            List<MallOrderGoodsVO> list = orderGoodsService.selectMallOrderGoodsByOrderId(order.getId());
            for (MallOrderGoodsVO vo : list) {
                //productService.updateMallGoodsProductByParams(vo.getProductId(),vo.getTotal());
                mallGoodsGoodsMapper.updateGoodsStock(vo.getTotal(), vo.getGoodsId());
            }
            return ApiResult.ok("取消订单成功");
        } catch (Exception e) {
            return ApiResult.error("取消订单失败");
        }


    }

    @Override
    public int checkTotleCount() {
        return mallOrderOrderMapper.checkTotleCount();
    }

    @Override
    public BigDecimal checkTotlePrice() {
        return mallOrderOrderMapper.checkTotlePrice();
    }

    @Override
    public BigDecimal checkYearDate(String year) {
        return mallOrderOrderMapper.checkYearDate(year);
    }

    @Override
    public BigDecimal checkYearAndMonth(String year, String month, String day) {
        return mallOrderOrderMapper.checkYearAndMonth(year, month, day);
    }

    @Override
    public int checkCountYearAndMonth(String year, String month, String day) {
        return mallOrderOrderMapper.checkCountYearAndMonth(year, month, day);
    }

    /**
     * 查询退货订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public MallOrderOrder selectMallOrderBackById(Long id) {
        List<MallOrderGoods> mallOrderGoodsList = mallOrderGoodsMapper.selectMallBackOrderGoodsList(id);

        // 商品数量
        Integer totalCount = 0;

        // 商品数量
        BigDecimal totalprice = new BigDecimal("0");

        if (mallOrderGoodsList.size() > 0) {
            for (MallOrderGoods orderGoods : mallOrderGoodsList) {
                // 单商品数量
                Integer total = orderGoods.getTotal();
                // 单商品总价
                BigDecimal multiply = orderGoods.getPrice().multiply(new BigDecimal(total));
                totalCount += total;
                totalprice = totalprice.add(multiply);
            }
        }

        MallOrderOrder mallOrderOrder = mallOrderOrderMapper.selectMallOrderOrderById(id);
        mallOrderOrder.setTotalCount(totalCount);
        mallOrderOrder.setTotalPrice(totalprice);

        return mallOrderOrder;
    }

    /**
     * 导出订单列表
     *
     * @param orderIds 订单ID
     * @return 订单集合
     */
    @Override
    public List<MallOrderGoodsExportVO> selectExportOrderMallOrderOrderList(Long[] orderIds) {

        return mallOrderGoodsMapper.selectMallOrderGoodsListByOrderIds(orderIds);
    }

    /**
     * 导出订单
     *
     * @param mallOrderOrder
     * @return
     */
    @Override
    public List<MallOrderGoodsExportVO> selectExportOrderList(MallOrderOrder mallOrderOrder) {
        return mallOrderGoodsMapper.exportOrder(mallOrderOrder);
    }

    /**
     * 旧订单绑定shopId
     */
    @Override
    public void change() {
        List<MallOrderOrder> orderList = mallOrderOrderMapper.selectOrderListByShopId();

        for (MallOrderOrder order : orderList) {
            List<MallOrderGoodsVO> goodsList = orderGoodsService.selectMallOrderGoodsByOrderId(order.getId());
            if (!goodsList.isEmpty()) {
                Long goodsId = goodsList.get(0).getGoodsId();
                MallGoodsGoods goods = mallGoodsGoodsMapper.selectGoodsById(goodsId);
                Long shopId = goods.getShopId();
                MallShopShop mallShopShop = mallShopShopMapper.selectMallShopShopByShopId(shopId);
                if (ObjectUtils.isNotEmpty(mallShopShop)) {
                    order.setShopId(shopId);

                } else {
                    order.setShopId(0L);
                }
                mallOrderOrderMapper.updateMallOrderOrder(order);
            }
        }

    }

    /**
     * 修改订单
     *
     * @param resourceDTO 订单
     * @return 结果
     */
    @Override
    public ApiResult uploadOnlineOrderRemarks(MallOrderOrderDTO resourceDTO) {
        MallOrderOrder mallOrderOrder = new MallOrderOrder();
        mallOrderOrder.setId(resourceDTO.getId());
        mallOrderOrder.setRemarks(resourceDTO.getRemarks());
        mallOrderOrderMapper.updateMallOrderOrderInfo(mallOrderOrder);
        return ApiResult.ok();
    }


//    @Override
//    @Transactional(rollbackFor = {Exception.class})
//    public ApiResult examineorderadmin(MallOrderOrderPO resourceDTO) {
//        if (resourceDTO.getSysUserId() != 1) {
//            return ApiResult.error("只有管理员才可审核订单");
//        }
//        long orderId = resourceDTO.getId();
//        Integer orderType = resourceDTO.getOrderType();
//        Map<String, String> orderInfoParams = new HashMap<>();
//        String receiverName = "";
//        String receiverPhone = "";
//        // 线下订单
//        if (orderType == 3) {
//            MallOrderOrder mallAppOrderOrder = mallOrderOrderMapper.selectMallOrderOrderById(orderId);
//            if (mallAppOrderOrder == null || "1".equals(mallAppOrderOrder.getDelFlag())) {
//                return ApiResult.error("订单已删除");
//            }
//            if ("1".equals(mallAppOrderOrder.getIsExamine())) {
//                return ApiResult.error("该订单已审核");
//            }
//            if (!"0".equals(mallAppOrderOrder.getStatus()) && !"1".equals(mallAppOrderOrder.getStatus())) {
//                return ApiResult.error("该订单状态不可审核");
//            }
//            MallOrderOrder appOrderOrder = new MallOrderOrder();
//            appOrderOrder.setId(orderId);
//            appOrderOrder.setIsExamine("1");
//            appOrderOrder.setExamineAt(DateUtils.getTime());
//            appOrderOrder.setStatus("2");
//            mallOrderOrderMapper.updateMallOrderOrder(appOrderOrder);
//            orderInfoParams.put("orderId", mallAppOrderOrder.getId().toString());
//            orderInfoParams.put("orderType", "3");
//            receiverName = mallAppOrderOrder.getReceiverName();
//            receiverPhone = mallAppOrderOrder.getReceiverPhone();
//        } else {
//            // 线上订单
//            MallOrderOrder onlineOrder = mallOrderOrderMapper.selectMallOrderOrderById(orderId);
//            if (onlineOrder == null || "1".equals(onlineOrder.getDelFlag())) {
//                return ApiResult.error("订单已删除");
//            }
//            if ("1".equals(onlineOrder.getIsExamine())) {
//                return ApiResult.error("该订单已审核");
//            }
//            if (!"1".equals(onlineOrder.getOrderStatus())) {
//                return ApiResult.error("该订单状态不可审核");
//            }
//            MallOrderOrder order = new MallOrderOrder();
//            order.setId(orderId);
//            order.setIsExamine("1");
//            order.setExamineAt(DateUtils.getTime());
//            order.setOrderStatus("2");
//            mallOrderOrderMapper.updateMallOrderOrder(order);
//            orderInfoParams.put("orderId", onlineOrder.getId().toString());
//            orderInfoParams.put("orderType", "0");
//            receiverName = onlineOrder.getReceiverName();
//            receiverPhone = onlineOrder.getReceiverPhone();
//        }
//
//        // 极光推送
//        String orderInfo = JSON.toJSONString(orderInfoParams);
//        // roleId：1-超级管理员，12-仓库管理员，13-财务，10-分公司管理员，11-业务员
//        Map<String, Object> newParams = new HashMap<>();// 超级管理员审核订单-仓库管理员接单推送
//        newParams.put("roleId", 12);
//        String[] userName = sysUserMapper.selectUserNameByParams(newParams);
//        if (userName.length > 0) {
//            System.out.println("超级管理员审核订单-仓库管理员接单推送");
//            try {
//                String url = "intent:#Intent;action=cn.jiguang.myaction;component=com.qdw.qianlengnet/com.qdw.qianlengnet.activity.OrderDetailsActivity;S.orderNo="+orderId+";i.orderType="+orderType+";end";
//                JsonObject jsonObject = new JsonObject();
//                jsonObject.addProperty("url",url);
//                jPushUtils.jPush(userName, receiverName + receiverPhone + "已通过审核，请及时接单", "仓库管理员接单", orderInfo, orderInfoParams, jsonObject);
//            } catch (Exception e) {
//                System.out.println("超级管理员审核订单-仓库管理员接单推送异常");
//            }
//        }
//        long salesmanId = -1L;
//        if (orderType == 3) {
//            MallAppOrderOrder mallAppOrderOrder = mallAppOrderOrderMapper.selectMallAppOrderOrderById(orderId);
//            if (mallAppOrderOrder.getSalesmanId() != null) {
//                MallSalesman mallSalesman = mallSalesmanMapper.selectMallSalesmanBySysUserId(mallAppOrderOrder.getSalesmanId());
//                if (mallSalesman != null) {
//                    salesmanId = mallSalesman.getId().longValue();
//                }
//            }
//        } else {
//            // 线上订单
//            MallOrderOrder onlineOrder = mallOrderOrderMapper.selectMallOrderOrderById(orderId);
//            if (onlineOrder.getSalesmanId() != null) {
//                salesmanId = onlineOrder.getSalesmanId().longValue();
//            }
//        }
//
//        // roleId：1-超级管理员，12-仓库管理员，13-财务，10-分公司管理员，11-业务员
//        Map<String, Object> salesmanParams = new HashMap<>();// 超级管理员审核订单-业务员查看推送
//        salesmanParams.put("roleId", 11);
//        salesmanParams.put("salesmanId", salesmanId);
//        String[] salesmanName = sysUserMapper.selectUserNameByParams(salesmanParams);
//        if (salesmanName.length > 0) {
//            System.out.println("超级管理员审核订单-业务员查看推送");
//            try {
//                String url = "intent:#Intent;action=cn.jiguang.myaction;component=com.qdw.qianlengnet/com.qdw.qianlengnet.activity.OrderDetailsActivity;S.orderNo="+orderId+";i.orderType="+orderType+";end";
//                JsonObject jsonObject = new JsonObject();
//                jsonObject.addProperty("url",url);
//
//                jPushUtils.jPush(salesmanName, receiverName + receiverPhone + "已通过管理审核，请及时查看", "业务员查看", orderInfo, orderInfoParams, jsonObject);
//            } catch (Exception e) {
//                System.out.println("超级管理员审核订单-业务员查看推送异常");
//            }
//        }
//
//        return ApiResult.ok("审核成功");
//    }
}
