package com.sqx.modules.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.UserBrowseDao;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.dao.UserMoneyDao;
import com.sqx.modules.app.dao.UserMoneyDetailsDao;
import com.sqx.modules.app.entity.UserBrowse;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.service.UserMoneyService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.coupon.dao.TbCouponUserDao;
import com.sqx.modules.coupon.entity.TbCouponUser;
import com.sqx.modules.errand.dao.TbIndentDao;
import com.sqx.modules.errand.entity.TbIndent;
import com.sqx.modules.errand.service.TbIndentService;
import com.sqx.modules.goods.dao.GoodsDao;
import com.sqx.modules.goods.dao.GoodsShopDao;
import com.sqx.modules.goods.dao.GoodsShopRelevancyDao;
import com.sqx.modules.goods.dao.GoodsSkuDao;
import com.sqx.modules.goods.entity.*;
import com.sqx.modules.message.dao.MessageInfoDao;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.order.dao.AppOrderDao;
import com.sqx.modules.order.dao.EvaluateDao;
import com.sqx.modules.order.dao.OrderGoodsDao;
import com.sqx.modules.order.entity.Evaluate;
import com.sqx.modules.order.entity.OrderGoods;
import com.sqx.modules.order.entity.TbOrder;
import com.sqx.modules.order.service.AppOrderService;
import com.sqx.modules.pay.controller.app.AliPayController;
import com.sqx.modules.pay.dao.PayDetailsDao;
import com.sqx.modules.pay.entity.PayDetails;
import com.sqx.modules.pay.service.PayDetailsService;
import com.sqx.modules.pay.service.WxErrService;
import com.sqx.modules.shop.service.ShopMessageService;
import com.sqx.modules.sys.dao.SysUserRoleDao;
import com.sqx.modules.utils.SenInfoCheckUtil;
import com.sqx.modules.utils.excel.ExcelData;
import com.sqx.modules.utils.fieYun.FeiYunUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.locks.ReentrantReadWriteLock;

@Service
@Slf4j
public class AppAppOrderServiceImpl extends ServiceImpl<AppOrderDao, TbOrder> implements AppOrderService {

    @Autowired
    private AppOrderDao appOrderDao;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderGoodsDao orderGoodsDao;
    @Autowired
    private GoodsSkuDao goodsSkuDao;
    @Autowired
    private TbCouponUserDao tbCouponUserDao;
    @Autowired
    private GoodsShopDao goodsShopDao;
    @Autowired
    private MessageInfoDao messageInfoDao;
    @Autowired
    private GoodsShopRelevancyDao goodsShopRelevancyDao;
    @Autowired
    private SysUserRoleDao sysUserRoleDao;
    @Autowired
    private UserMoneyDao userMoneyDao;
    @Autowired
    private WxErrService wxErrService;
    @Autowired
    private UserMoneyDetailsDao userMoneyDetailsDao;
    @Autowired
    private EvaluateDao evaluateDao;
    @Autowired
    private TbIndentService tbIndentService;
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private TbIndentDao tbIndentDao;
    @Autowired
    private UserBrowseDao userBrowseDao;
    @Autowired
    private PayDetailsDao payDetailsDao;
    @Autowired
    private ShopMessageService shopMessageService;
    private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock(true);

    @Override
    public Result insertOrder(Long userId, Long shopId, Long goodsId, Integer num, Long skuId, String skuMessage, Integer orderType) {
        reentrantReadWriteLock.writeLock().lock();
        try {
            return addOrder(userId, shopId, goodsId, num, skuId, skuMessage, orderType);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("下单异常：" + e.getMessage(), e);
        } finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请稍后再试！");
    }

    @Transactional
    public Result addOrder(Long userId, Long shopId, Long goodsId, Integer num, Long skuId, String skuMessage, Integer orderType) {
        //先判断该商品的库存是否足够
        GoodsShopRelevancy goodsShopRelevancy = goodsShopRelevancyDao.selectOne(new QueryWrapper<GoodsShopRelevancy>().eq("shop_id", shopId).eq("goods_id", goodsId));
        if (goodsShopRelevancy.getInventory() < num) {
            return Result.error("该商品库存不足！");
        }
        TbOrder order = new TbOrder();
        order = appOrderDao.selectOne(new QueryWrapper<TbOrder>()
                .eq("user_id", userId).eq("shop_id", shopId).eq("status", 1));
        Goods goods = goodsDao.selectById(goodsId);
        UserEntity userEntity = userDao.selectById(userId);
        TbOrder tbOrder = new TbOrder();
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        if (order == null) {
            tbOrder.setUserId(userId);
            tbOrder.setUserName(userEntity.getUserName());
            tbOrder.setPhone(userEntity.getPhone());
            tbOrder.setOrderNumber(getGeneralOrder());
            tbOrder.setIsPay(0);
            tbOrder.setDeleteFlag(0);
            tbOrder.setStatus(1);
            tbOrder.setShopId(shopId);
            //创建订单，订单发起人就是该登录用户
            tbOrder.setParentUserId(userId);
            tbOrder.setCreateTime(format);
            tbOrder.setAddGoodsTime(format);
            appOrderDao.insertOrder(tbOrder);

            TbOrder tbOrder1 = new TbOrder();
            tbOrder1.setOrderId(tbOrder.getOrderId());
            tbOrder1.setParentId(tbOrder.getOrderId());
            appOrderDao.updateById(tbOrder1);
            //添加订单-商品表
            Long orderId = tbOrder.getOrderId();
            OrderGoods orderGoods = new OrderGoods();
            orderGoods.setOrderId(orderId);
            orderGoods.setGoodsName(goods.getGoodsName());
            orderGoods.setSkuId(skuId);
            GoodsSku goodsSku = goodsSkuDao.selectById(skuId);
            orderGoods.setGoodsPrice(goodsSku.getSkuPrice());
            orderGoods.setSkuMessage(skuMessage);
            orderGoods.setGoodsNum(num);
            orderGoods.setGoodsPack(goods.getPackMoney());
            orderGoods.setGoodsPicture(goods.getGoodsCover());
            orderGoods.setGoodsId(goods.getGoodsId());
            orderGoods.setUserId(userId);
            orderGoodsDao.insert(orderGoods);
        } else {
            //添加订单-商品表
            Long orderId = order.getOrderId();
            OrderGoods orderGoods = orderGoodsDao.selectOne(new QueryWrapper<OrderGoods>().eq("order_id", orderId).eq("goods_id", goods.getGoodsId()).eq("sku_id", skuId).eq("user_id", userId));
            if (orderGoods != null) {
                orderGoods.setGoodsNum(orderGoods.getGoodsNum() + 1);
                orderGoodsDao.updateById(orderGoods);
            } else {
                orderGoods = new OrderGoods();
                orderGoods.setOrderId(orderId);
                orderGoods.setGoodsName(goods.getGoodsName());
                orderGoods.setSkuId(skuId);
                GoodsSku goodsSku = goodsSkuDao.selectById(skuId);
                orderGoods.setGoodsPrice(goodsSku.getSkuPrice());
                orderGoods.setSkuMessage(skuMessage);
                orderGoods.setGoodsNum(num);
                orderGoods.setGoodsPack(goods.getPackMoney());
                orderGoods.setGoodsPicture(goods.getGoodsCover());
                orderGoods.setGoodsId(goods.getGoodsId());
                orderGoods.setUserId(userId);
                orderGoodsDao.insert(orderGoods);
            }
            //修改订单表最后一次添加商品的时间
            TbOrder tbOrder1 = new TbOrder();
            tbOrder1.setOrderId(orderId);
            tbOrder1.setAddGoodsTime(format);
            appOrderDao.updateById(tbOrder1);
        }
        return Result.success();
    }


    @Override
    public Result shareTheBill(Long userId, Long shopId) {
        TbOrder tbOrder2 = appOrderDao.selectOne(new QueryWrapper<TbOrder>()
                .eq("user_id", userId).eq("shop_id", shopId).eq("status", 1));
        if (tbOrder2 == null) {
            String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            UserEntity userEntity = userDao.selectById(userId);
            TbOrder tbOrder = new TbOrder();
            tbOrder.setUserId(userId);
            tbOrder.setUserName(userEntity.getUserName());
            tbOrder.setPhone(userEntity.getPhone());
            tbOrder.setOrderNumber(getGeneralOrder());
            tbOrder.setIsPay(0);
            tbOrder.setDeleteFlag(0);
            tbOrder.setStatus(1);
            tbOrder.setShopId(shopId);
            //创建订单，订单发起人就是该登录用户
            tbOrder.setParentUserId(userId);
            tbOrder.setCreateTime(format);
            tbOrder.setAddGoodsTime(format);
            appOrderDao.insertOrder(tbOrder);
            Long orderId = tbOrder.getOrderId();
            TbOrder tbOrder1 = new TbOrder();
            tbOrder1.setOrderId(tbOrder.getOrderId());
            tbOrder1.setParentId(tbOrder.getOrderId());
            appOrderDao.updateById(tbOrder1);
            return Result.success().put("data", orderId);
        }
        return Result.success().put("data", tbOrder2.getOrderId());
    }

    @Override
    public Result selectShareTheBill(Long userId, Long orderId) {
        HashMap hashMap = new HashMap();
        TbOrder tbOrder = appOrderDao.selectById(orderId);
        if (tbOrder == null) {
            return Result.success();
        }
        List<OrderGoods> parentShareTheBill = orderGoodsDao.selectParentShareTheBill(orderId, tbOrder.getUserId());
        List<OrderGoods> orderGoodsList = orderGoodsDao.selectShareTheBill(orderId, tbOrder.getUserId());
        GoodsShop goodsShop = goodsShopDao.selectById(tbOrder.getShopId());
        hashMap.put("parentShareTheBill", parentShareTheBill);
        hashMap.put("orderGoodsList", orderGoodsList);
        hashMap.put("goodsShop", goodsShop);
        return Result.success().put("data", hashMap);
    }

    @Override
    public Result deleteByGoods(Long userId, Long id) {
        orderGoodsDao.delete(new QueryWrapper<OrderGoods>().eq("id", id).eq("user_id", userId));
        return Result.success();
    }

    @Override
    public Result deleteShareTheBill(Long userId, Long orderId) {
        orderGoodsDao.delete(new QueryWrapper<OrderGoods>().eq("order_id", orderId).eq("user_id", userId));
        return Result.success();
    }

    @Override
    public Result deleteOrder(Long userId, Long orderId) {
        TbOrder order = appOrderDao.selectById(orderId);
        if(order.getIsPay()==1){
            return Result.error("拼单已经支付，无法取消！");
        }
        appOrderDao.delete(new QueryWrapper<TbOrder>().eq("user_id", userId).eq("order_id", orderId));
        return Result.success();
    }

    @Override
    public IPage<Evaluate> getEvaluateList(Evaluate evaluate, Integer page, Integer limit) {
        Page<Evaluate> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
        }
        return evaluateDao.getEvaluateList(pages, evaluate);


    }

    @Override
    public Result deleteEvaluateById(Long userId, Long id) {

        Evaluate evaluate = evaluateDao.selectById(id);
        if (!evaluate.getUserId().equals(userId)) {
            return Result.error("你无权操作此评论");
        } else {
            return Result.upStatus(evaluateDao.deleteById(id));
        }
    }

    @Override
    public Result joinOrder(Long userId, Long orderId, Long shopId, Long goodsId, Integer num, Long skuId, String skuMessage) {
        //先判断该商品的库存是否足够
        GoodsShopRelevancy goodsShopRelevancy = goodsShopRelevancyDao.selectOne(new QueryWrapper<GoodsShopRelevancy>()
                .eq("shop_id", shopId).eq("goods_id", goodsId));
        if (goodsShopRelevancy.getInventory() < num) {
            return Result.error("该商品库存不足！");
        }
        Goods goods = goodsDao.selectById(goodsId);
        OrderGoods orderGoods = orderGoodsDao.selectOne(new QueryWrapper<OrderGoods>().eq("order_id", orderId).eq("goods_id", goods.getGoodsId()).eq("sku_id", skuId).eq("user_id", userId));
        if (orderGoods != null) {
            orderGoods.setGoodsNum(orderGoods.getGoodsNum() + 1);
            orderGoodsDao.updateById(orderGoods);
        } else {
            //添加订单-商品表
            orderGoods = new OrderGoods();
            orderGoods.setOrderId(orderId);
            orderGoods.setGoodsName(goods.getGoodsName());
            orderGoods.setSkuId(skuId);
            orderGoods.setGoodsPrice(goods.getGoodsMoney());
            orderGoods.setSkuMessage(skuMessage);
            orderGoods.setGoodsNum(num);
            orderGoods.setGoodsPack(goods.getPackMoney());
            orderGoods.setGoodsPicture(goods.getGoodsCover());
            orderGoods.setGoodsId(goods.getGoodsId());
            orderGoods.setUserId(userId);
            orderGoodsDao.insert(orderGoods);
        }

        return Result.success();
    }


    @Transactional
    @Override
    public Result buyGoods(Long userId, Long shopId, Long goodsId, Integer num, Long skuId, String skuMessage, Integer orderType) {
        //先判断该商品的库存是否足够
        GoodsShopRelevancy goodsShopRelevancy = goodsShopRelevancyDao.selectOne(new QueryWrapper<GoodsShopRelevancy>().eq("shop_id", shopId).eq("goods_id", goodsId));
        if (goodsShopRelevancy.getInventory() < num) {
            return Result.error("该商品库存不足！");
        }
        Goods goods = goodsDao.selectById(goodsId);
        UserEntity userEntity = userDao.selectById(userId);
        TbOrder tbOrder = new TbOrder();
        tbOrder.setUserId(userId);
        tbOrder.setUserName(userEntity.getUserName());
        tbOrder.setPhone(userEntity.getPhone());
        tbOrder.setOrderNumber(getGeneralOrder());
        tbOrder.setIsPay(0);
        tbOrder.setDeleteFlag(0);
        tbOrder.setStatus(2);
        tbOrder.setShopId(shopId);
        //创建订单，订单发起人就是该登录用户
        tbOrder.setParentUserId(userId);
        //   tbOrder.setPackMoney(goods.getPackMoney());
        //  tbOrder.setOrderType(orderType);
        tbOrder.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        /*if (orderType == 2) {
            CommonInfo one = commonInfoService.findOne(123);
            Double value = Double.valueOf(one.getValue());
            tbOrder.setErrandMoney(BigDecimal.valueOf(value));
        }*/
        appOrderDao.insertOrder(tbOrder);

        OrderGoods orderGoods = new OrderGoods();
        orderGoods.setOrderId(tbOrder.getOrderId());
        orderGoods.setGoodsName(goods.getGoodsName());
        orderGoods.setSkuId(skuId);
        GoodsSku goodsSku = goodsSkuDao.selectById(skuId);
        orderGoods.setGoodsPrice(goodsSku.getSkuPrice());
        orderGoods.setSkuMessage(skuMessage);
        orderGoods.setGoodsNum(num);
        orderGoods.setGoodsPack(goods.getPackMoney());
        orderGoods.setGoodsPicture(goods.getGoodsCover());
        orderGoods.setGoodsId(goods.getGoodsId());
        orderGoods.setUserId(userId);
        orderGoodsDao.insert(orderGoods);

        BigDecimal multiply = orderGoods.getGoodsPrice().multiply(new BigDecimal(num));
        TbOrder tbOrder1 = new TbOrder();
        tbOrder1.setOrderId(tbOrder.getOrderId());
        tbOrder1.setParentId(tbOrder.getOrderId());
        tbOrder1.setPayMoney(multiply);
        appOrderDao.updateById(tbOrder1);
        return Result.success().put("data", tbOrder.getOrderId());
    }

    @Override
    public Result echoOrder(Long userId, Long shopId, Long goodsId) {
        TbOrder tbOrder = appOrderDao.selectOne(new QueryWrapper<TbOrder>().eq("user_id", userId).eq("shop_id", shopId).eq("status", 1));
        if (tbOrder == null) {
            return Result.error("用户在该商铺没有订单");
        }
        Long orderId = tbOrder.getOrderId();
        List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>().eq("order_id", orderId).eq("goods_id", goodsId));
        return Result.success().put("data", orderGoodsList);
    }




    /*public Result insertOrder1(Long userId, Long shopId, Long goodsId, Integer num, Long skuId, String skuMessage, Integer orderType) {
        //判断该用户在该商店有没有订单，没有的话创建订单，有的话加入订单
        List<TbOrder> tbOrder1 = appOrderDao.selectList(new QueryWrapper<TbOrder>()
                .eq("user_id", userId).eq("shop_id", shopId).eq("status", 1));

        if(tbOrder1==null) {
            Goods goods = goodsDao.selectById(goodsId);
            UserEntity userEntity = userDao.selectById(userId);
            net.sf.json.JSONObject goodsJson = net.sf.json.JSONObject.fromObject(goods);

            TbOrder order = new TbOrder();
            order.setUserId(userId);
            order.setUserName(userEntity.getUserName());
            order.setPhone(userEntity.getPhone());
            order.setOrderNumber(getGeneralOrder());
            order.setIsPay(0);
            order.setDeleteFlag(0);
            order.setStatus(1);
        //    order.setNum(num);
            order.setShopId(shopId);
            //创建订单，订单发起人就是该登录用户
            order.setParentUserId(userId);
            order.setPackMoney(goods.getPackMoney());
            order.setOrderType(orderType);
            order.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            if (orderType == 2) {
                CommonInfo one = commonInfoService.findOne(121);
                Double value = Double.valueOf(one.getValue());
                order.setErrandMoney(BigDecimal.valueOf(value));
            }
            appOrderDao.insertOrder(order);
            TbOrder tbOrder = new TbOrder();
            tbOrder.setOrderId(order.getOrderId());
            tbOrder.setParentId(order.getOrderId());
            appOrderDao.updateById(tbOrder);
        }
        return Result.success();
    }*/


    @Override
    public TbOrder selectOrderByNum(String orderNum) {
        TbOrder tbOrder = appOrderDao.selectOne(new QueryWrapper<TbOrder>().eq("order_number", orderNum));
        return tbOrder;
    }

    @Override
    public Result selectAllOrder(Integer page, Integer limit, Integer status, String phone, Long shopId, String userName, String orderNumber, Integer orderType, String shopName) {
        Page<TbOrder> pages = new Page<>(page, limit);
        IPage<TbOrder> tbOrderIPage = appOrderDao.selectOrder(pages, status, phone, shopId, userName, orderNumber, orderType, shopName);
        for (int i = 0; i < tbOrderIPage.getRecords().size(); i++) {
            List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>()
                    .eq("order_id", tbOrderIPage.getRecords().get(i).getOrderId()));
            tbOrderIPage.getRecords().get(i).setOrderGoodsList(orderGoodsList);
            //todo
            /*BigDecimal packMoney = BigDecimal.valueOf(0);
            for (int a = 0; a < orderGoodsList.size(); a++) {
                packMoney = packMoney.add(tbOrderIPage.getRecords().get(i).getPackMoney());
            }
            tbOrderIPage.getRecords().get(i).setPackMoney(packMoney);*/
        }
        PageUtils pageUtils = new PageUtils(tbOrderIPage);
        return Result.success().put("data", pageUtils);
    }


    @Override
    public Result selectAllOrderAdmin(Integer page, Integer limit, Integer status, String phone, Long shopId, String userName,
                                      String orderNumber, Integer orderType, String shopName, String riderPhone,String startTime,String endTime) {
        Page<TbOrder> pages = new Page<>(page, limit);
        IPage<TbOrder> tbOrderIPage = appOrderDao.selectAllOrderAdmin(pages, status, phone, shopId, userName, orderNumber,
                orderType, shopName, riderPhone,startTime,endTime);
        for (int i = 0; i < tbOrderIPage.getRecords().size(); i++) {
            List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>()
                    .eq("order_id", tbOrderIPage.getRecords().get(i).getOrderId()));
            tbOrderIPage.getRecords().get(i).setOrderGoodsList(orderGoodsList);
        }
        PageUtils pageUtils = new PageUtils(tbOrderIPage);
        return Result.success().put("data", pageUtils);
    }

    @Override
    public ExcelData excelAllOrderAdmin(Integer status, String phone, Long shopId,
                                        String userName, String orderNumber, Integer orderType, String shopName,
                                        String riderPhone, String startTime, String endTime) {
        List<TbOrder> tbOrderIPage = appOrderDao.excelAllOrderAdmin( status, phone, shopId, userName, orderNumber, orderType,
                shopName, riderPhone,startTime,endTime);
        for (int i = 0; i < tbOrderIPage.size(); i++) {
            List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>()
                    .eq("order_id", tbOrderIPage.get(i).getOrderId()));
            tbOrderIPage.get(i).setOrderGoodsList(orderGoodsList);
        }
        ExcelData data = new ExcelData();
        data.setName("订单列表");
        List<String> titles = new ArrayList();
        titles.add("编号");titles.add("下单用户");titles.add("用户头像");titles.add("手机号");
        titles.add("商铺信息"); titles.add("订单类型");titles.add("配送信息");titles.add("骑手昵称");
        titles.add("骑手电话"); titles.add("订单号");titles.add("内容");titles.add("商品总价（元）");
        titles.add("优惠金额（元）"); titles.add("打包费（元/个 具体按照数量计算）");titles.add("跑腿费（元）");titles.add("支付金额（元）");
        titles.add("跑腿费说明"); titles.add("订单备注");titles.add("支付时间");titles.add("支付方式");
        titles.add("取餐号"); titles.add("状态");titles.add("是否转单");

        data.setTitles(titles);
        List<List<Object>> rows = new ArrayList();
        for(TbOrder order:tbOrderIPage){
            List<Object> row = new ArrayList();
            row.add(order.getOrderId());
            row.add(order.getUserName());
            row.add(order.getAvatar());
            row.add(order.getPhone());
            StringBuffer stringBuffer=new StringBuffer();
            stringBuffer.append("店铺名称：").append(StringUtils.isNotBlank(order.getShopName())?order.getShopName():"")
                    .append("\n").append("店铺电话：").append(StringUtils.isNotBlank(order.getShopPhone())?order.getShopPhone():"")
                    .append("\n").append("店铺地址：").append(StringUtils.isNotBlank(order.getDetailedAddress())?order.getDetailedAddress():"");
            row.add(stringBuffer.toString());
            if(order.getOrderType()!=null && order.getOrderType()==1){
                row.add("到店取餐");
            }else if(order.getOrderType()!=null && order.getOrderType()==2){
                row.add("外卖配送");
            }else{
                row.add("");
            }
            if(StringUtils.isNotEmpty(order.getAddress())){
                JSONObject jsonObject = JSONObject.parseObject(order.getAddress());

                stringBuffer=new StringBuffer();
                stringBuffer.append("订餐人：").append(jsonObject.getString("userName")).append("\n").append("订餐人电话：").append(jsonObject.getString("userPhone")).append("\n").append("订餐地址：").append(jsonObject.getString("addressDetail"));
                row.add(stringBuffer.toString());
            }else{
                row.add("-");
            }
            row.add(order.getRiderNickName());
            row.add(order.getRiderPhone());
            row.add(order.getOrderNumber());
            stringBuffer=new StringBuffer();
            BigDecimal sumGoodsPrice=BigDecimal.ZERO;
            List<OrderGoods> orderGoodsList = order.getOrderGoodsList();
            for(int i=0;i<orderGoodsList.size();i++){
                OrderGoods orderGoods = orderGoodsList.get(i);
                stringBuffer.append(i + 1).append(". 商品名：").append(orderGoods.getGoodsName()).append(",数量：").append(orderGoods.getGoodsNum()).append(",规格：").append(orderGoods.getSkuMessage());
                if(orderGoods.getGoodsPrice()!=null && orderGoods.getGoodsNum()!=null){
                    BigDecimal goodsPrice = orderGoods.getGoodsPrice().multiply(BigDecimal.valueOf(orderGoods.getGoodsNum()));
                    sumGoodsPrice=sumGoodsPrice.add(goodsPrice);
                }
            }
            row.add(stringBuffer.toString());
            row.add(sumGoodsPrice);
            row.add(order.getCouponMoney());
            row.add(order.getPackMoney());
            row.add(order.getErrandMoney());
            row.add(order.getPayMoney());

            row.add(order.getErrandMoneyIsShop());
            row.add(order.getPayTime());
            //支付方式  1微信支付  2余额支付  3支付宝支付
            if(order.getPayType()!=null && order.getPayType()==1){
                row.add("微信支付");
            }else if(order.getPayType()!=null && order.getPayType()==2){
                row.add("余额支付");
            }else if(order.getPayType()!=null && order.getPayType()==3){
                row.add("支付宝支付");
            }else{
                row.add("");
            }

            row.add(order.getOrderCode());
            //订单状态 0待结算 1待支付 2直接购买（未支付） 7商家待接单 8商家拒绝接单 6制作中  3待取餐/派送中 4已完成 5已取消
            if(order.getStatus()!=null && order.getStatus()==0){
                row.add("待结算");
            }else if(order.getStatus()!=null && order.getStatus()==1){
                row.add("待支付");
            }else if(order.getStatus()!=null && order.getStatus()==2){
                row.add("直接购买（未支付）");
            }else if(order.getStatus()!=null && order.getStatus()==3){
                row.add("待取餐/派送中");
            }else if(order.getStatus()!=null && order.getStatus()==4){
                row.add("已完成");
            }else if(order.getStatus()!=null && order.getStatus()==5){
                row.add("已取消");
            }else if(order.getStatus()!=null && order.getStatus()==6){
                row.add("制作中");
            }else if(order.getStatus()!=null && order.getStatus()==7){
                row.add("商家待接单");
            }else if(order.getStatus()!=null && order.getStatus()==8){
                row.add("商家拒绝接单");
            }else{
                row.add("");
            }
            if(order.getIsRider()!=null && order.getIsRider()==1){
                row.add("是");
            }else{
                row.add("");
            }
            rows.add(row);
        }
        data.setRows(rows);
        return data;
    }


    @Override
    public Result selectOrderByUserId(Long userId, String date, String dateType) {
        HashMap hashMap = new HashMap();
        int count = appOrderDao.selectCountOrderByUserId(userId, date, dateType);
        BigDecimal bigDecimal = appOrderDao.selectSunMoneyByUserId(userId, date, dateType);
        hashMap.put("bigDecimal", bigDecimal);
        hashMap.put("count", count);
        return Result.success().put("data", hashMap);
    }

    @Override
    public Result selectOrderDetails(Integer page, Integer limit, Long userId) {
        Page<TbOrder> pages = new Page<>(page, limit);
        IPage<TbOrder> tbOrderIPage = appOrderDao.selectOrderDetails(pages, userId);
        for (int i = 0; i < tbOrderIPage.getRecords().size(); i++) {
            Long orderId = tbOrderIPage.getRecords().get(i).getOrderId();
            List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>().eq("order_id", orderId));
            tbOrderIPage.getRecords().get(i).setOrderGoodsList(orderGoodsList);
        }


        PageUtils pageUtils = new PageUtils(tbOrderIPage);
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result waitTakeFood(Long userId, Integer orderType, Integer page, Integer limit, Integer status) {
        Page<TbOrder> pages = new Page<>(page, limit);
        IPage<TbOrder> tbOrderIPage = appOrderDao.waitTakeFood(pages, userId, orderType, status);
        List<TbOrder> records = tbOrderIPage.getRecords();
        int size = records.size();
        for (int i = 0; i < size; i++) {
            List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>()
                    .eq("order_id", records.get(i).getOrderId()));
            tbOrderIPage.getRecords().get(i).setOrderGoodsList(orderGoodsList);
        }
        PageUtils pageUtils = new PageUtils(tbOrderIPage);
        return Result.success().put("data", pageUtils);
    }

    @Override
    public List<TbOrder> selectOrderByParentId(Long parentId) {
        List<TbOrder> tbOrder = appOrderDao.selectList(new QueryWrapper<TbOrder>().eq("parent_id", parentId));
        return tbOrder;
    }

    @Override
    public Result selectOrderById(Long orderId) {
        TbOrder tbOrder = appOrderDao.selectByOrderId(orderId);
        int i = appOrderDao.selectCountOrderByTime(tbOrder.getPayTime(), tbOrder.getShopId());
        tbOrder.setCountOrder(i);
        if (tbOrder.getCouponId() != null) {
            TbCouponUser tbCouponUser = tbCouponUserDao.selectById(tbOrder.getCouponId());
            tbOrder.setCouponMoney(tbCouponUser.getMoney());
        }
        List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>().eq("order_id", tbOrder.getOrderId()));
        tbOrder.setOrderGoodsList(orderGoodsList);
        return Result.success().put("data", tbOrder);
    }

    @Override
    public TbOrder selectOrderByIds(Long orderId) {
        TbOrder tbOrder = appOrderDao.selectByOrderId(orderId);
        int i = appOrderDao.selectCountOrderByTime(tbOrder.getPayTime(), tbOrder.getShopId());
        tbOrder.setCountOrder(i);
        if (tbOrder.getCouponId() != null) {
            TbCouponUser tbCouponUser = tbCouponUserDao.selectById(tbOrder.getCouponId());
            tbOrder.setCouponMoney(tbCouponUser.getMoney());
        }
        List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>().eq("order_id", tbOrder.getOrderId()));
        tbOrder.setOrderGoodsList(orderGoodsList);
        GoodsShop goodsShop = goodsShopDao.selectById(tbOrder.getShopId());
        if (goodsShop != null) {
            tbOrder.setShopName(goodsShop.getShopName());
        }
        return tbOrder;
    }


    @Transactional
    @Override
    public Result updateGoodsNum(Long orderGoodsId, Integer type, Integer num, Long shopId) {
        /*reentrantReadWriteLock.writeLock().lock();
        try{*/
        //type = 1增加商品数  = 2 减少商品数

        OrderGoods orderGoods = orderGoodsDao.selectById(orderGoodsId);
        if(orderGoods==null){
            return Result.error("系统繁忙，请稍后再试！");
        }
        GoodsShopRelevancy goodsShopRelevancy = goodsShopRelevancyDao.selectOne(new QueryWrapper<GoodsShopRelevancy>()
                .eq("shop_id", shopId)
                .eq("goods_id", orderGoods.getGoodsId()));

        if (type == 1 && goodsShopRelevancy.getInventory() <= orderGoods.getGoodsNum()) {
            return Result.error("该商品库存不足，不能再添加商品！");
        }
        if (type == 1) {
            OrderGoods orderGoods1 = new OrderGoods();
            orderGoods1.setId(orderGoodsId);
            orderGoods1.setGoodsNum(orderGoods.getGoodsNum() + num);
            orderGoodsDao.updateById(orderGoods1);
        } else {
            if (orderGoods.getGoodsNum() <= 1) {
                orderGoodsDao.deleteById(orderGoodsId);
            } else {
                OrderGoods orderGoods2 = new OrderGoods();
                orderGoods2.setId(orderGoodsId);
                orderGoods2.setGoodsNum(orderGoods.getGoodsNum() - num);
                orderGoodsDao.updateById(orderGoods2);
            }
        }
        /*}catch (Exception e){
            e.printStackTrace();
            log.error("减少购物车商品出错："+e.getMessage(),e);
        }finally {
            reentrantReadWriteLock.writeLock().unlock();
        }*/
        return Result.success();
    }

    @Override
    public Result emptyShoppingTrolley(Long userId, Long shopId) {
        appOrderDao.delete(new QueryWrapper<TbOrder>().eq("user_id", userId).eq("shop_id", shopId).eq("status", 1));
        return Result.success();
    }

    @Override
    public Result employCoupon(Long userId, Long parentId, Long couponId) {
        TbOrder tbOrder = appOrderDao.selectById(parentId);
        TbCouponUser tbCouponUser = tbCouponUserDao.selectById(couponId);

        TbOrder tbOrder1 = new TbOrder();
        tbOrder1.setOrderId(tbOrder.getOrderId());
        tbOrder1.setCouponId(tbCouponUser.getId());
        appOrderDao.updateById(tbOrder1);
        return Result.success();
    }

    @Override
    public Result deleteCouponByOrderId(Long orderId) {
        appOrderDao.deleteCouponByOrderId(orderId);
        return Result.success();
    }

    @Override
    public Result print(Long orderId) {
        TbOrder tbOrder = selectOrderByIds(orderId);
        Long shopId = tbOrder.getShopId();
        GoodsShop goodsShop = goodsShopDao.selectById(shopId);
        if (StringUtils.isNotEmpty(goodsShop.getSnCode())) {
            FeiYunUtils.print(goodsShop.getSnCode(), null, tbOrder);
        } else {
            return Result.error("当前商家未绑定打印机！");
        }
        return Result.success();
    }

    @Transactional
    public Result updateOrders(TbOrder order) {
        String format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        TbOrder tbOrder = selectOrderByIds(order.getOrderId());
        if (order.getStatus() == 6) {
            if (tbOrder.getStatus().equals(6)) {
                return Result.success();
            }
            //商家接单
            order.setShopReceivingTime(format1);
            //设置小程序消息推送
            CommonInfo one = commonInfoService.findOne(269);
            List<String> msgList = new ArrayList<>();
            Long shopId = tbOrder.getShopId();
            GoodsShop goodsShop = shopMessageService.selectShopId(shopId);
            String shopName = goodsShop.getShopName();
            String orderNum1 = tbOrder.getOrderNumber();
            msgList.add("商家已接单");
            msgList.add(orderNum1);
            msgList.add(shopName);
            msgList.add(format1);
            UserEntity userEntity = userDao.selectById(tbOrder.getUserId());
            userService.pushToSingle("商家已接单", "亲爱的用户您好，商家已接单，请耐心等待！", userEntity.getClientid());

            //计算商户应得金额

            BigDecimal shopRate = goodsShop.getShopRate();
            BigDecimal sumMoney = tbOrder.getPayMoney();
            if (tbOrder.getCouponId() != null) {
                TbCouponUser tbCouponUser = tbCouponUserDao.selectById(tbOrder.getCouponId());
                sumMoney = tbOrder.getPayMoney().add(tbCouponUser.getMoney());
            }
            if (tbOrder.getAutoSendOrder() == 0) {
                //再减去商户需要支付的配送费
                sumMoney = sumMoney.subtract(goodsShop.getErrandMoney());
            }

            BigDecimal shopMoney = sumMoney.multiply(shopRate);
            shopMoney = (shopMoney.setScale(2, BigDecimal.ROUND_DOWN));
            tbOrder.setShopIncomeMoney(shopMoney);

            SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 1);
            if (StringUtils.isNotEmpty(goodsShop.getSnCode())) {
                FeiYunUtils.print(goodsShop.getSnCode(), null, tbOrder);
            }
        } else if (order.getStatus() == 3) {
            if (tbOrder.getStatus().equals(3)) {
                return Result.success();
            }
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setTitle("餐品制作完成");
            if (tbOrder.getOrderType() == 1) {
                messageInfo.setContent("您的餐品已制作完成，请及时取餐");
            } else if (tbOrder.getOrderType() == 2) {
                messageInfo.setContent("您的餐品已制作完成，正在配送中");
                //如果是外卖订单,则修改外卖订单的状态
                GoodsShop goodsShop = goodsShopDao.selectById(tbOrder.getShopId());
                if (goodsShop.getAutoSendOrder() == 0) {
                    TbIndent tbIndent = tbIndentDao.selectOne(new QueryWrapper<TbIndent>().eq("order_id", tbOrder.getOrderId()));
                    TbIndent tbIndent1 = new TbIndent();
                    tbIndent1.setIndentId(tbIndent.getIndentId());
                    tbIndent1.setCreateTime(format1);
                    tbIndent1.setIndentState("2");
                    tbIndentService.updateById(tbIndent1);
                    tbIndentService.sendNewIndentMsg(tbIndent);
                }
            }
            messageInfo.setCreateAt(format1);
            messageInfo.setUserId(tbOrder.getUserId().toString());
            messageInfoDao.insert(messageInfo);
            //设置小程序消息推送
            CommonInfo one = commonInfoService.findOne(269);
            List<String> msgList = new ArrayList<>();
            Long shopId = tbOrder.getShopId();
            GoodsShop goodsShop = goodsShopDao.selectById(shopId);
            String shopName = goodsShop.getShopName();
            String orderNum1 = tbOrder.getOrderNumber();
            /*msgList.add(shopName);
            msgList.add(orderNum1);
            msgList.add("已制作完成");
            msgList.add(format1);*/

            msgList.add("已制作完成");
            msgList.add(orderNum1);
            msgList.add(shopName);
            msgList.add(format1);
            /*
            if(tbOrder.getOrderType()==1){
                msgList.add("您的餐品已制作完成，请及时取餐");
            }else if(tbOrder.getOrderType()==2){
                msgList.add("您的餐品已制作完成，正在配送中");
            }*/
            UserEntity userEntity = userDao.selectById(tbOrder.getUserId());
            SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 1);
            userService.pushToSingle("制作完成", "亲爱的用户您好，您的订单已制作完成，请耐心等待配送！", userEntity.getClientid());
        } else if (order.getStatus() == 4) {
            if (tbOrder.getStatus().equals(4)) {
                return Result.success();
            }
            log.info("操作完成订单4："+order.getOrderId());
            Result result = this.accomplishOrder(order.getOrderId());
            if("500".equals(String.valueOf(result.get("code")))){
                return result;
            }
            //管理端完成订单，则消息通知用户
            //添加消息记录
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setTitle("订单完成");
            messageInfo.setContent("您的订单已完成，欢迎下次光临");
            messageInfo.setCreateAt(format1);
            messageInfo.setUserId(tbOrder.getUserId().toString());
            messageInfoDao.insert(messageInfo);
            //设置小程序消息推送
            CommonInfo one = commonInfoService.findOne(269);
            List<String> msgList = new ArrayList<>();
            Long shopId = tbOrder.getShopId();
            GoodsShop goodsShop = goodsShopDao.selectById(shopId);
            String shopName = goodsShop.getShopName();
            String orderNum1 = tbOrder.getOrderNumber();
            msgList.add("订单完成");
            msgList.add(orderNum1);
            msgList.add(shopName);
            msgList.add(format1);
            UserEntity userEntity = userDao.selectById(tbOrder.getUserId());
            SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 1);
            userService.pushToSingle("订单完成", "亲爱的用户您好，您的订单已完成，欢迎下次光临！", userEntity.getClientid());
        } else if (order.getStatus() == 8) {
            if (tbOrder.getStatus().equals(8) || tbOrder.getStatus().equals(5)) {
                return Result.success();
            }
            UserEntity userEntity = userDao.selectById(tbOrder.getUserId());
            //已支付判断支付方式
            if (tbOrder.getPayType() == 2) {
                //余额支付，直接退还钱包
                userMoneyDao.updateMayMoney(1, tbOrder.getUserId(), tbOrder.getPayMoney().doubleValue());
            } else if (tbOrder.getPayType() == 1) {
                PayDetails payDetails = payDetailsDao.selectByOrderId(tbOrder.getOrderNumber());
                boolean b = wxErrService.wxRefund(payDetails);
                if (!b) {
                    return Result.error("退款失败，请联系客服！");
                }
            } else {
                PayDetails payDetails = payDetailsDao.selectByOrderId(tbOrder.getOrderNumber());
                String code = AliPayController.alipayRefund(payDetails);
                if (StringUtils.isNotBlank(code)) {
                    log.error(code);
                    JSONObject jsonObject = JSON.parseObject(code);
                    JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                    String code1 = alipay_trade_refund_response.getString("code");
                    if (!"10000".equals(code1)) {
                        return Result.error("退款失败！" + alipay_trade_refund_response.getString("sub_msg"));
                    }
                } else {
                    return Result.error("退款失败！");
                }
            }
            tbOrder.setStatus(5);
            appOrderDao.updateById(tbOrder);
            //添加退款记录
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setUserId(tbOrder.getUserId());
            userMoneyDetails.setTitle("退款");
            userMoneyDetails.setType(1);
            userMoneyDetails.setClassify(3);
            userMoneyDetails.setState(2);
            userMoneyDetails.setMoney(tbOrder.getPayMoney());
            userMoneyDetails.setContent("商家拒绝接单，退款到账：" + tbOrder.getPayMoney() + "元，退款按原路返回");
            userMoneyDetails.setCreateTime(format1);
            userMoneyDetailsDao.insert(userMoneyDetails);
            //判断是否使用优惠券
            if (tbOrder.getCouponId() != null) {
                TbCouponUser tbCouponUser = tbCouponUserDao.selectById(tbOrder.getCouponId());
                tbCouponUser.setStatus(0);
                tbCouponUserDao.updateById(tbCouponUser);
            }


            //设置小程序消息推送
            CommonInfo one = commonInfoService.findOne(266);
            List<String> msgList = new ArrayList<>();
            msgList.add(tbOrder.getOrderNumber());
            msgList.add("商家拒绝接单订单");
            msgList.add(tbOrder.getPayMoney().toString());
            msgList.add(format1);
            SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 3);
            userService.pushToSingle("下单失败", "抱歉，商家已拒绝接单，给您带来不便请谅解，如有疑问可联系客服！", userEntity.getClientid());

            List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>().eq("order_id", tbOrder.getOrderId()));
            for (int a = 0; a < orderGoodsList.size(); a++) {
                OrderGoods orderGoods = orderGoodsList.get(a);
                Integer goodsNum = orderGoods.getGoodsNum();
                Long goodsId = orderGoodsList.get(a).getGoodsId();
                GoodsShopRelevancy goodsShopRelevancy = goodsShopRelevancyDao.selectOne(new QueryWrapper<GoodsShopRelevancy>()
                        .eq("shop_id", tbOrder.getShopId()).eq("goods_id", goodsId));
                GoodsShopRelevancy goodsShopRelevancy1 = new GoodsShopRelevancy();
                goodsShopRelevancy1.setId(goodsShopRelevancy.getId());
                goodsShopRelevancy1.setSales(goodsShopRelevancy.getSales() - goodsNum);//加销量
                goodsShopRelevancy1.setInventory(goodsShopRelevancy.getInventory() + goodsNum);//减库存
                goodsShopRelevancyDao.updateById(goodsShopRelevancy1);
                goodsShopDao.updateShopSales(2, goodsNum, goodsShopRelevancy.getShopId());
            }

            return Result.success("取消订单成功！");
        }
        order.setUpdateTime(format1);
        baseMapper.updateById(order);
        return Result.success();
    }


    @Override
    public Result updateOrder(TbOrder order) {
        reentrantReadWriteLock.writeLock().lock();
        try {
            return updateOrders(order);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("修改订单异常：" + e.getMessage(), e);
        } finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请稍后再试！");
    }


    @Override
    public Result accomplishOrder(Long orderId) {
        reentrantReadWriteLock.writeLock().lock();
        try {
            return accomplishOrders(orderId,1);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("完成订单异常：" + e.getMessage(), e);
        } finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请稍后再试！");
    }

    /**
     *
     * @param orderId
     * @param type 1用户操作 2自动任务超时直接完成订单
     * @return
     */
    @Transactional
    @Override
    public Result accomplishOrders(Long orderId, Integer type) {
        log.info("订单id:"+orderId+"，类型："+type);
        TbOrder tbOrder = appOrderDao.selectById(orderId);
        log.info("订单状态 :"+tbOrder.getStatus());
        if (tbOrder.getStatus().equals(4)) {
            return Result.success();
        }
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        if (tbOrder.getAutoSendOrder() != null && tbOrder.getAutoSendOrder().equals(0)) {
            TbIndent indent = tbIndentService.getOne(new QueryWrapper<TbIndent>().eq("order_id", orderId));
            if (type==1){
                if (indent == null || !"4".equals(indent.getIndentState())) {
                    return Result.error("请等待骑手送达！");
                }
            }

            tbOrder.setStatus(4);
            appOrderDao.updateById(tbOrder);
            //修改跑腿订单的状态和给骑手佣金
            indent.setIndentState("6");
            indent.setFinishTime(DateUtils.format(new Date()));
            tbIndentService.updateById(indent);
            tbIndentService.finshIndent(tbOrder.getUserId(), indent.getIndentNumber());
        } else {
            if (tbOrder.getStatus().equals(4)) {
                return Result.success();
            }

            tbOrder.setStatus(4);
            appOrderDao.updateById(tbOrder);
        }


        GoodsShop goodsShop = shopMessageService.selectShopId(tbOrder.getShopId());
        //计算商户应得金额

        BigDecimal shopRate = goodsShop.getShopRate();
        BigDecimal sumMoney = tbOrder.getPayMoney();
        BigDecimal couponMoney = BigDecimal.ZERO;
        Long shopIds = -1L;
        if (tbOrder.getCouponId() != null) {
            TbCouponUser tbCouponUser = tbCouponUserDao.selectById(tbOrder.getCouponId());
            sumMoney = tbOrder.getPayMoney().add(tbCouponUser.getMoney());
            couponMoney = tbCouponUser.getMoney();
            shopIds = tbCouponUser.getShopId();
        }

        BigDecimal errandMoney = BigDecimal.ZERO;
        if (tbOrder.getOrderType() != 1) {
            //判断是否达到商家满减  如果达到商家满减 跑腿费让商家承担
            if(tbOrder.getAutoSendOrder()!=null && tbOrder.getAutoSendOrder()==0){
                errandMoney = tbOrder.getErrandMoney();
                /*if(!"本单已达到商家满减金额，跑腿费由商家承担".equals(tbOrder.getErrandMoneyIsShop())){
                    sumMoney = sumMoney.subtract(tbOrder.getErrandMoney());
                }*/
                sumMoney = sumMoney.subtract(tbOrder.getErrandMoney());
            }else{
                sumMoney = sumMoney.subtract(tbOrder.getErrandMoney());
                errandMoney = tbOrder.getErrandMoney();
            }

        }
        BigDecimal shopMoney = sumMoney.multiply(shopRate);

        shopMoney = (shopMoney.setScale(2, BigDecimal.ROUND_DOWN));
        BigDecimal pingRate = sumMoney.subtract(shopMoney);

        //这里再判断 是否是商家优惠券  如果是商家优惠券  这笔钱商家承担
        if (shopIds != -1 && shopIds != 0) {
            shopMoney = shopMoney.subtract(couponMoney);
        }
        if(tbOrder.getAutoSendOrder()!=null && tbOrder.getAutoSendOrder()==1){
            //如果达到商家满减 则商家不加上配送费
            if(!"本单已达到商家满减金额，跑腿费由商家承担".equals(tbOrder.getErrandMoneyIsShop())){
                shopMoney=shopMoney.add(tbOrder.getErrandMoney());
            }
        }else{
            /*if("本单已达到商家满减金额，跑腿费由商家承担".equals(tbOrder.getErrandMoneyIsShop())){
                shopMoney=shopMoney.subtract(tbOrder.getErrandMoney());
            }*/
        }


        tbOrder.setShopIncomeMoney(shopMoney);
        appOrderDao.updateById(tbOrder);
        //添加商户用户钱包收入记录
        UserMoneyDetails userMoneyDetails1 = new UserMoneyDetails();
        userMoneyDetails1.setShopId(goodsShop.getShopId());
        userMoneyDetails1.setTitle("商户订单收入，订单号：" + tbOrder.getOrderNumber());
//        userMoneyDetails1.setContent("商户本单收入金额：" + shopMoney + "元");
        if (tbOrder.getOrderType() != 1) {
            //订单金额： 优惠券金额：  用户实付金额：   跑腿费：   平台服务费：  到账金额：（本单为平台优惠券，平台补贴）
            //订单金额： 商家优惠券：  用户实付金额：   跑腿费：   平台服务费：  到账金额：（本单为商家优惠券，商家补贴）
            if (shopIds == -1) {
                //未使用优惠券
                userMoneyDetails1.setContent("订单金额：" + tbOrder.getPayMoney() + ",用户实付金额:" + tbOrder.getPayMoney() + ",其中跑腿费:" + errandMoney + "（" + tbOrder.getErrandMoneyIsShop() + "）,平台服务费:" + pingRate + "，到账金额:" + shopMoney);
            } else if (shopIds == 0) {
                //使用平台优惠券
                sumMoney = tbOrder.getPayMoney().add(couponMoney);
                userMoneyDetails1.setContent("订单金额：" + sumMoney + ",优惠券金额：" + couponMoney + "，用户实付金额:" + tbOrder.getPayMoney() + ",其中跑腿费:" + errandMoney + "（" + tbOrder.getErrandMoneyIsShop() + "）,平台服务费:" + pingRate + "，到账金额:" + shopMoney + "（本单为平台优惠券，平台补贴）");
            } else {
                //使用商家优惠券
                sumMoney = tbOrder.getPayMoney().add(couponMoney);
                userMoneyDetails1.setContent("订单金额：" + sumMoney + ",优惠券金额：" + couponMoney + "，用户实付金额:" + tbOrder.getPayMoney() + ",其中跑腿费:" + errandMoney + "（" + tbOrder.getErrandMoneyIsShop() + "）,平台服务费:" + pingRate + "，到账金额:" + shopMoney + "（本单为商家优惠券，商家补贴）");
            }
        } else {
            if (shopIds == -1) {
                //未使用优惠券
                userMoneyDetails1.setContent("订单金额：" + tbOrder.getPayMoney() + ",用户实付金额:" + tbOrder.getPayMoney() + ",其中跑腿费:" + errandMoney + "（" + tbOrder.getErrandMoneyIsShop() + "）,平台服务费:" + pingRate + "，到账金额:" + shopMoney);
            } else if (shopIds == 0) {
                //使用平台优惠券
                sumMoney = tbOrder.getPayMoney().add(couponMoney);
                userMoneyDetails1.setContent("订单金额：" + sumMoney + ",优惠券金额：" + couponMoney + "，用户实付金额:" + tbOrder.getPayMoney() + ",平台服务费:" + pingRate + "，到账金额:" + shopMoney + "（本单为平台优惠券，平台补贴）");
            } else {
                //使用商家优惠券
                sumMoney = tbOrder.getPayMoney().add(couponMoney);
                userMoneyDetails1.setContent("订单金额：" + sumMoney + ",优惠券金额：" + couponMoney + "，用户实付金额:" + tbOrder.getPayMoney() + ",平台服务费:" + pingRate + "，到账金额:" + shopMoney + "（本单为商家优惠券，商家补贴）");
            }
        }

        userMoneyDetails1.setType(1);
        userMoneyDetails1.setClassify(3);
        userMoneyDetails1.setMoney(shopMoney);
        userMoneyDetails1.setCreateTime(format);
        userMoneyDetails1.setState(2);
        userMoneyDetailsDao.insert(userMoneyDetails1);
        //将用户支付的金额转入商户用户钱包
        userMoneyService.updateMoney(1, goodsShop.getUserId(), shopMoney.doubleValue());
        //管理端完成订单，则消息通知用户
        //添加消息记录
        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setTitle("订单完成");
        messageInfo.setContent("您的订单已完成，欢迎下次光临");
        messageInfo.setCreateAt(format);
        messageInfo.setUserId(tbOrder.getUserId().toString());
        messageInfoDao.insert(messageInfo);
        //设置小程序消息推送
        CommonInfo one = commonInfoService.findOne(269);
        List<String> msgList = new ArrayList<>();

        String shopName = goodsShop.getShopName();
        String orderNum1 = tbOrder.getOrderNumber();
        msgList.add("订单完成");
        msgList.add(orderNum1);
        msgList.add(shopName);
        msgList.add(format);
        UserEntity userEntity = userDao.selectById(tbOrder.getUserId());
        SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 1);
        userService.pushToSingle("订单完成", "您的订单已完成，欢迎下次光临！", userEntity.getClientid());
        TbIndent indent = tbIndentService.getOne(new QueryWrapper<TbIndent>().eq("order_id", orderId));
        String shopTemplate = commonInfoService.findOne(354).getValue();
        List<String> msgListShop = new ArrayList<>();
        msgListShop.add(indent.getIndentNumber());
        msgListShop.add("订单完成");
        msgListShop.add(DateUtils.format(new Date()));
        UserEntity shopUser = userService.selectUserById(goodsShop.getUserId());
        SenInfoCheckUtil.sendShopMsg(shopUser.getShopOpenId(), shopTemplate, msgListShop, 9);

        return Result.success();
    }

    @Scheduled(cron = "0 */10 * * * ?")
    public void orderEnd() {
        CommonInfo one = commonInfoService.findOne(268);
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        List<TbOrder> orderList = appOrderDao.selectList(new QueryWrapper<TbOrder>().eq("status", 3));
        for (TbOrder tbOrder : orderList) {
            LocalDateTime updateTime = LocalDateTime.parse(tbOrder.getUpdateTime(), df);
            //计算当前订单什么时候超时完成
            LocalDateTime overDateTime = updateTime.plusHours(Integer.parseInt(one.getValue()));
            if (LocalDateTime.now().isAfter(overDateTime)) {
                log.info("操作完成订单6："+tbOrder.getOrderId());
                accomplishOrders(tbOrder.getOrderId(),2);
                //管理端完成订单，则消息通知用户
                //添加消息记录
                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setState(String.valueOf(5));
                messageInfo.setTitle("订单完成");
                messageInfo.setContent("您的订单已完成，欢迎下次光临");
                messageInfo.setCreateAt(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                messageInfo.setUserId(tbOrder.getUserId().toString());
                messageInfoDao.insert(messageInfo);
                //设置小程序消息推送
                CommonInfo one1 = commonInfoService.findOne(269);
                List<String> msgList = new ArrayList<>();
                Long shopId = tbOrder.getShopId();
                GoodsShop goodsShop = goodsShopDao.selectById(shopId);
                String orderNum1 = tbOrder.getOrderNumber();
                msgList.add("订单完成");
                msgList.add(orderNum1);
                if (goodsShop != null && goodsShop.getShopName() != null) {
                    String shopName = goodsShop.getShopName();
                    msgList.add(shopName);
                } else {
                    msgList.add("");
                }
                msgList.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                UserEntity userEntity = userDao.selectById(tbOrder.getUserId());
                if (userEntity != null && userEntity.getOpenId() != null) {
                    SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one1.getValue(), msgList, 1);
                    userService.pushToSingle("订单完成", "亲爱的用户您好，您的订单已完成，欢迎下次光临！", userEntity.getClientid());
                }

            }

        }
    }

    @Transactional
    @Override
    public Result insertEvaluate(Evaluate evaluate) {
        evaluate.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        evaluateDao.insert(evaluate);
        TbOrder tbOrder = new TbOrder();
        tbOrder.setCommentFlag(1);
        appOrderDao.update(tbOrder, new QueryWrapper<TbOrder>().eq("order_number", evaluate.getOrderNumber()));
        //重新计算并修改该商铺评分
        Evaluate evaluate1 = evaluateDao.selectScoreByShopId(evaluate.getShopId());
        Double score = evaluate1.getAllScore() / Double.valueOf(evaluate1.getEvaluatecount());
        GoodsShop goodsShop = new GoodsShop();
        goodsShop.setShopId(evaluate.getShopId());
        goodsShop.setShopScore(score);
        goodsShopDao.updateById(goodsShop);
        return Result.success();
    }

    @Override
    public Result selectShoppingTrolley(Long userId) {
        List<TbOrder> tbOrderIPage = appOrderDao.selectShoppingTrolley(userId);
        for (int i = 0; i < tbOrderIPage.size(); i++) {
            Long orderId = tbOrderIPage.get(i).getOrderId();
            List<OrderGoods> orderGoods = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>().eq("order_id", orderId));
            tbOrderIPage.get(i).setOrderGoodsList(orderGoods);
        }
        return Result.success().put("data", tbOrderIPage);
    }

    @Override
    public Result selectShoppingTrolleyByShopId(Long userId, Long shopId) {
        TbOrder tbOrders = appOrderDao.selectShoppingTrolleyByShopId(userId, shopId);
        List<OrderGoods> orderGoods = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>().eq("order_id", tbOrders.getOrderId()));
        tbOrders.setOrderGoodsList(orderGoods);
        return Result.success().put("data", tbOrders);
    }


    @Override
    public Result userCancelOrder(Long orderId){
        reentrantReadWriteLock.writeLock().lock();
        try {
            return userCancelOrders(orderId);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请稍后再试！");
    }


    @Transactional
    public Result userCancelOrders(Long orderId) {
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        TbOrder tbOrder = appOrderDao.selectById(orderId);
        if (tbOrder.getStatus().equals(5) || tbOrder.getStatus().equals(8)) {
            return Result.success();
        }
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MINUTE, -1);
        Date parse = null;
        if (tbOrder.getStatus() == 6) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                parse = sdf.parse(tbOrder.getShopReceivingTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        MessageInfo messageInfo1 = new MessageInfo();
        messageInfo1.setTitle("用户取消订单");
        messageInfo1.setCreateAt(DateUtils.format(new Date()));
        messageInfo1.setContent("用户取消订单，订单号：" + tbOrder.getOrderNumber());
        messageInfo1.setShopId(tbOrder.getShopId());
        messageInfo1.setReadFlag(2);
        messageInfo1.setIsSee("1");
        messageInfoDao.insert(messageInfo1);
        if ((tbOrder.getStatus() == 6 && parse.getTime() > cal.getTime().getTime()) || (tbOrder.getStatus() == 7)) {
            UserEntity userEntity = userDao.selectById(tbOrder.getUserId());
            //已支付判断支付方式

            if (tbOrder.getPayType() == 2) {
                //余额支付，直接退还钱包
                userMoneyDao.updateMayMoney(1, tbOrder.getUserId(), tbOrder.getPayMoney().doubleValue());
            } else if (tbOrder.getPayType() == 1) {
                PayDetails payDetails = payDetailsDao.selectByOrderId(tbOrder.getOrderNumber());
                boolean b = wxErrService.wxRefund(payDetails);
                if (!b) {
                    return Result.error("退款失败，请联系客服！");
                }
            } else {
                PayDetails payDetails = payDetailsDao.selectByOrderId(tbOrder.getOrderNumber());
                String code = AliPayController.alipayRefund(payDetails);
                if (StringUtils.isNotBlank(code)) {
                    log.error(code);
                    JSONObject jsonObject = JSON.parseObject(code);
                    JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                    String code1 = alipay_trade_refund_response.getString("code");
                    if (!"10000".equals(code1)) {
                        return Result.error("退款失败！" + alipay_trade_refund_response.getString("sub_msg"));
                    }
                } else {
                    return Result.error("退款失败！");
                }
            }
            tbOrder.setStatus(5);
            appOrderDao.updateById(tbOrder);
            //添加退款记录
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setUserId(tbOrder.getUserId());
            userMoneyDetails.setTitle("退款");
            userMoneyDetails.setType(1);
            userMoneyDetails.setClassify(3);
            userMoneyDetails.setState(2);
            userMoneyDetails.setMoney(tbOrder.getPayMoney());
            userMoneyDetails.setContent("退款到账：" + tbOrder.getPayMoney() + "元，退款按原路返回");
            userMoneyDetails.setCreateTime(format);
            userMoneyDetailsDao.insert(userMoneyDetails);
            //判断是否使用优惠券
            if (tbOrder.getCouponId() != null) {
                TbCouponUser tbCouponUser = tbCouponUserDao.selectById(tbOrder.getCouponId());
                tbCouponUser.setStatus(0);
                tbCouponUserDao.updateById(tbCouponUser);
            }
            //设置小程序消息推送
            CommonInfo one = commonInfoService.findOne(266);
            List<String> msgList = new ArrayList<>();
            msgList.add(tbOrder.getOrderNumber());
            msgList.add("用户取消订单");
            msgList.add(tbOrder.getPayMoney().toString());
            msgList.add(format);
            SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 3);
            userService.pushToSingle("取消订单", "您已取消订单！", userEntity.getClientid());

            CommonInfo shopTemplate = commonInfoService.findOne(353);
            //商家通知
            List<String> msgShopList = new ArrayList<>();
            msgShopList.add(tbOrder.getOrderNumber());
            msgShopList.add(tbOrder.getPayMoney().toString());
            msgShopList.add("订单已取消，请前往查看>");

            Long shopId = tbOrder.getShopId();
            GoodsShop goodsShop = goodsShopDao.selectById(shopId);

            UserEntity shopUser = userService.selectUserById(goodsShop.getUserId());
            if (StringUtils.isNotEmpty(shopUser.getShopOpenId())) {
                SenInfoCheckUtil.sendShopMsg(shopUser.getShopOpenId(), shopTemplate.getValue(), msgShopList, 8);
            }
            if (StringUtils.isNotEmpty(shopUser.getShopClientId())) {
                userService.pushToSingleShop("取消订单", "订单已取消，请前往查看", shopUser.getShopClientId());
            }

            List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>().eq("order_id", tbOrder.getOrderId()));
            for (int a = 0; a < orderGoodsList.size(); a++) {
                OrderGoods orderGoods = orderGoodsList.get(a);
                Integer goodsNum = orderGoods.getGoodsNum();
                Long goodsId = orderGoodsList.get(a).getGoodsId();
                GoodsShopRelevancy goodsShopRelevancy = goodsShopRelevancyDao.selectOne(new QueryWrapper<GoodsShopRelevancy>()
                        .eq("shop_id", tbOrder.getShopId()).eq("goods_id", goodsId));
                GoodsShopRelevancy goodsShopRelevancy1 = new GoodsShopRelevancy();
                goodsShopRelevancy1.setId(goodsShopRelevancy.getId());
                goodsShopRelevancy1.setSales(goodsShopRelevancy.getSales() - goodsNum);//加销量
                goodsShopRelevancy1.setInventory(goodsShopRelevancy.getInventory() + goodsNum);//减库存
                goodsShopRelevancyDao.updateById(goodsShopRelevancy1);
                goodsShopDao.updateShopSales(2, goodsNum, goodsShopRelevancy.getShopId());
            }

            return Result.success("取消订单成功！");
        }
        return Result.error("餐品正在制作中，无法退款！");
    }

    @Override
    public Result shopReplyEvaluate(String orderNumber, String shopReplyMessage) {
        Evaluate evaluate = new Evaluate();
        evaluate.setShopReplyMessage(shopReplyMessage);
        evaluateDao.update(evaluate, new QueryWrapper<Evaluate>().eq("order_number", orderNumber));
        return Result.success();
    }


    @Transactional
    @Override
    public Result deleteOrderList(List<Integer> orderId) {
        for (int i = 0; i < orderId.size(); i++) {
            baseMapper.deleteById(orderId.get(i));
        }
        return Result.success();
    }

    @Override
    public Result selectBuyGoods(Long userId, Long orderId) {
        //   TbOrder tbOrder = appOrderDao.selectOne(new QueryWrapper<TbOrder>().eq("order_id", orderId).eq("user_id", userId));
        TbOrder tbOrder = appOrderDao.selectBuyGoods(orderId, userId);
        List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>().eq("order_id", tbOrder.getOrderId()));
        tbOrder.setOrderGoodsList(orderGoodsList);
        return Result.success().put("data", tbOrder);
    }

    @Override
    public Result adminCancelOrder(Long orderId){
        reentrantReadWriteLock.writeLock().lock();
        try {
            return adminCancelOrders(orderId);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请稍后再试！");
    }


    @Transactional
    public Result adminCancelOrders(Long orderId) {
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        TbOrder tbOrder = appOrderDao.selectById(orderId);
        if(tbOrder.getStatus()==5){
            return Result.success();
        }
        if (tbOrder.getIsPay() == 0) {
            //未支付直接取消
            TbOrder tbOrder1 = new TbOrder();
            tbOrder1.setOrderId(orderId);
            tbOrder1.setStatus(5);
            appOrderDao.updateById(tbOrder1);
        } else {
            UserEntity userEntity = userDao.selectById(tbOrder.getUserId());
            //已支付判断支付方式
            if (tbOrder.getPayType() == 2) {
                //余额支付，直接退还钱包
                userMoneyDao.updateMayMoney(1, tbOrder.getUserId(), tbOrder.getPayMoney().doubleValue());
            } else if (tbOrder.getPayType() == 1) {
                PayDetails payDetails = payDetailsDao.selectByOrderId(tbOrder.getOrderNumber());
                boolean b = wxErrService.wxRefund(payDetails);
                if (!b) {
                    return Result.error("退款失败，请联系客服！");
                }
            } else {
                PayDetails payDetails = payDetailsDao.selectByOrderId(tbOrder.getOrderNumber());
                String code = AliPayController.alipayRefund(payDetails);
                if (StringUtils.isNotBlank(code)) {
                    log.error(code);
                    JSONObject jsonObject = JSON.parseObject(code);
                    JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                    String code1 = alipay_trade_refund_response.getString("code");
                    if (!"10000".equals(code1)) {
                        return Result.error("退款失败！" + alipay_trade_refund_response.getString("sub_msg"));
                    }
                } else {
                    return Result.error("退款失败！");
                }
            }
            tbOrder.setStatus(5);
            appOrderDao.updateById(tbOrder);
            //取消跑腿订单
            TbIndent tbIndent = new TbIndent();
            TbIndent tbIndent1 = tbIndentDao.selectOne(new QueryWrapper<TbIndent>().eq("order_id", orderId));
            tbIndent.setIndentId(tbIndent1.getIndentId());
            tbIndent.setIndentState("10");
            tbIndentDao.updateById(tbIndent);
            //添加退款记录
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setUserId(tbOrder.getUserId());
            userMoneyDetails.setTitle("退款");
            userMoneyDetails.setType(1);
            userMoneyDetails.setState(2);
            userMoneyDetails.setClassify(3);
            userMoneyDetails.setMoney(tbOrder.getPayMoney());
            userMoneyDetails.setContent("退款到账：" + tbOrder.getPayMoney() + "元，退款按原路返回");
            userMoneyDetails.setCreateTime(format);
            userMoneyDetailsDao.insert(userMoneyDetails);
            //判断是否使用优惠券
            if (tbOrder.getCouponId() != null) {
                TbCouponUser tbCouponUser = tbCouponUserDao.selectById(tbOrder.getCouponId());
                tbCouponUser.setStatus(0);
                tbCouponUserDao.updateById(tbCouponUser);
            }
            //设置小程序消息推送
            CommonInfo one = commonInfoService.findOne(266);
            List<String> msgList = new ArrayList<>();
            msgList.add(tbOrder.getOrderNumber());
            msgList.add("门店主动取消订单");
            msgList.add(tbOrder.getPayMoney().toString());
            msgList.add(format);
            SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), one.getValue(), msgList, 3);
            userService.pushToSingle("下单失败", "亲爱的用户您好，商铺已取消您的订单，给您带来不便请谅解，如有疑问可联系客服！", userEntity.getClientid());

            CommonInfo shopTemplate = commonInfoService.findOne(353);
            //商家通知
            List<String> msgShopList = new ArrayList<>();
            msgShopList.add(tbOrder.getOrderNumber());
            msgShopList.add(tbOrder.getPayMoney().toString());
            msgShopList.add("订单已取消，请前往查看>");

            Long shopId = tbOrder.getShopId();
            GoodsShop goodsShop = goodsShopDao.selectById(shopId);

            UserEntity shopUser = userService.selectUserById(goodsShop.getUserId());
            if (StringUtils.isNotEmpty(shopUser.getShopOpenId())) {
                SenInfoCheckUtil.sendShopMsg(shopUser.getShopOpenId(), shopTemplate.getValue(), msgShopList, 8);
            }
            if (StringUtils.isNotEmpty(shopUser.getShopClientId())) {
                userService.pushToSingleShop("取消订单", "订单已取消，请前往查看", shopUser.getShopClientId());
            }

            List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>().eq("order_id", orderId));
            for (int a = 0; a < orderGoodsList.size(); a++) {
                Integer goodsNum = orderGoodsList.get(a).getGoodsNum();
                Long goodsId = orderGoodsList.get(a).getGoodsId();
                GoodsShopRelevancy goodsShopRelevancy = goodsShopRelevancyDao.selectOne(new QueryWrapper<GoodsShopRelevancy>()
                        .eq("shop_id", tbOrder.getShopId()).eq("goods_id", goodsId));
                GoodsShopRelevancy goodsShopRelevancy1 = new GoodsShopRelevancy();
                goodsShopRelevancy1.setId(goodsShopRelevancy.getId());
                goodsShopRelevancy1.setSales(goodsShopRelevancy.getSales() - goodsNum);//加销量
                goodsShopRelevancy1.setInventory(goodsShopRelevancy.getInventory() + goodsNum);//减库存
                goodsShopRelevancyDao.updateById(goodsShopRelevancy1);
                goodsShopDao.updateShopSales(2, goodsNum, goodsShopRelevancy.getShopId());
            }
        }
        return Result.success();
    }


    @Override
    public Result selectOrderList(Long userId, Long shopId, Integer status, Integer orderType, Integer page, Integer limit) {
        HashMap hashMap = new HashMap();
        Page<TbOrder> pages = new Page(page, limit);
        IPage<TbOrder> tbOrderList = baseMapper.selectOrderList(pages, userId, status, orderType, shopId);
        BigDecimal money = new BigDecimal(0);
        ArrayList list = new ArrayList();
        for (int i = 0; i < tbOrderList.getRecords().size(); i++) {
            List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>()
                    .eq("order_id", tbOrderList.getRecords().get(i).getOrderId()));
            for (int a = 0; a < orderGoodsList.size(); a++) {
                BigDecimal goodsPrice = orderGoodsList.get(a).getGoodsPrice();
                Integer goodsNum = orderGoodsList.get(a).getGoodsNum();
                BigDecimal multiply = goodsPrice.multiply(new BigDecimal(goodsNum));
                money = money.add(multiply);
            }
            list.add(orderGoodsList);
            tbOrderList.getRecords().get(i).setOrderGoodsList(list);
        }
        if (shopId != null && userId != null) {
            reentrantReadWriteLock.writeLock().lock();
            try {
                UserBrowse userBrowse = userBrowseDao.selectOne(new QueryWrapper<UserBrowse>().eq("user_id", userId).eq("by_browse_id", shopId));
                String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                if (userBrowse != null) {
                    userBrowse.setUpdateTime(format);
                } else {
                    userBrowse = new UserBrowse();
                    userBrowse.setUserId(userId);
                    userBrowse.setByBrowseId(shopId);
                    userBrowse.setUpdateTime(format);
                    userBrowseDao.insert(userBrowse);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                reentrantReadWriteLock.writeLock().unlock();
            }
        }
        PageUtils pageUtils = new PageUtils(tbOrderList);
        hashMap.put("pageUtils", pageUtils);
        hashMap.put("money", money);
        return Result.success().put("data", hashMap);
    }

    public String getGeneralOrder() {
        Date date = new Date();
        String newString = String.format("%0" + 4 + "d", (int) ((Math.random() * 9 + 1) * 1000));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String format = sdf.format(date);
        return format + newString;
    }


    @Scheduled(cron = "0 */1 * * * ?")
    public void makeOrders(){
        //自动制作完成订单
        String value = commonInfoService.findOne(418).getValue();
        if("是".equals(value)){
            String minute = commonInfoService.findOne(419).getValue();
            List<TbOrder> tbOrders = baseMapper.selectMakeOrdersList(minute);
            for (TbOrder order:tbOrders){
                try{
                    order.setStatus(3);
                    updateOrder(order);
                }catch (Exception e){
                    e.printStackTrace();
                    log.error("自动完成异常："+e.getMessage(),e);
                }
            }
        }
    }



}
