Helius
2022-05-24 560228ac3c15cccce0b2a5994d44e4e81b5b3b73
zq-erp/src/main/java/com/matrix/system/hive/service/imp/SysOrderServiceImpl.java
@@ -1,16 +1,17 @@
package com.matrix.system.hive.service.imp;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.matrix.component.asyncmessage.AsyncMessageManager;
import com.matrix.core.constance.MatrixConstance;
import com.matrix.core.exception.GlobleException;
import com.matrix.core.pojo.PaginationVO;
import com.matrix.core.tools.DateUtil;
import com.matrix.core.tools.LogUtil;
import com.matrix.core.tools.StringUtils;
import com.matrix.core.tools.WebUtil;
import com.matrix.system.app.dto.OrderListDto;
import com.matrix.system.app.mapper.SysProjUseMapper;
import com.matrix.system.app.vo.OrderDetailAchieveItemVo;
import com.matrix.system.app.vo.OrderDetailItemVo;
import com.matrix.system.app.vo.OrderDetailVo;
@@ -22,28 +23,27 @@
import com.matrix.system.common.dao.SysUsersDao;
import com.matrix.system.common.service.OperationLogService;
import com.matrix.system.constance.Dictionary;
import com.matrix.system.enums.BooleanEnum;
import com.matrix.system.enums.OperationButtonEnum;
import com.matrix.system.enums.OperationFunctionEnum;
import com.matrix.system.hive.bean.*;
import com.matrix.system.hive.dao.*;
import com.matrix.system.hive.dto.GoodsSealLimitDto;
import com.matrix.system.hive.dto.MoneyCardOperationDto;
import com.matrix.system.hive.dto.ProjUseOperationDto;
import com.matrix.system.hive.dto.SysOrderItemDto;
import com.matrix.system.hive.plugin.util.CollectionUtils;
import com.matrix.system.hive.plugin.util.MoneyUtil;
import com.matrix.system.hive.pojo.CzXkVo;
import com.matrix.system.hive.pojo.ShoppingCarItem;
import com.matrix.system.hive.pojo.ShoppingCarItemsVo;
import com.matrix.system.hive.service.*;
import com.matrix.system.score.constant.ScoreSettingConstant;
import com.matrix.system.score.entity.ScoreVipDetail;
import com.matrix.system.padApi.dto.PadOrderListDto;
import com.matrix.system.padApi.vo.PadOrderDetailVo;
import com.matrix.system.score.service.ScoreVipDetailService;
import com.matrix.system.shopXcx.mqTask.AsyncMessageRouting;
import com.matrix.system.wechart.templateMsg.UniformMsgParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotEmpty;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
@@ -58,15 +58,12 @@
    @Autowired
    private SysOrderItemDao orderItemDao;
    @Autowired
    private SysProjUseDao sysProjUseDao;
    @Autowired
    private SysStoreInfoDao storeInfoDao;
    @Autowired
    private CodeService codeService;
    private SysProjUseService sysProjUseService;
    @Autowired
    SysVipInfoDao sysVipInfoDao;
    @Autowired
    SysOutStoreDao sysOutStoreDao;
    SysOutStoreService sysOutStoreService;
    @Autowired
    SysOutStoreItemDao sysOutStoreItemDao;
    @Autowired
@@ -102,26 +99,12 @@
    @Autowired
    private AchieveNewDao achieveNewDao;
    @Autowired
    private WarehouseDao warehouseDao;
    @Autowired
    private ShoppingGoodsService shoppingGoodsService;
    @Autowired
    private SysOrderFlowDao sysOrderFlowDao;
    @Autowired
    private SysSupplierInfoDao sysSupplierInfoDao;
    @Autowired
    private SysInstoreInfoDao sysInstoreInfoDao;
    @Autowired
    private SysInstoreDetailDao sysInstoreDetailDao;
    @Autowired
    private SysInstoreInfoService sysInstoreInfoService;
    @Autowired
    BusParameterSettingsDao parameterSettingsDao;
@@ -131,6 +114,559 @@
    @Autowired
    private OperationLogService operationLogService;
    @Autowired
    private SysVipInfoService sysVipInfoService;
    @Autowired
    private SysOrderServiceHelper sysOrderServiceHelper;
    @Autowired
    MoneyCardUseService moneyCardUseService;
    //↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓业务代码区↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysOrder checkAndSaveOrder(SysOrder sysOrder) {
        if (Objects.isNull(sysOrder.getId())) {
            LogUtil.info("新增正向订单");
            return sysOrderServiceHelper.saveOrder(sysOrder);
        } else {
            LogUtil.info("修改订单");
            return sysOrderServiceHelper.modifyOrder(sysOrder);
        }
    }
    /**
     * 取消订单
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelOrder(Long id) {
        SysOrder order = sysOrderDao.selectById(id);
        if (order.getStatu().equals(Dictionary.ORDER_STATU_DFK)) {
            //待付款订单取消
            cancelDFKOrder(order);
        } else {
            //已付款订单取消
            cancelYFKOrder(order);
        }
    }
    /**
     * 已付款订单取消
     *
     * @param order
     */
    private void cancelYFKOrder(SysOrder order) {
        SysUsers sysUsers = WebUtil.getSessionAttribute(MatrixConstance.LOGIN_KEY);
        //一个订单只能被取消一次
        if (Dictionary.ORDER_STATU_YQX.equals(order.getStatu())) {
            throw new GlobleException("订单已取消");
        }
        //储值卡退款
        sysOrderServiceHelper.returnMoneyCardPay(order);
        //套餐项目取消
        List<SysOrderItem> sysOrderItems = orderItemDao.selectByOrderId(order.getId());
        for (SysOrderItem orderItem : sysOrderItems) {
            // 充值卡类型退款
            if (Dictionary.SHOPPING_GOODS_TYPE_CZK.equals(orderItem.getType())) {
                //删除购买的充值卡
                moneyCardUseService.deleteByOrderItemId(orderItem.getId());
            } else if (Dictionary.SHOPPING_GOODS_TYPE_XM.equals(orderItem.getType())
                    || Dictionary.SHOPPING_GOODS_TYPE_TC.equals(orderItem.getType())) {
                // 项目套餐退款
                // 删除套餐项目使用情况
                sysProjUseService.deleteByOrderItemId(orderItem.getId());
            }
        }
        //删除出库单,恢复库存
        SysOutStore sysOutStore = new SysOutStore();
        sysOutStore.setOrderId(order.getId());
        List<SysOutStore> sysOutStores = sysOutStoreService.findByModel(sysOutStore);
        if (sysOutStores.size() == 1) {
            sysOutStore = sysOutStores.get(0);
            sysOutStoreService.cancelOutStore(sysOutStore.getId());
        }
        // 删除业绩
        achieveNewService.removeByOrderId(order.getId());
        // 删除收款记录
        sysOrderFlowDao.deleteByOrderId(order.getId());
        //删除积分
        scoreVipDetailService.removeByBusinessId(order.getVipId(), order.getId());
        // 取消订单
        order.setStatu(Dictionary.ORDER_STATU_YQX);
        sysOrderDao.update(order);
        //保存单据日志
        operationLogService.saveOperation(order.getCompanyId(), order.getShopId(), sysUsers.getSuId(),
                OperationFunctionEnum.ORDER,
                OperationButtonEnum.CANCEL,
                order.getId(),
                order.getOrderNo(),
                order.getVipId(),
                "已付款取消订单");
    }
    /**
     * 待付款订单取消
     *
     * @param order
     */
    private void cancelDFKOrder(SysOrder order) {
        SysUsers sysUsers = WebUtil.getSessionAttribute(MatrixConstance.LOGIN_KEY);
        order.setStatu(Dictionary.ORDER_STATU_YQX);
        order.setArrears(0D);
        //发送微信公众号提醒
        UniformMsgParam uniformMsgParam = new UniformMsgParam(order.getCompanyId(), UniformMsgParam.GZH_DDQX);
        uniformMsgParam.put("orderId", order.getId());
        asyncMessageManager.sendMsg(AsyncMessageRouting.SEND_UNIFORM_TEMPLATE_MSG, uniformMsgParam);
        sysOrderDao.update(order);
        //保存单据日志
        operationLogService.saveOperation(order.getCompanyId(), order.getShopId(), sysUsers.getSuId(),
                OperationFunctionEnum.ORDER,
                OperationButtonEnum.CANCEL,
                order.getId(),
                order.getOrderNo(),
                order.getVipId(),
                "未付款取消订单");
    }
    /**
     * jyy 收款
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void payOrder(SysOrder pageOrder) throws GlobleException {
        //校验订单是否满足收款条件
        checkOrderAblePay(pageOrder);
        // 更新订单主表信息
        payEndUpdateOrderInfo(pageOrder);
        //添加支付流水
        sysOrderServiceHelper.addOrderFlow(pageOrder, false);
        //扣除储值卡余额
        sysOrderServiceHelper.cardPaySk(pageOrder);
        // 设置会员充值卡使用情况
        sysOrderServiceHelper.addMoneyCardUse(pageOrder);
        // 改变客户项目套餐使用情况
        sysOrderServiceHelper.addTaocanProj(pageOrder);
        // 新增出库单
        sysOrderServiceHelper.addOutStore(pageOrder);
        // 设置业绩
        achieveNewService.addAchaeveByOrder(pageOrder);
        //设置会员积分
        sysOrderServiceHelper.addVipScore(pageOrder);
        //保存订单收款日志
        saveOrderSkLog(pageOrder);
    }
    /**
     * 保存订单收款日志
     *
     * @param pageOrder
     */
    private void saveOrderSkLog(SysOrder pageOrder) {
        SysUsers user = WebUtil.getSessionAttribute(MatrixConstance.LOGIN_KEY);
        operationLogService.saveOperation(pageOrder.getCompanyId(), pageOrder.getShopId(), user.getSuId(),
                OperationFunctionEnum.ORDER,
                OperationButtonEnum.ORDER_SK,
                pageOrder.getId(),
                pageOrder.getOrderNo(),
                pageOrder.getVipId());
    }
    /**
     * 付款后更新订单信息
     *
     * @param pageOrder
     */
    private void payEndUpdateOrderInfo(SysOrder pageOrder) {
        LogUtil.info("付款更新订单信息 id={}", pageOrder.getId());
        SysUsers user = (SysUsers) WebUtil.getSession().getAttribute(MatrixConstance.LOGIN_KEY);
        pageOrder.setCashierId(user.getSuId());
        pageOrder.setPayTime(new Date());
        pageOrder.setStatu(Dictionary.ORDER_STATU_YFK);
        List<SysOrderFlow> flows = pageOrder.getFlows();
        BigDecimal cashPayAmount = flows.stream()
                .filter(item -> (!item.getPayMethod().equals("储值卡")) && (!item.getPayMethod().equals("欠款")))
                .map(SysOrderFlow::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal cardPayAmount = flows.stream()
                .filter(item -> item.getPayMethod().equals("储值卡"))
                .map(SysOrderFlow::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        pageOrder.setCardPay(cardPayAmount.doubleValue());
        pageOrder.setCashPay(cashPayAmount.doubleValue());
        for (SysOrderFlow flow : pageOrder.getFlows()) {
            //欠款处理
            if (SysOrderFlow.PAY_METHOD_ARREARS.equals(flow.getPayMethod())) {
                pageOrder.setStatu(Dictionary.ORDER_STATU_QK);
                pageOrder.setArrears(flow.getAmount().doubleValue());
            }
        }
        double sum = flows.stream().mapToDouble(item -> item.getAmount().doubleValue()).sum();
        if (sum > 0 && cardPayAmount.doubleValue() == 0 && cashPayAmount.doubleValue() == 0) {
            throw new GlobleException("订单更新失败,支付金额计算错误,请联系管理员");
        }
        sysOrderDao.update(pageOrder);
        // 设置用户为成交客户
        sysVipInfoService.updateDealStatus(pageOrder.getVipId(), BooleanEnum.TRUE.getValue());
    }
    /**
     * 检查订单是否满足支付条件
     *
     * @param pageOrder
     */
    private void checkOrderAblePay(SysOrder pageOrder) {
        SysOrder checkOrder = sysOrderDao.selectById(pageOrder.getId());
        //状态校验
        if (!Dictionary.ORDER_STATU_DFK.equals(checkOrder.getStatu())) {
            throw new GlobleException("该订单已经收过款,请刷新页面再试!");
        }
        //检查交易限制调整
        GoodsSealLimitDto goodsSealLimitDto = new GoodsSealLimitDto();
        goodsSealLimitDto.setVipId(pageOrder.getVipId());
        goodsSealLimitDto.setSysOrderItemDtoList(Lists.newArrayList());
        pageOrder.getItems().forEach(e -> {
            goodsSealLimitDto.getSysOrderItemDtoList().add(BeanUtil.copyProperties(e, SysOrderItemDto.class));
        });
        shoppingGoodsService.checkGoodsSealLimit(goodsSealLimitDto);
        //检查业绩设置
        checkOrderAchieve(pageOrder);
        LogUtil.info("订单满足支付条件 id={}", pageOrder.getId());
    }
    /**
     * 检查业绩设置是否合理
     * 1、每个订单明细都要有至少一个对应的业绩
     * 2、每个订单明细的同类型业绩金额之和不能大于明细支付金额
     *
     * @param pageOrder
     */
    private void checkOrderAchieve(SysOrder pageOrder) {
        pageOrder.getItems().forEach(item -> {
            if (CollectionUtil.isEmpty(item.getAchieveList())) {
                ShoppingGoods shopGoods = shoppingGoodsDao.selectById(item.getGoodsId());
                throw GlobleException.instance(shopGoods.getName() + "缺少设置业绩");
            }
            //按业绩类型分组后比较支付金额与业绩金额是否相等
            Map<String, List<AchieveNew>> achieveTypeMap = item.getAchieveList().stream().collect(Collectors.groupingBy(AchieveNew::getAchieveType));
            Set<Map.Entry<String, List<AchieveNew>>> entries = achieveTypeMap.entrySet();
            entries.forEach(entrie -> {
                double sum = entrie.getValue().stream().mapToDouble(AchieveNew::getGoodsCash).sum();
                //todo 目前使用js计算金额可能存在精度的误差展示用0.1屏蔽
                if (Math.abs(sum - (item.getZkPrice() * item.getCount())) > 0.1) {
                    ShoppingGoods shopGoods = shoppingGoodsDao.selectById(item.getGoodsId());
                    throw GlobleException.instance(shopGoods.getName() + "," + entrie.getKey() + "业绩金额与收款金额不一致");
                }
            });
        });
    }
    /**
     * 补交
     *
     * @author:姜友瑶
     * @date 2016年9月19日
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateAfterMoney(SysOrder pageOrder) {
        SysOrder sourceOrder = sysOrderDao.selectById(pageOrder.getId());
        //添加支付流水
        sysOrderServiceHelper.addOrderFlow(pageOrder, true);
        //扣除储值卡余额
        sysOrderServiceHelper.cardPaySk(pageOrder);
        double refundTotal = 0D;
        double cardPayTotal = 0D;
        double cashPayTotal = 0D;
        for (SysOrderFlow flow : pageOrder.getFlows()) {
            // 若使用储值卡付款
            if (SysOrderFlow.PAY_METHOD_CARD.equals(flow.getPayMethod())) {
                cardPayTotal += flow.getAmount().doubleValue();
            } else {
                cashPayTotal += flow.getAmount().doubleValue();
            }
            refundTotal += flow.getAmount().doubleValue();
        }
        if (refundTotal == pageOrder.getArrears()) {
            sourceOrder.setStatu(Dictionary.ORDER_STATU_YFK);
        } else {
            sourceOrder.setStatu(Dictionary.ORDER_STATU_QK);
        }
        sourceOrder.setArrears(sourceOrder.getArrears() - refundTotal);
        sourceOrder.setCardPay(sourceOrder.getCardPay() == null ? 0 : sourceOrder.getCardPay() + cardPayTotal);
        sourceOrder.setCashPay(sourceOrder.getCashPay() == null ? 0 : sourceOrder.getCashPay() + cashPayTotal);
        sysOrderDao.update(sourceOrder);
    }
    /**
     * 会员卡充值
     *
     * @param czVo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysOrder moneyCardCz(CzXkVo czVo) {
        // 新增一个充值订单
        SysOrder order = sysOrderServiceHelper.createCzOrder(czVo);
        //新增会员卡金额
        MoneyCardUse cardUser = moneyCardUseDao.selectVipCard(czVo.getVipId());
        MoneyCardOperationDto moneyCardOperationDto = new MoneyCardOperationDto();
        moneyCardOperationDto.setRealMoney(czVo.getBjmoney());
        moneyCardOperationDto.setGiftMoney(czVo.getGiftMoney());
        moneyCardOperationDto.setCarUseId(cardUser.getId());
        moneyCardOperationDto.setOrderId(order.getId());
        moneyCardOperationDto.setOrderNo(order.getOrderNo());
        moneyCardOperationDto.setType(MoneyCardUseFlow.USE_TYPE_CZ);
        SysUsers user = WebUtil.getSessionAttribute(MatrixConstance.LOGIN_KEY);
        moneyCardOperationDto.setUpdateUser(user.getSuId());
        moneyCardUseService.changeMoneyCard(Arrays.asList(moneyCardOperationDto));
        // 更新订单主表信息
        payEndUpdateOrderInfo(order);
        //添加支付流水
        sysOrderServiceHelper.addOrderFlow(order, false);
        // 设置业绩
        achieveNewService.addAchaeveByOrder(order);
        //设置会员积分
        sysOrderServiceHelper.addVipScore(order);
        return order;
    }
    @Override
    public SysOrder findSysOrderTjByVipId(Long vipId) {
        return sysOrderDao.selectVipOrderInfoTotal(vipId);
    }
    @Override
    public List<OrderDetailVo> findApiOrderListInPage(OrderListDto orderListDto, PaginationVO pageVo) {
        return sysOrderDao.selectApiOrderListInPage(orderListDto, pageVo);
    }
    @Override
    public List<PadOrderDetailVo> findPadApiOrderListInPage(PadOrderListDto orderListDto, PaginationVO pageVo) {
        List<PadOrderDetailVo> padOrderDetailVos = sysOrderDao.selectPadApiOrderListInPage(orderListDto, pageVo);
        if(CollUtil.isNotEmpty(padOrderDetailVos)){
            for(PadOrderDetailVo padOrderDetailVo : padOrderDetailVos){
                padOrderDetailVo.setItems(orderItemDao.selectApiOrderDetailItemsByOrderId(Long.parseLong(padOrderDetailVo.getOrderId())));
            }
        }
        return padOrderDetailVos;
    }
    @Override
    public int findApiOrderListTotal(OrderListDto orderListDto) {
        return sysOrderDao.selectApiOrderListTotal(orderListDto);
    }
    @Override
    public int findPadApiOrderListTotal(PadOrderListDto orderListDto) {
        return sysOrderDao.selectPadApiOrderListTotal(orderListDto);
    }
    @Override
    public OrderDetailVo findApiOrderDetailByOrderId(Long orderId) {
        OrderDetailVo orderDetail = sysOrderDao.selectApiOrderDetailById(orderId);
        if (orderDetail == null) {
            throw new GlobleException("该订单不存在");
        }
        List<OrderDetailItemVo> items = orderItemDao.selectApiOrderDetailItemsByOrderId(orderId);
        if (CollectionUtils.isNotEmpty(items)) {
            for (OrderDetailItemVo item : items) {
                List<OrderDetailAchieveItemVo> achieveItems = achieveNewDao.selectApiOrderItemAchieve(item.getId());
                item.setAchieves(achieveItems);
            }
        }
        orderDetail.setItems(items);
        return orderDetail;
    }
    @Override
    public List<RankingVo> findApiShopAchieveRanking(SysOrder sysOrder) {
        return sysOrderDao.selectShopAchieveRanking(sysOrder);
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void orderTk(SysOrder sysOrder) {
        //创建并保存退款订单
        sysOrder = sysOrderServiceHelper.createTkOrder(sysOrder);
        // 添加订单收款流水
        sysOrderServiceHelper.addOrderFlow(sysOrder, false);
        //退款退套餐退项目
        refundProjUse(sysOrder);
        //删除积分
        SysOrder oldOrder = sysOrderDao.selectById(sysOrder.getOldOrderId());
        scoreVipDetailService.removeByBusinessId(oldOrder.getVipId(), oldOrder.getId());
        // 设置业绩
        achieveNewService.addAchaeveByOrder(sysOrder);
        SysUsers user = WebUtil.getSessionAttribute(MatrixConstance.LOGIN_KEY);
        //保存单据日志
        operationLogService.saveOperation(sysOrder.getCompanyId(), sysOrder.getShopId(), user.getSuId(),
                OperationFunctionEnum.ORDER,
                OperationButtonEnum.ORDER_TK,
                sysOrder.getId(),
                sysOrder.getOrderNo(),
                sysOrder.getVipId());
    }
    /**
     * 退款退项目,套餐,卡项
     *
     * @param sysOrder
     */
    private void refundProjUse(SysOrder sysOrder) {
        SysUsers user = WebUtil.getSessionAttribute(MatrixConstance.LOGIN_KEY);
        //记录需要退库存的产品
        List<SysOrderItem> returnGoodsList = new ArrayList<>();
        //需要退的套餐和项目
        List<ProjUseOperationDto> projUseDtoList = Lists.newArrayList();
        //需要退的储值卡
        List<MoneyCardOperationDto> moneyCardOperationDtos = Lists.newArrayList();
        for (SysOrderItem item : sysOrder.getItems()) {
            if (Dictionary.SHOPPING_GOODS_TYPE_JJCP.equals(item.getType()) && Dictionary.FLAG_YES_Y.equals(item.getIsReturnStore())) {
                returnGoodsList.add(item);
            } else if (Dictionary.SHOPPING_GOODS_TYPE_TC.equals(item.getType())
                    || Dictionary.SHOPPING_GOODS_TYPE_XM.equals(item.getType())) {
                ProjUseOperationDto dto = new ProjUseOperationDto();
                dto.setGoodsId(item.getGoodsId());
                dto.setCount(item.getRefundCount());
                dto.setOrderItemId(item.getOldItemId());
                dto.setUpdateUserId(user.getSuId());
                projUseDtoList.add(dto);
            }else if (Dictionary.SHOPPING_GOODS_TYPE_CZK.equals(item.getType())) {
                MoneyCardOperationDto moneyCardOperationDto = new MoneyCardOperationDto();
                moneyCardOperationDto.setOrderId(sysOrder.getId());
                moneyCardOperationDto.setOrderNo(sysOrder.getOrderNo());
                moneyCardOperationDto.setOrderItemId(item.getOldItemId());
                moneyCardOperationDto.setType(MoneyCardUseFlow.USE_TYPE_ORDRE_TK);
                moneyCardOperationDto.setUpdateUser(user.getSuId());
                moneyCardOperationDto.setOrderNo(sysOrder.getOrderNo());
                moneyCardOperationDto.setRealMoney(item.getZkPrice());
                moneyCardOperationDtos.add(moneyCardOperationDto);
            }
        }
        BusParameterSettings manageStockSetting = busParameterSettingsDao.selectCompanyParamByCode(AppConstance.WAREHOUSE_MANAGE_STOCK, sysOrder.getCompanyId());
//        if (AppConstance.IS_Y.equals(manageStockSetting.getParamValue())) {
        if (BooleanEnum.TRUE.getValue() == manageStockSetting.getIntParamValue()) {
            // 家居产品退库存
            if (CollectionUtils.isNotEmpty(returnGoodsList)) {
                LogUtil.info("订单退款:退产品库存:{}", JSON.toJSONString(returnGoodsList));
                sysOrderServiceHelper.refundInstore(returnGoodsList);
            }
        }
        if(CollUtil.isNotEmpty(projUseDtoList)){
            LogUtil.info("订单退款:退套餐项目:{}", JSON.toJSONString(projUseDtoList));
            sysProjUseService.projectTk(projUseDtoList);
        }
        if(CollUtil.isNotEmpty(moneyCardOperationDtos)){
            LogUtil.info("订单退款:储值卡:{}", JSON.toJSONString(moneyCardOperationDtos));
            moneyCardUseService.moneyCardTk(moneyCardOperationDtos);
        }
    }
    @Override
    public BigDecimal findVipArrearsByVipId(Long vipId) {
        return sysOrderDao.selectArrearsByVipId(vipId);
    }
    //↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓===增删改查代码区↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
    @Override
@@ -186,1748 +722,5 @@
    public SysOrder findById(Long id) {
        return sysOrderDao.selectById(id);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysOrder checkAndSaveOrder(SysOrder sysOrder) {
        // 计算订单折扣金额,收款情况下 计算订单总额
        double zkTotal = 0.0;
        // 判断是否为退款
        String orderStatus = Dictionary.ORDER_STATU_DFK;
        if (Dictionary.ORDER_STATU_TK.equals(sysOrder.getStatu())) {
            orderStatus = Dictionary.ORDER_STATU_TK;
        }
        // 页面的pageOrder 参数只包含支付金额信息,不带有购买商品
        for (SysOrderItem item : sysOrder.getItems()) {
            // 若为退款,则先更新原有数量
            if (orderStatus.equals(Dictionary.ORDER_STATU_TK)) {
                SysOrderItem sysOrderItem = new SysOrderItem();
                sysOrderItem.setId(item.getId());
                sysOrderItem.setCount(item.getPreCount() - item.getCount());
                orderItemDao.update(sysOrderItem);
            }
            item.setId(null);
            ShoppingGoods shoppingGoods = shoppingGoodsDao.selectById(item.getGoodsId());
            item.setType(shoppingGoods.getGoodType());
            if (item.getZkPrice() == 0) {
                item.setIsFree(Dictionary.FLAG_YES);
            }
            // 订单欠款减去支付金额 设置实际欠款
            Double itemZkTotal = MoneyUtil.mul(item.getZkPrice(), Double.valueOf(item.getCount()));
            zkTotal = MoneyUtil.add(zkTotal, itemZkTotal);
            item.setStatus(orderStatus);
        }
        SysUsers user = (SysUsers) WebUtil.getSession().getAttribute(MatrixConstance.LOGIN_KEY);
        sysOrder.setZkTotal(zkTotal);
        sysOrder.setStatu(orderStatus);
        SysOrder source = null;
        if (sysOrder.getId() != null) {
            source = sysOrderDao.selectById(sysOrder.getId());
        }
        sysOrder.setStaffId(source != null ? source.getStaffId() : user.getSuId());
        sysOrder.setCompanyId(source != null ? source.getCompanyId() : user.getCompanyId());
        if (sysOrder.getId() == null) {
            //新增订单
            sysOrder.setOrderNo(codeService.getOrderCode());
            sysOrderDao.insert(sysOrder);
            //保存单据日志
            operationLogService.saveOperation(sysOrder.getCompanyId(), sysOrder.getShopId(), user.getSuId(),
                    OperationFunctionEnum.ORDER,
                    OperationButtonEnum.CREATE,
                    sysOrder.getId(),
                    sysOrder.getOrderNo(),
                    sysOrder.getVipId());
        } else {
            //更新订单
            sysOrderDao.update(sysOrder);
            //删除原有订单明细
            orderItemDao.deleteByOrderId(sysOrder.getId());
            //保存单据日志
            operationLogService.saveOperation(sysOrder.getCompanyId(), sysOrder.getShopId(), user.getSuId(),
                    OperationFunctionEnum.ORDER,
                    OperationButtonEnum.UPDATE,
                    sysOrder.getId(),
                    sysOrder.getOrderNo(),
                    sysOrder.getVipId(),
                    "修改订单内容");
        }
        sysOrder.getItems().forEach(sysOrderItem -> {
            sysOrderItem.setOrderId(sysOrder.getId());
            if (sysOrder.getStatu().equals(Dictionary.ORDER_STATU_TK)) {
                // 取负数
                sysOrderItem.setCount(-sysOrderItem.getCount());
                orderItemDao.insert(sysOrderItem);
                // 调整回来
                sysOrderItem.setCount(-sysOrderItem.getCount());
            } else {
                orderItemDao.insert(sysOrderItem);
            }
        });
        return sysOrder;
    }
    /**
     * 取消订单
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelOrder(Long id) {
        SysOrder order = sysOrderDao.selectById(id);
        SysUsers sysUsers = WebUtil.getSessionAttribute(MatrixConstance.LOGIN_KEY);
        if (order.getStatu().equals(Dictionary.ORDER_STATU_DFK)) {
            order.setStatu(Dictionary.ORDER_STATU_YQX);
            order.setArrears(0D);
            //发送微信公众号提醒
            UniformMsgParam uniformMsgParam = new UniformMsgParam(order.getCompanyId(), UniformMsgParam.GZH_DDQX);
            uniformMsgParam.put("orderId", order.getId());
            asyncMessageManager.sendMsg(AsyncMessageRouting.SEND_UNIFORM_TEMPLATE_MSG, uniformMsgParam);
            sysOrderDao.update(order);
            //保存单据日志
            operationLogService.saveOperation(order.getCompanyId(), order.getShopId(),sysUsers.getSuId(),
                    OperationFunctionEnum.ORDER,
                    OperationButtonEnum.CANCEL,
                    order.getId(),
                    order.getOrderNo(),
                    order.getVipId(),
                    "未付款取消订单");
        } else {
            //一个订单只能被取消一次
            if (Dictionary.ORDER_STATU_YQX.equals(order.getStatu())) {
                throw new GlobleException("订单已取消");
            }
            List<SysOrderFlow> flows = sysOrderFlowDao.selectByOrderId(id);
            // 非现金收款退回扣卡余额
            for (SysOrderFlow flow : flows) {
                if (SysOrderFlow.PAY_METHOD_CARD.equals(flow.getPayMethod())) {
                    MoneyCardUse moneyCardUse = moneyCardUseDao.selectById(flow.getCardId());
                    MoneyCardUseFlow moneyCardUseFlow = new MoneyCardUseFlow();
                    if (moneyCardUse != null) {
                        // 根据订单明细判断是赠送金额购买还是本金购买
                        moneyCardUseFlow.setTotal(flow.getAmount().doubleValue());
                        if (SysOrderFlow.IS_GIFT_Y.equals(flow.getIsGift())) {
                            moneyCardUse.setGiftMoney(MoneyUtil.add(moneyCardUse.getGiftMoney(), flow.getAmount().doubleValue()));
                        } else {
                            moneyCardUse.setRealMoney(MoneyUtil.add(moneyCardUse.getRealMoney(), flow.getAmount().doubleValue()));
                        }
                        if (!moneyCardUse.getIsVipCar().equals(Dictionary.FLAG_YES_Y)) {
                            if (moneyCardUse.getLastCount() != null) {
                                moneyCardUse.setLastCount(moneyCardUse.getLastCount() + 1);
                                moneyCardUseFlow.setTimes(1);
                            }
                        }
                        moneyCardUseDao.update(moneyCardUse);
                        //插入充值卡变动流水
                        SysUsers user = WebUtil.getSessionAttribute(MatrixConstance.LOGIN_KEY);
                        moneyCardUseFlow.setOrderNo(order.getOrderNo());
                        moneyCardUseFlow.setCarUseId(moneyCardUse.getId());
                        moneyCardUseFlow.setVipId(order.getVipId());
                        moneyCardUseFlow.setType(MoneyCardUseFlow.USE_TYPE_ORDRE_CANCEL);
                        moneyCardUseFlow.setCreateTime(new Date());
                        moneyCardUseFlow.setOperationId(user.getSuId());
                        moneyCardUseFlow.setContent(moneyCardUse.getChangeRemark());
                        moneyCardUseFlow.setBalance(moneyCardUse.getGiftMoney() + moneyCardUse.getRealMoney());
                        moneyCardUseFlowDao.insert(moneyCardUseFlow);
                    }
                }
            }
            List<SysOrderItem> sysOrderItems = orderItemDao.selectByOrderId(id);
            for (SysOrderItem orderItem : sysOrderItems) {
                // 充值卡类型退款
                if (Dictionary.SHOPPING_GOODS_TYPE_CZK.equals(orderItem.getType())) {
                    ShoppingGoods shoppingGoods = shoppingGoodsDao.selectById(orderItem.getGoodsId());
                    //删除购买的充值卡
                    moneyCardUseDao.deleteByOrderItemId(orderItem.getId());
                } else if (Dictionary.SHOPPING_GOODS_TYPE_XM.equals(orderItem.getType())
                        || Dictionary.SHOPPING_GOODS_TYPE_TC.equals(orderItem.getType())) {
                    // 项目套餐退款
                    // 删除套餐项目使用情况
                    sysProjUseDao.deleteByOrderItemId(orderItem.getId());
                } else if (Dictionary.SHOPPING_GOODS_TYPE_ZHK.equals(orderItem.getType())) {
                    // 综合卡
                    // 删除套餐项目使用情况
                    sysProjUseDao.deleteByOrderItemId(orderItem.getId());
                    // 删除充值卡
                    moneyCardUseDao.deleteByOrderItemId(orderItem.getId());
                }
            }
            //删除出库单,恢复库存
            SysOutStore sysOutStore = new SysOutStore();
            sysOutStore.setOrderId(order.getId());
            List<SysOutStore> sysOutStores = sysOutStoreDao.selectByModel(sysOutStore);
            if (sysOutStores.size() == 1) {
                sysOutStore = sysOutStores.get(0);
                List<SysOutStoreItem> outStoreItemList = sysOutStoreItemDao.selectByOrderId(sysOutStore.getId());
                for (SysOutStoreItem item : outStoreItemList) {
                    SysStoreInfo sysStoreInfo = storeInfoDao.selectById(item.getStoreId());
                    sysStoreInfo.setStoreTotal(sysStoreInfo.getStoreTotal() + item.getAmount());
                    //更新库存
                    storeInfoDao.update(sysStoreInfo);
                }
                sysOutStoreDao.deleteById(sysOutStore.getId());
                sysOutStoreItemDao.deleteByOrderId(sysOutStore.getId());
            }
            // 删除业绩
            AchieveNew achieveNew = new AchieveNew();
            achieveNew.setOrderId(id);
            achieveNewService.removeByModel(achieveNew);
            // 删除收款记录
            sysOrderFlowDao.deleteByOrderId(id);
            //删除积分
            scoreVipDetailService.removeByBusinessId(order.getVipId(), order.getId());
            // 取消订单
            order.setStatu(Dictionary.ORDER_STATU_YQX);
            sysOrderDao.update(order);
            //保存单据日志
            operationLogService.saveOperation(order.getCompanyId(), order.getShopId(),sysUsers.getSuId(),
                    OperationFunctionEnum.ORDER,
                    OperationButtonEnum.CANCEL,
                    order.getId(),
                    order.getOrderNo(),
                    order.getVipId(),
                    "已付款取消订单");
        }
    }
    /**
     * 创建订单 lk
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int createOrder(HttpSession session, ShoppingCarItemsVo car) {
        if (car.getCarItems().size() < 1) {
            throw new GlobleException("没用选择购买产品");
        }
        // 获取会员信息,判断等级 获取相应家居折扣
        SysVipInfo info = sysVipInfoDao.selectById(car.getVipId());
        //获取折扣-----
        Double zk = zk = 1.0;
        SysOrder order = new SysOrder();
        SysUsers user = (SysUsers) WebUtil.getSession().getAttribute(MatrixConstance.LOGIN_KEY);
        order.setShopId(user.getShopId());
        order.setOrderNo(codeService.getOrderCode());
        order.setVipId(info.getId());
        order.setOrderTime(new Date());
        order.setRemark(car.getRemark());
        order.setStaffId(user.getSuId());
        order.setIsCross(2 + "");
        order.setChangeId(car.getChangeId());
        order.setStatu(Dictionary.ORDER_STATU_DFK);
        order.setCardPay(0.00);
        order.setCashPay(0.00);
        order.setCompanyId(user.getCompanyId());
        order.setBeatuyId(car.getBeatuyId() + "");
        // 根据美疗师id查询美疗师姓名
        if (car.getBeatuyId() != null) {
            String beatuyName = shopStaffInfoDao.selectById(car.getBeatuyId()).getSuName();
            System.out.println("美疗师:" + beatuyName);
            order.setBeatuyName(beatuyName);
        }
        int i = sysOrderDao.insert(order);
        // 创建订单明细,并计算总价与折扣总价
        // 总价
        double total = 0;
        double zkTotal = 0;
        int count = 0;
        // 设置订单条目
        for (ShoppingCarItem carItem : car.getCarItems()) {
            SysOrderItem orderItem = new SysOrderItem();
            orderItem.setOrderId(order.getId());
            orderItem.setCount(carItem.getCount());
            orderItem.setIsFree(carItem.getIsFree());
            orderItem.setType(carItem.getType());
            orderItem.setStatus(Dictionary.ORDER_STATU_DFK);
            // 新增明细
            // 设置商品id
            orderItem.setGoodsId(carItem.getGoodsId());
            // 设置assembleId
            orderItem.setAssembleId(carItem.getAssembleId());
            // 如果是家居产品的话,要取出组合sku中的价格
            double p = carItem.getShoppingGoods().getSealPice();
            orderItem.setPrice(p);
            if (carItem.getIsFree().equals(Dictionary.FLAG_NO)) {
                orderItem.setZkPrice(MoneyUtil.mul(p, zk));
            } else {
                // 如果是免费,则设置为0.0
                orderItem.setZkPrice(0.0);
            }
            orderItemDao.insert(orderItem);
            total = MoneyUtil.add(total,
                    MoneyUtil.mul(orderItem.getPrice(), Double.parseDouble(carItem.getCount() + "")));
            zkTotal = MoneyUtil.add(zkTotal,
                    MoneyUtil.mul(orderItem.getZkPrice(), Double.parseDouble(carItem.getCount() + "")));
        }
        // 设置订单总价与折后价
        order.setTotal(total);
        order.setZkTotal(zkTotal);
        sysOrderDao.update(order);
        return i;
    }
    /**
     * jyy 收款
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateReceiptMoney(SysOrder pageOrder) throws GlobleException {
        if (!Dictionary.ORDER_STATU_DFK.equals(pageOrder.getStatu())) {
            throw new GlobleException("该订单已经收过款,请刷新页面再试!");
        }
        checkOrder(pageOrder);
        // 更新收款时间
        updateOrderInfo(pageOrder);
        // 获取用户信息
        SysVipInfo vipInfo = sysVipInfoDao.selectById(pageOrder.getVipId());
        if (SysVipInfo.UNDEAL_VIP == vipInfo.getIsDeal()) {
            //非成交客户下单更新客户为成交客户
            vipInfo.setIsDeal(SysVipInfo.DEAL_VIP);
            sysVipInfoDao.update(vipInfo);
        }
        //添加支付流水
        addOrderFlow(pageOrder);
        // 设置会员充值卡使用情况
        addMoneyCardUse(pageOrder);
        // 改变客户项目套餐使用情况
        addTaocanProj(pageOrder);
        // 新增出库单
        addOutStore(pageOrder);
        // 设置业绩
        achieveNewService.addAchaeveByOrder(pageOrder);
        setShopSelCount(pageOrder);
        //设置会员积分
        addVipScore(pageOrder);
    }
    /**
     * 付款后更新订单信息
     *
     * @param pageOrder
     */
    private void updateOrderInfo(SysOrder pageOrder) {
        SysUsers user = (SysUsers) WebUtil.getSession().getAttribute(MatrixConstance.LOGIN_KEY);
        pageOrder.setCashierId(user.getSuId());
        pageOrder.setPayTime(new Date());
        pageOrder.setStatu(Dictionary.ORDER_STATU_YFK);
        List<SysOrderFlow> flows = pageOrder.getFlows();
        BigDecimal cashPayAmount = flows.stream()
                .filter(item -> (!item.getPayMethod().equals("储值卡")) && (!item.getPayMethod().equals("欠款")))
                .map(SysOrderFlow::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal cardPayAmount = flows.stream()
                .filter(item -> item.getPayMethod().equals("储值卡"))
                .map(SysOrderFlow::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        pageOrder.setCardPay(cardPayAmount.doubleValue());
        pageOrder.setCashPay(cashPayAmount.doubleValue());
        //欠款金额在流水处理中处理了
        double sum = flows.stream().mapToDouble(item -> item.getAmount().doubleValue()).sum();
        if (sum > 0 && cardPayAmount.doubleValue() == 0 && cashPayAmount.doubleValue() == 0) {
            throw new GlobleException("订单更新失败,支付金额计算错误,请联系管理员");
        }
        sysOrderDao.update(pageOrder);
        //保存单据日志
        operationLogService.saveOperation(pageOrder.getCompanyId(), pageOrder.getShopId(), user.getSuId(),
                OperationFunctionEnum.ORDER,
                OperationButtonEnum.ORDER_SK,
                pageOrder.getId(),
                pageOrder.getOrderNo(),
                pageOrder.getVipId());
    }
    private void checkOrder(SysOrder pageOrder) {
        //检查交易限制调整
        checkSealLimit(pageOrder);
        //检查业绩设置
        checkOrderAchieve(pageOrder);
    }
    /**
     * 检查业绩设置是否合理
     * 1、每个订单明细都要有至少一个对应的业绩
     * 2、每个订单明细的同类型业绩金额之和不能大于明细支付金额
     *
     * @param pageOrder
     */
    private void checkOrderAchieve(SysOrder pageOrder) {
        pageOrder.getItems().forEach(item -> {
            if (CollectionUtil.isEmpty(item.getAchieveList())) {
                ShoppingGoods shopGoods = shoppingGoodsDao.selectById(item.getGoodsId());
                throw GlobleException.instance(shopGoods.getName() + "缺少设置业绩");
            }
            //按业绩类型分组后比较支付金额与业绩金额是否相等
            Map<String, List<AchieveNew>> achieveTypeMap = item.getAchieveList().stream().collect(Collectors.groupingBy(AchieveNew::getAchieveType));
            Set<Map.Entry<String, List<AchieveNew>>> entries = achieveTypeMap.entrySet();
            entries.forEach(entrie -> {
                double sum = entrie.getValue().stream().mapToDouble(AchieveNew::getGoodsCash).sum();
                //todo 目前使用js计算金额可能存在精度的误差展示用0.1屏蔽
                if (Math.abs(sum - (item.getZkPrice() * item.getCount())) > 0.1) {
                    ShoppingGoods shopGoods = shoppingGoodsDao.selectById(item.getGoodsId());
                    throw GlobleException.instance(shopGoods.getName() + "," + entrie.getKey() + "业绩金额与收款金额不一致");
                }
            });
        });
    }
    /**
     * 检查产品销售次数
     */
    private void checkSealLimit(SysOrder pageOrder) {
        pageOrder.getItems().forEach(item -> {
            ShoppingGoods shopGoods = shoppingGoodsDao.selectById(item.getGoodsId());
            //最大销售次数检测
            Integer maxNum = shopGoods.getCarMaxSaleCount();
            if (maxNum != null && maxNum != 0) {
                Integer buyNum = orderItemDao.selectByGoodsId(shopGoods.getId(), null);
                if ((buyNum + item.getCount()) > maxNum) {
                    throw new GlobleException(shopGoods.getName() + "已超过最大销售数量");
                }
                if ((buyNum + item.getCount()) == maxNum) {
                    if (!shopGoods.getStaus().equals(Dictionary.BUSINESS_STATE_DOWN)) {
                        shopGoods.setStaus(Dictionary.BUSINESS_STATE_DOWN);
                        shoppingGoodsDao.update(shopGoods);
                    }
                }
            }
            //每人限购次数检测
            Integer onceCount = shopGoods.getIsOnce();
            if (onceCount != null && onceCount != 0) {
                Integer buyOnceCount = orderItemDao.selectByGoodsId(shopGoods.getId(), pageOrder.getVipId());
                if ((buyOnceCount + item.getCount()) > onceCount) {
                    throw new GlobleException(shopGoods.getName() + "每人限购" + onceCount + "次");
                }
            }
        });
    }
    /**
     * 设置会员消费积分
     *
     * @param pageOrder
     */
    private void addVipScore(SysOrder pageOrder) {
        SysVipInfo vipInfo = sysVipInfoDao.selectById(pageOrder.getVipId());
        List<SysOrderFlow> flows = pageOrder.getFlows();
        int[] cashScore = {0, 0, 0};
        //现金支付金额
        BigDecimal cashPayAmount = flows.stream()
                .filter(item -> (!item.getPayMethod().equals("储值卡")) && (!item.getPayMethod().equals("欠款")))
                .map(SysOrderFlow::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        BusParameterSettings cashConsumption = busParameterSettingsDao.selectCompanyParamByCode(ScoreSettingConstant.CASH_CONSUMPTION, vipInfo.getCompanyId());
        if (cashPayAmount != null
                && cashPayAmount.compareTo(BigDecimal.ZERO) > 0
                && StringUtils.isNotBlank(cashConsumption.getParamValue())) {
            BigDecimal scoreSetting0 = new BigDecimal(cashConsumption.getParamValue());
            if (scoreSetting0.compareTo(BigDecimal.ZERO) > 0) {
                cashScore[0] = cashPayAmount.divide(scoreSetting0).intValue();
            }
            if (StringUtils.isNotBlank(cashConsumption.getParamValue1())) {
                BigDecimal scoreSetting1 = new BigDecimal(cashConsumption.getParamValue1());
                if (scoreSetting1.compareTo(BigDecimal.ZERO) > 0) {
                    cashScore[1] = cashPayAmount.divide(scoreSetting1).intValue();
                }
            }
            if (StringUtils.isNotBlank(cashConsumption.getParamValue2())) {
                BigDecimal scoreSetting2 = new BigDecimal(cashConsumption.getParamValue2());
                if (scoreSetting2.compareTo(BigDecimal.ZERO) > 0) {
                    cashScore[2] = cashPayAmount.divide(scoreSetting2).intValue();
                }
            }
        }
        int[] cardScore = {0, 0, 0};
        //储值卡本金支付金额
        BigDecimal cardPayAmount = flows.stream()
                .filter(item -> item.getPayMethod().equals("储值卡") && item.getIsGift().equals("N"))
                .map(SysOrderFlow::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        BusParameterSettings principalBalanceConsumption = busParameterSettingsDao.selectCompanyParamByCode(ScoreSettingConstant.PRINCIPAL_BALANCE_CONSUMPTION, vipInfo.getCompanyId());
        if (cardPayAmount != null
                && cardPayAmount.compareTo(BigDecimal.ZERO) > 0
                && StringUtils.isNotBlank(principalBalanceConsumption.getParamValue())) {
            BigDecimal scoreSetting0 = new BigDecimal(principalBalanceConsumption.getParamValue());
            if (scoreSetting0.compareTo(BigDecimal.ZERO) > 0) {
                cardScore[0] = cardPayAmount.divide(scoreSetting0).intValue();
            }
            if (StringUtils.isNotBlank(principalBalanceConsumption.getParamValue1())) {
                BigDecimal scoreSetting1 = new BigDecimal(principalBalanceConsumption.getParamValue1());
                if (scoreSetting1.compareTo(BigDecimal.ZERO) > 0) {
                    cardScore[1] = cardPayAmount.divide(scoreSetting1).intValue();
                }
            }
            if (StringUtils.isNotBlank(principalBalanceConsumption.getParamValue2())) {
                BigDecimal scoreSetting2 = new BigDecimal(principalBalanceConsumption.getParamValue2());
                if (scoreSetting2.compareTo(BigDecimal.ZERO) > 0) {
                    cardScore[2] = cardPayAmount.divide(scoreSetting2).intValue();
                }
            }
        }
        int[] giftScore = {0, 0, 0};
        //储值卡本赠送付金额
        BigDecimal giftPayAmount = flows.stream()
                .filter(item -> item.getPayMethod().equals("储值卡") && item.getIsGift().equals("Y"))
                .map(SysOrderFlow::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        BusParameterSettings bonusBalanceConsumption = busParameterSettingsDao.selectCompanyParamByCode(ScoreSettingConstant.BONUS_BALANCE_CONSUMPTION, vipInfo.getCompanyId());
        if (giftPayAmount != null
                && giftPayAmount.compareTo(BigDecimal.ZERO) > 0
                && StringUtils.isNotBlank(bonusBalanceConsumption.getParamValue())) {
            BigDecimal scoreSetting0 = new BigDecimal(bonusBalanceConsumption.getParamValue());
            if (scoreSetting0.compareTo(BigDecimal.ZERO) > 0) {
                giftScore[0] = giftPayAmount.divide(scoreSetting0).intValue();
            }
            if (StringUtils.isNotBlank(bonusBalanceConsumption.getParamValue1())) {
                BigDecimal scoreSetting1 = new BigDecimal(bonusBalanceConsumption.getParamValue1());
                if (scoreSetting1.compareTo(BigDecimal.ZERO) > 0) {
                    giftScore[1] = giftPayAmount.divide(scoreSetting1).intValue();
                }
            }
            if (StringUtils.isNotBlank(bonusBalanceConsumption.getParamValue2())) {
                BigDecimal scoreSetting2 = new BigDecimal(bonusBalanceConsumption.getParamValue2());
                if (scoreSetting2.compareTo(BigDecimal.ZERO) > 0) {
                    giftScore[2] = giftPayAmount.divide(scoreSetting2).intValue();
                }
            }
        }
        int selfScore = cashScore[0] + cardScore[0] + giftScore[0];
        int parentScore = cashScore[1] + cardScore[1] + giftScore[1];
        int topParentScore = cashScore[2] + cardScore[2] + giftScore[2];
        //添加自己的积分
        if (selfScore > 0) {
            scoreVipDetailService.addScore(
                    vipInfo.getId(),
                    pageOrder.getStaffId(),
                    pageOrder.getShopId(),
                    selfScore,
                    pageOrder.getId(),
                    ScoreVipDetail.SCORE_VIP_TYPE_CASH,
                    "消费奖励"
            );
        }
        if (vipInfo.getRecommendId() != null) {
            //推荐注册老带新积分奖励
            SysVipInfo referrerVip = sysVipInfoDao.selectById(vipInfo.getRecommendId());
            if (parentScore > 0) {
                scoreVipDetailService.addScore(
                        referrerVip.getId(),
                        pageOrder.getStaffId(),
                        pageOrder.getShopId(),
                        parentScore,
                        pageOrder.getId(),
                        ScoreVipDetail.SCORE_VIP_TYPE_CASH,
                        "推荐消费奖励"
                );
            }
            //推荐注册二级带新积分奖励
            if (referrerVip.getRecommendId() != null) {
                SysVipInfo topVipInfo = sysVipInfoDao.selectById(referrerVip.getRecommendId());
                if (topParentScore > 0) {
                    scoreVipDetailService.addScore(
                            topVipInfo.getId(),
                            pageOrder.getStaffId(),
                            pageOrder.getShopId(),
                            topParentScore,
                            pageOrder.getId(),
                            ScoreVipDetail.SCORE_VIP_TYPE_CASH,
                            "推荐消费奖励"
                    );
                }
            }
        }
    }
    /**
     * 创建支付流水
     *
     * @author:姜友瑶
     */
    private void addOrderFlow(SysOrder sourceOrder) {
        //处理支付流水
        int flowCount = 1;
        for (SysOrderFlow flow : sourceOrder.getFlows()) {
            //支付内容摘要设置
            Long goodsId = sourceOrder.getItems().get(0).getGoodsId();
            ShoppingGoods goods = shoppingGoodsDao.selectById(goodsId);
            flow.setFlowContent(goods.getName() + "等" + sourceOrder.getItems().size() + "件产品");
            // 若是退款,则取负数
            if (SysOrder.ORDER_TYPE_REFUND == sourceOrder.getOrderType()) {
                flow.setFlowType(SysOrderFlow.FLOW_TYPE_REFUND);
                flow.setAmount(flow.getAmount().negate());
                flow.setOrderId(sourceOrder.getOldOrderId());
            } else {
                flow.setFlowType(SysOrderFlow.FLOW_TYPE_BUY);
                flow.setOrderId(sourceOrder.getId());
            }
            //欠款处理
            if (SysOrderFlow.PAY_METHOD_ARREARS.equals(flow.getPayMethod())) {
                sourceOrder.setStatu(Dictionary.ORDER_STATU_QK);
                sourceOrder.setArrears(flow.getAmount().doubleValue());
                sysOrderDao.update(sourceOrder);
            }
            //统计储值卡支付
            if (SysOrderFlow.PAY_METHOD_CARD.equals(flow.getPayMethod())) {
                if (flow.getCardId() != null) {
                    MoneyCardUse moneyCardUse = moneyCardUseDao.selectById(flow.getCardId());
                    //修改储值卡余额
                    cardPaySk(moneyCardUse, sourceOrder, flow);
                } else {
                    throw new GlobleException("无效的储值卡支付方式");
                }
            }
            flow.setFlowNo(codeService.getFlowCode() + "-" + flowCount);
            flow.setVipId(sourceOrder.getVipId());
            flow.setShopId(sourceOrder.getShopId());
            flow.setCompanyId(sourceOrder.getCompanyId());
            sysOrderFlowDao.insert(flow);
            flowCount++;
        }
    }
    /**
     * 验证商品是否达到最大发卡限制
     *
     * @author jiangyouyao
     */
    private void checkIsArrivedMax(ShoppingCarItem carItem) {
        // 获取该商品的最大购买数量
        ShoppingGoods shopGoods = shoppingGoodsDao.selectById(carItem.getGoodsId());
        Integer maxNum = shopGoods.getCarMaxSaleCount();
        // 最大发卡数量为0代表不做限制
        if (maxNum != null && maxNum != 0) {
            // 查询该商品已经被购买的次数
            Integer buyNum = orderItemDao.selectByGoodsId(shopGoods.getId(), null);
            buyNum = (buyNum == null ? 0 : buyNum);
            if ((buyNum + carItem.getCount()) > maxNum) {
                throw new GlobleException(shopGoods.getName() + "已超过最大销售数量");
            }
            if ((buyNum + carItem.getCount()) == maxNum) {
                if (!shopGoods.getStaus().equals(Dictionary.BUSINESS_STATE_DOWN)) {
                    shopGoods.setStaus(Dictionary.BUSINESS_STATE_DOWN);
                    shoppingGoodsDao.update(shopGoods);
                }
            }
        }
    }
    /**
     * 使用充值卡付款操作
     *
     * @param sourceOrder
     * @param moneyCardUse
     * @param flow
     */
    private void cardPaySk(MoneyCardUse moneyCardUse, SysOrder sourceOrder, SysOrderFlow flow) {
        // 判断商品是否在充值卡的限制购买,判断分类
        sourceOrder.getItems().forEach(item -> {
            if (!isInBangding(moneyCardUse, item.getGoodsId())) {
                throw new GlobleException(shoppingGoodsDao.selectById(item.getGoodsId()).getName() + "不在" + moneyCardUse.getCardName() + "优惠中");
            }
        });
        SysUsers user = (SysUsers) WebUtil.getSession().getAttribute(MatrixConstance.LOGIN_KEY);
        MoneyCardUseFlow moneyCardUseFlow = new MoneyCardUseFlow();
        if (SysOrderFlow.IS_GIFT_Y.equals(flow.getIsGift())) {
            if (moneyCardUse.getGiftMoney() >= flow.getAmount().doubleValue()) {
                double surplus = MoneyUtil.sub(moneyCardUse.getGiftMoney(), flow.getAmount().doubleValue());
                moneyCardUse.setGiftMoney(surplus);
                moneyCardUseFlow.setGiftMoney(0D - flow.getAmount().doubleValue());
            } else {
                throw new GlobleException(moneyCardUse.getCardName() + "余额不足");
            }
        } else {
            if (moneyCardUse.getRealMoney() >= flow.getAmount().doubleValue()) {
                double surplus = MoneyUtil.sub(moneyCardUse.getRealMoney(), flow.getAmount().doubleValue());
                moneyCardUse.setRealMoney(surplus);
                moneyCardUseFlow.setTotal(0 - flow.getAmount().doubleValue());
            } else {
                throw new GlobleException(moneyCardUse.getCardName() + "余额不足");
            }
        }
        if (moneyCardUse.getIsVipCar().equals(Dictionary.FLAG_NO_N)) {
            //余额为0时充值卡变为无效
            if (moneyCardUse.getRealMoney().equals(0D) && moneyCardUse.getGiftMoney().equals(0D)) {
                moneyCardUse.setIsOver(Dictionary.FLAG_YES_Y);
                moneyCardUse.setStatus(Dictionary.MONEYCARD_STATUS_WX);
            }
        }
        ShoppingGoods shoppingGoods = shoppingGoodsService.findById(moneyCardUse.getGoodsId());
        if (shoppingGoods != null) {
            Date invalidTime = shoppingGoodsService.calInvalidTime(shoppingGoods, 2, moneyCardUse.getFailTime());
            moneyCardUse.setFailTime(invalidTime);
        }
        // 更新充值卡信息
        moneyCardUseDao.update(moneyCardUse);
        //设置卡项使用流水
        moneyCardUseFlow.setCarUseId(moneyCardUse.getId());
        moneyCardUseFlow.setOrderNo(sourceOrder.getOrderNo());
        moneyCardUseFlow.setVipId(sourceOrder.getVipId());
        moneyCardUseFlow.setTimes(-1);
        moneyCardUseFlow.setType(MoneyCardUseFlow.USE_TYPE_CONSUMER);
        moneyCardUseFlow.setCreateTime(new Date());
        moneyCardUseFlow.setOperationId(user.getSuId());
        moneyCardUseFlow.setBalance(moneyCardUse.getGiftMoney() + moneyCardUse.getRealMoney());
        moneyCardUseFlowDao.insert(moneyCardUseFlow);
    }
    /**
     * @param moneyCardUse
     * @param goodsId
     * @return 返回类型 boolean
     * 判断商品是否在充值卡的优惠中
     * @author:姜友瑶
     * @date 2016年9月19日
     */
    private boolean isInBangding(MoneyCardUse moneyCardUse, Long goodsId) {
        // 如果是一卡通则肯定在绑定范围内
        if (moneyCardUse.getIsVipCar().equals(Dictionary.FLAG_YES_Y)) {
            return true;
        } else {
            // 不是一卡通,
            // 判断卡是否可应用于所有产品
            ShoppingGoods cardGoods = shoppingGoodsDao.selectById(moneyCardUse.getGoodsId());
            if (cardGoods != null) {
                if (Dictionary.FLAG_YES.equals(cardGoods.getCarIsAll())) {
                    return true;
                }
            }
            // 比较分类
            MoneyCardAssemble moneyCardAssemble = new MoneyCardAssemble();
            moneyCardAssemble.setCardId(moneyCardUse.getGoodsId());
            List<MoneyCardAssemble> cardAssembleList = moneyCardAssembleDao.selectByModel(moneyCardAssemble);
            ShoppingGoods yhGoods = shoppingGoodsDao.selectById(goodsId);
            boolean flag = false;
            for (MoneyCardAssemble cardAssemble : cardAssembleList) {
                // 比较类型
                if (cardAssemble.getType().equals(Dictionary.CZK_ASSEMBLE_FL)) {
                    if (yhGoods.getCateId().equals(cardAssemble.getCateId())) {
                        flag = true;
                        break;
                    }
                } else {
                    // 比较绑定
                    if (yhGoods.getId().equals(cardAssemble.getGoodsId())) {
                        flag = true;
                        break;
                    }
                }
            }
            return flag;
        }
    }
    /**
     * 设置销量
     *
     * @param sourceOrder
     */
    public void setShopSelCount(SysOrder sourceOrder) {
        for (SysOrderItem item : sourceOrder.getItems()) {
            // 正真实销量
            ShoppingGoods goods = shoppingGoodsDao.selectById(item.getGoodsId());
            if (goods.getRealSealCount() == null) {
                goods.setRealSealCount(item.getCount());
            } else {
                goods.setRealSealCount(goods.getRealSealCount() + item.getCount());
            }
            shoppingGoodsDao.update(goods);
        }
    }
    /**
     * @param sourceOrder 如果购买了充值卡设置会员的充值卡
     * @author:姜友瑶
     * @date 2016年9月19日
     */
    public void addMoneyCardUse(SysOrder sourceOrder) {
        SysUsers user = WebUtil.getSessionAttribute(MatrixConstance.LOGIN_KEY);
        List<SysOrderItem> orderItemList = sourceOrder.getItems();
        for (SysOrderItem sysOrderItem : orderItemList) {
            // 如果购买的是充值卡
            if (sysOrderItem.getType().equals(Dictionary.SHOPPING_GOODS_TYPE_CZK)) {
                for (int i = 0; i < sysOrderItem.getCount(); i++) {
                    ShoppingGoods moneyCar = shoppingGoodsDao.selectById(sysOrderItem.getGoodsId());
                    MoneyCardUse moneyCardUse = new MoneyCardUse();
                    moneyCardUse.setVipId(sourceOrder.getVipId());
                    moneyCardUse.setGiftMoney(moneyCar.getReferencePice());
                    moneyCardUse.setRealMoney(moneyCar.getSealPice());
                    moneyCardUse.setGoodsId(moneyCar.getId());
                    moneyCardUse.setOrderItemId(sysOrderItem.getId());
                    moneyCardUse.setSource(Dictionary.TAOCAN_SOURCE_GM);
                    moneyCardUse.setStatus(Dictionary.MONEYCARD_STATUS_YX);
                    moneyCardUse.setCardName(moneyCar.getName());
                    moneyCardUse.setIsVipCar(Dictionary.FLAG_NO_N);
                    moneyCardUse.setVipId(sourceOrder.getVipId());
                    // 是否为赠送
                    if (sysOrderItem.getIsFree().equals(Dictionary.FLAG_YES)) {
                        moneyCardUse.setSource(Dictionary.TAOCAN_SOURCE_ZS);
                    } else {
                        moneyCardUse.setSource(Dictionary.TAOCAN_SOURCE_GM);
                    }
                    //余次处理
                    if (moneyCar.getCarUseCount() == null || moneyCar.getCarUseCount() == 0) {
                        moneyCardUse.setUseTotal(999999999);
                        moneyCardUse.setLastCount(999999999);
                    } else {
                        moneyCardUse.setUseTotal(moneyCar.getCarUseCount());
                        moneyCardUse.setLastCount(moneyCar.getCarUseCount());
                    }
                    //失效时间处理
                    Date invalidTime = shoppingGoodsService.calInvalidTime(sysOrderItem.getShoppingGoods(), 1, null);
                    moneyCardUse.setFailTime(invalidTime);
                    moneyCardUseDao.insert(moneyCardUse);
                }
            }
        }
    }
    /**
     * @author:姜友瑶
     * @date 2016年9月19日
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateAfterMoney(SysOrder pageOrder) {
        SysOrder sourceOrder = sysOrderDao.selectById(pageOrder.getId());
        int i = 1;
        double refundTotal = 0D;
        double cardPayTotal = 0D;
        double cashPayTotal = 0D;
        for (SysOrderFlow flow : pageOrder.getFlows()) {
            flow.setFlowNo(codeService.getFlowCode() + "-" + i);
            Long goodsId = pageOrder.getItems().get(0).getGoodsId();
            ShoppingGoods goods = shoppingGoodsDao.selectById(goodsId);
            flow.setFlowContent(goods.getName() + "等" + pageOrder.getItems().size() + "件产品");
            flow.setOrderId(pageOrder.getId());
            flow.setVipId(pageOrder.getVipId());
            flow.setFlowType(SysOrderFlow.FLOW_TYPE_REPAY);
            // 若使用储值卡付款
            if (SysOrderFlow.PAY_METHOD_CARD.equals(flow.getPayMethod())) {
                if (flow.getCardId() != null) {
                    cardPayTotal += flow.getAmount().doubleValue();
                    MoneyCardUse moneyCardUse = moneyCardUseDao.selectById(flow.getCardId());
                    cardPaySk(moneyCardUse, pageOrder, flow);
                }
            } else {
                cashPayTotal += flow.getAmount().doubleValue();
            }
            refundTotal += flow.getAmount().doubleValue();
            flow.setShopId(sourceOrder.getShopId());
            flow.setCompanyId(sourceOrder.getCompanyId());
            sysOrderFlowDao.insert(flow);
            i++;
        }
        boolean haQk = false;
        if (refundTotal == pageOrder.getArrears()) {
            haQk = true;
        }
        //更新收款状态
        if (haQk) {
            sourceOrder.setStatu(Dictionary.ORDER_STATU_YFK);
        } else {
            sourceOrder.setStatu(Dictionary.ORDER_STATU_QK);
        }
        sourceOrder.setArrears(sourceOrder.getArrears() - refundTotal);
        sourceOrder.setCardPay(sourceOrder.getCardPay() == null ? 0 : sourceOrder.getCardPay() + cardPayTotal);
        sourceOrder.setCashPay(sourceOrder.getCashPay() == null ? 0 : sourceOrder.getCashPay() + cashPayTotal);
        sysOrderDao.update(sourceOrder);
    }
    /**
     * @param order 新增出库单并更新本店库存
     * @author:姜友瑶
     * @date 2016年9月2日
     */
    @Override
    public void addOutStore(SysOrder order) {
        BusParameterSettings manageStockSetting = busParameterSettingsDao.selectCompanyParamByCode(AppConstance.WAREHOUSE_MANAGE_STOCK, order.getCompanyId());
        if (AppConstance.IS_Y.equals(manageStockSetting.getParamValue())) {
            List<SysOutStoreItem> storeItemList = new ArrayList<>();
            for (SysOrderItem sysOrderItem : order.getItems()) {
                if (ShoppingGoods.SHOPPING_GOODS_TYPE_JJCP.equals(sysOrderItem.getType())) {
                    SysOutStoreItem storeItem = new SysOutStoreItem();
                    storeItem.setSkuId(sysOrderItem.getGoodsId());
                    storeItem.setAmount(Double.valueOf(sysOrderItem.getCount()));
                    storeItemList.add(storeItem);
                } else if (ShoppingGoods.SHOPPING_GOODS_TYPE_TC.equals(sysOrderItem.getType())
                        || ShoppingGoods.SHOPPING_GOODS_TYPE_ZHK.equals(sysOrderItem.getType())) {
                    List<ShoppingGoodsAssemble> goodsList = new ArrayList<>();
                    goodsList.addAll(shoppingGoodsAssembleDao.selectGoodsByShoppingGoodsIdAndType(sysOrderItem.getGoodsId(), ShoppingGoods.SHOPPING_GOODS_TYPE_JJCP));
                    if (ShoppingGoods.SHOPPING_GOODS_TYPE_ZHK.equals(sysOrderItem.getType())) {
                        //综合卡处理,中的套餐,中的家居产品
                        List<ShoppingGoodsAssemble> zhkAssemble = shoppingGoodsAssembleDao.selectGoodsByShoppingGoodsIdAndType(sysOrderItem.getGoodsId(), ShoppingGoods.SHOPPING_GOODS_TYPE_TC);
                        zhkAssemble.forEach(item -> {
                            goodsList.addAll(shoppingGoodsAssembleDao.selectGoodsByShoppingGoodsIdAndType(item.getAssembleGoodId(), ShoppingGoods.SHOPPING_GOODS_TYPE_JJCP));
                        });
                    }
                    goodsList.forEach(item -> {
                        SysOutStoreItem storeItem = new SysOutStoreItem();
                        storeItem.setSkuId(item.getAssembleGoodId());
                        storeItem.setAmount(Double.valueOf(item.getTotal()));
                        storeItemList.add(storeItem);
                    });
                }
            }
            if (CollectionUtils.isNotEmpty(storeItemList)) {
                Long warehouseId = warehouseDao.findShopWarehouse(order.getShopId()).get(0).getId();
                SysOutStore outStore = new SysOutStore();
                outStore.setOutStoreNo(codeService.getOutStoreCode());
                outStore.setOrderId(order.getId());
                outStore.setShopId(order.getShopId());
                outStore.setShopId(order.getShopId());
                outStore.setStaffId(order.getStaffId());
                outStore.setType(Dictionary.OUT_STORE_JJCPCK);
                outStore.setServiceNo(order.getOrderNo());
                outStore.setTime(new Date());
                outStore.setCheckStatus(Dictionary.CHECK_STATUS_DSH);
                outStore.setCompanyId(order.getCompanyId());
                sysOutStoreDao.insert(outStore);
                //出库明细,根据批次维度定义
                List<SysOutStoreItem> realOutStoreItemList = new ArrayList<>();
                storeItemList.forEach(outStoreItem -> {
                    //设置出库主键
                    outStoreItem.setOutStoreId(outStore.getId());
                    //计算库存总数是否满足本次扣减的需求
                    List<SysStoreInfo> stores = storeInfoDao.selectStoInfoBySku(outStoreItem.getSkuId(), warehouseId);
                    double sum = stores.stream().mapToDouble(item -> item.getStoreTotal()).sum();
                    if (sum < outStoreItem.getAmount()) {
                        ShoppingGoods sysGoods = shoppingGoodsDao.selectById(outStoreItem.getSkuId());
                        if (sysGoods != null) {
                            throw new GlobleException("出库失败:【" + sysGoods.getName() + "库存不足】");
                        } else {
                            throw new GlobleException("出库失败没有找到出库产品");
                        }
                    }
                    //循环获取所有批次产品,并扣减库存
                    Double number = outStoreItem.getAmount();
                    for (SysStoreInfo storeInfo : stores) {
                        Double oldStoreTotal = storeInfo.getStoreTotal();
                        Double surplus = storeInfo.getStoreTotal() - number;
                        //更新库存
                        storeInfo.setStoreTotal(surplus < 0 ? 0 : surplus);
                        //每次扣减库存都创建一个出库记录
                        SysOutStoreItem sysOutStoreItem = new SysOutStoreItem();
                        BeanUtils.copyProperties(outStoreItem, sysOutStoreItem);
                        sysOutStoreItem.setStoreId(storeInfo.getId());
                        sysOutStoreItem.setAmount(oldStoreTotal - storeInfo.getStoreTotal());
                        realOutStoreItemList.add(sysOutStoreItem);
                        storeInfoDao.update(storeInfo);
                        //扣除后剩余库存大于0则跳出扣除,否则剩余数量的负数的绝对值就是再次扣减的数量
                        if (surplus > 0) {
                            break;
                        } else {
                            number = Math.abs(surplus);
                        }
                    }
                });
                sysOutStoreItemDao.batchInsert(realOutStoreItemList);
            }
        } else {
            LogUtil.debug("不管理库存");
        }
    }
    /**
     * 新增项目和套餐的余次
     *
     * @author:姜友瑶
     * @date 2016年9月2日
     */
    public void addTaocanProj(SysOrder order) {
        List<SysOrderItem> itemList = order.getItems();
        for (SysOrderItem sysOrderItem : itemList) {
            // 折扣 项目的实际购买除以项目原价,来计算项目的消耗价格
            // 赠送 计算全额的消耗业绩
            if (sysOrderItem.getType().equals(Dictionary.SHOPPING_GOODS_TYPE_XM)) {
                createXmProjuse(order, sysOrderItem);
            } else if (sysOrderItem.getType().equals(Dictionary.SHOPPING_GOODS_TYPE_TC)) {
                //每个套餐独立生成一个明细
                int orderCount = sysOrderItem.getCount();
                while (orderCount > 0) {
                    createTaocanProjUse(order, sysOrderItem, null);
                    orderCount--;
                }
            } else if (sysOrderItem.getType().equals(Dictionary.SHOPPING_GOODS_TYPE_ZHK)) {
                addZongheCarUse(order, sysOrderItem);
            }
        }
    }
    public void addZongheCarUse(SysOrder order, SysOrderItem sysOrderItem) {
        //处理一个订单买多次
        int orderCount = sysOrderItem.getCount();
        while (orderCount < 0) {
            orderCount--;
            //综合卡中包含的项目
            List<ShoppingGoodsAssemble> assembleList = shoppingGoodsAssembleDao.selectGoodsByShoppingGoodsIdAndType(sysOrderItem.getGoodsId(), ShoppingGoods.SHOPPING_GOODS_TYPE_XM);
            assembleList.forEach(item -> {
                //TODO 补综合卡逻辑
                createProjuseByAssemble(order, sysOrderItem, item, null, null, null, 0);
            });
            //处理综合卡中包含的套餐
            List<ShoppingGoodsAssemble> zhkAssemble = shoppingGoodsAssembleDao.selectGoodsByShoppingGoodsIdAndType(sysOrderItem.getGoodsId(), ShoppingGoods.SHOPPING_GOODS_TYPE_TC);
            zhkAssemble.forEach(taocan -> {
                int assembleCount = taocan.getTotal();
                while (assembleCount > 0) {
                    assembleCount--;
                    createTaocanProjUse(order, sysOrderItem, taocan);
                }
            });
        }
    }
    /**
     * 通过组合关系创建用户项目余次
     */
    private SysProjUse createProjuseByAssemble(SysOrder order, SysOrderItem sysOrderItem,
                                               ShoppingGoodsAssemble goodsAssemble, Long taocanId, Date failTime, String source, Integer maxCount) {
        //计算折扣
        Double zk = sysOrderItem.getZkPrice() / sysOrderItem.getPrice();
        SysProjUse puse = new SysProjUse();
        puse.setIsOver(Dictionary.DELETED_N);
        puse.setOrderItemId(sysOrderItem.getId());
        puse.setProjId(goodsAssemble.getAssembleGoodId());
        puse.setSurplusCount(goodsAssemble.getTotal() == null ? maxCount : goodsAssemble.getTotal());
        puse.setDeductionNum(goodsAssemble.getDeductionNum());
        puse.setProjName(goodsAssemble.getShoppingGoods().getName());
        puse.setVipId(order.getVipId());
        puse.setStatus(Dictionary.TAOCAN_STATUS_YX);
        puse.setTaocanId(taocanId);
        puse.setType(Dictionary.SHOPPING_GOODS_TYPE_XM);
        puse.setSource(source);
        if (taocanId == null) {
            puse.setPrice(goodsAssemble.getShoppingGoods().getPrice() * zk);
        } else {
            puse.setPrice(goodsAssemble.getPrice() * zk);
        }
        //赠送项目是否计算消耗业绩否则 赠送产品按原价计算消耗
        boolean zsConsumeAchieve = projServicesService.skipServiceOrderStep(Dictionary.ZS_CONSUME_ACHIEVE);
        if (zsConsumeAchieve) {
            if (sysOrderItem.getPrice() <= 0) {
                //等于0取原价
                if (taocanId == null) {
                    puse.setPrice(goodsAssemble.getShoppingGoods().getPrice());
                } else {
                    puse.setPrice(goodsAssemble.getPrice());
                }
            }
        } else {
            puse.setPrice(0D);
        }
        puse.setBalance(MoneyUtil.mul(puse.getPrice(), Double.valueOf(puse.getSurplusCount())));
        puse.setFailTime(failTime);
        sysProjUseDao.insert(puse);
        return puse;
    }
    private void createTaocanProjUse(SysOrder order, SysOrderItem sysOrderItem, ShoppingGoodsAssemble goodsAssemble) {
        //新建套餐
        SysProjUse taocanProjUse = new SysProjUse();
        ShoppingGoods taocanShoppingGoods = sysOrderItem.getShoppingGoods();
        Long projId = sysOrderItem.getGoodsId();
        if (goodsAssemble != null) {
            taocanShoppingGoods = shoppingGoodsDao.selectById(goodsAssemble.getAssembleGoodId());
            projId = goodsAssemble.getAssembleGoodId();
        }
        taocanProjUse.setProjId(projId);
        taocanProjUse.setIsOver(Dictionary.DELETED_N);
        taocanProjUse.setOrderItemId(sysOrderItem.getId());
        taocanProjUse.setProjName(taocanShoppingGoods.getName());
        taocanProjUse.setVipId(order.getVipId());
        taocanProjUse.setStatus(Dictionary.TAOCAN_STATUS_YX);
        taocanProjUse.setType(Dictionary.SHOPPING_GOODS_TYPE_TC);
        taocanProjUse.setIsCourse(taocanShoppingGoods.getIsCourse());
        taocanProjUse.setIsInfinite(taocanShoppingGoods.getIsInfinite());
        // 赠送和打折后金额为0的都视为赠送项目
        if (sysOrderItem.getIsFree().equals(Dictionary.FLAG_NO) && sysOrderItem.getZkPrice() > 0 && !isGiftMoneyPay(order)) {
            taocanProjUse.setSource(Dictionary.TAOCAN_SOURCE_GM);
        } else {
            taocanProjUse.setSource(Dictionary.TAOCAN_SOURCE_ZS);
        }
        // 失效时间
        Date invalidTime = shoppingGoodsService.calInvalidTime(taocanShoppingGoods, 1, null);
        taocanProjUse.setFailTime(invalidTime);
        sysProjUseDao.insert(taocanProjUse);
        //计划次数
        int surplusCount = 0;
        //总余额
        Double sumBanance = 0D;
        //创建套餐绑定的项目
        List<ShoppingGoodsAssemble> assembleList = shoppingGoodsAssembleDao.selectGoodsByShoppingGoodsIdAndType(projId, ShoppingGoods.SHOPPING_GOODS_TYPE_XM);
        for (ShoppingGoodsAssemble assemble : assembleList) {
            SysProjUse tempUse = createProjuseByAssemble(order, sysOrderItem, assemble, taocanProjUse.getId(), taocanProjUse.getFailTime(), taocanProjUse.getSource(), taocanShoppingGoods.getCarUseCount());
            sumBanance += tempUse.getBalance();
            surplusCount += tempUse.getSurplusCount();
        }
        if (Dictionary.FLAG_NO_N.equals(taocanShoppingGoods.getIsCourse())) {
            //固定套餐,剩余次数等于绑定项目的次数
            taocanProjUse.setSurplusCount(surplusCount);
            //合计套餐余额
            taocanProjUse.setBalance(sumBanance);
        } else {
            //任选套餐剩余次数等于最大使用次数
            taocanProjUse.setSurplusCount(taocanShoppingGoods.getCarUseCount());
            taocanProjUse.setBalance(sysOrderItem.getZkPrice());
        }
        sysProjUseDao.update(taocanProjUse);
    }
    @Autowired
    private SysProjServicesService projServicesService;
    /**
     * 根据订单创建用户项目使用情况
     *
     * @param order
     * @param sysOrderItem
     */
    private void createXmProjuse(SysOrder order, SysOrderItem sysOrderItem) {
        SysProjUse puse = new SysProjUse();
        puse.setIsOver(Dictionary.DELETED_N);
        puse.setOrderItemId(sysOrderItem.getId());
        puse.setProjId(sysOrderItem.getGoodsId());
        puse.setSurplusCount(sysOrderItem.getCount());
        puse.setVipId(order.getVipId());
        puse.setStatus(Dictionary.TAOCAN_STATUS_YX);
        puse.setType(Dictionary.SHOPPING_GOODS_TYPE_XM);
        puse.setProjName(sysOrderItem.getShoppingGoods().getName());
        // 赠送和打折后金额为0的都视为赠送项目
        if (sysOrderItem.getIsFree().equals(Dictionary.FLAG_NO) && sysOrderItem.getZkPrice() > 0 && !isGiftMoneyPay(order)) {
            puse.setSource(Dictionary.TAOCAN_SOURCE_GM);
            puse.setPrice(sysOrderItem.getZkPrice());
        } else {
            puse.setSource(Dictionary.TAOCAN_SOURCE_ZS);
            //赠送项目是否计算消耗业绩否则 赠送产品按原价计算消耗
            boolean zsConsumeAchieve = projServicesService.skipServiceOrderStep(Dictionary.ZS_CONSUME_ACHIEVE);
            if (zsConsumeAchieve) {
                //赠送情况下,如果收款金额大于0,就是赠送金额划扣的情况,金额即为划扣的折扣金额
                if (sysOrderItem.getZkPrice() > 0) {
                    puse.setPrice(sysOrderItem.getZkPrice());
                } else {
                    puse.setPrice(sysOrderItem.getShoppingGoods().getSealPice());
                }
            } else {
                puse.setPrice(0D);
            }
        }
        // 设置失效时间
        Date invalidTime = shoppingGoodsService.calInvalidTime(sysOrderItem.getShoppingGoods(), 1, null);
        puse.setFailTime(invalidTime);
        puse.setBalance(puse.getPrice() * puse.getSurplusCount());
        sysProjUseDao.insert(puse);
    }
    /**
     * 全是赠送金额,且配置了赠送金额购买计算为赠送
     *
     * @param order
     * @return
     */
    private boolean isGiftMoneyPay(SysOrder order) {
        BusParameterSettings giftiIsfree = busParameterSettingsDao.selectCompanyParamByCode(AppConstance.SHOP_MANAGE_GIFTISFREE, order.getCompanyId());
        if (giftiIsfree.getParamValue().equals("是")) {
            return order.getFlows().stream().allMatch(item -> SysOrderFlow.IS_GIFT_Y.equals(item.getIsGift())
                    && item.getAmount().doubleValue() > 0D);
        } else {
            return false;
        }
    }
    /**
     * 会员卡充值
     *
     * @param czVo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysOrder updateAddCardMoney(CzXkVo czVo) {
        SysUsers user = (SysUsers) WebUtil.getSession().getAttribute(MatrixConstance.LOGIN_KEY);
//        SysVipInfo vip = (SysVipInfo) WebUtil.getSession().getAttribute(SystemConstance.CURRENT_CUSTOMER);
//        czVo.setVipId(vip.getId());
        //更新会员会员卡金额
        MoneyCardUse cardUser = moneyCardUseDao.selectVipCard(czVo.getVipId());
        cardUser.setRealMoney(MoneyUtil.add(cardUser.getRealMoney(), czVo.getBjmoney()));
        cardUser.setGiftMoney(MoneyUtil.add(cardUser.getGiftMoney(), czVo.getGiftMoney()));
        moneyCardUseDao.update(cardUser);
        // 为会员新增积分
        SysVipInfo vipInfo = sysVipInfoDao.selectById(cardUser.getVipId());
        vipInfo.setPointAll(vipInfo.getPointAll() == null ? 0 : vipInfo.getPointAll() + czVo.getJf());
        sysVipInfoDao.update(vipInfo);
        // 新增一个充值订单
        SysOrder order = new SysOrder();
        order.setArrears(0D);
        order.setTotal(czVo.getBjmoney());
        order.setZkTotal(czVo.getBjmoney());
        order.setCashPay(czVo.getBjmoney());
        order.setShopId(user.getShopId());
        order.setOrderNo(codeService.getOrderCode());
        order.setVipId(czVo.getVipId());
        Date orderTime = new Date();
        if (StringUtils.isNotBlank(czVo.getDateTime())) {
            orderTime = DateUtil.stringToDateNew(czVo.getDateTime(), DateUtil.DATE_FORMAT_DD);
        }
        order.setOrderTime(orderTime);
        order.setPayTime(orderTime);
        order.setRemark(cardUser.getCardName());
        order.setStaffId(user.getSuId());
        order.setIsCross(2 + "");
        order.setOrderType(SysOrder.ORDER_TYPE_SEAL);
        order.setStatu(Dictionary.ORDER_STATU_YFK);
        order.setCompanyId(user.getCompanyId());
        sysOrderDao.insert(order);
        SysOrderItem orderItem = new SysOrderItem();
        orderItem.setOrderId(order.getId());
        orderItem.setOrderNo(order.getOrderNo());
        orderItem.setArrears(0D);
        ShoppingGoods shoppingGoods = shoppingGoodsDao.selectVipCzGoods();
        orderItem.setGoodsId(shoppingGoods.getId());
        orderItem.setPayMethod(Dictionary.PAY_TYPE_MOENY);
        orderItem.setCashPay(czVo.getBjmoney());
        orderItem.setZkPrice(czVo.getBjmoney());
        orderItem.setCardPay(0D);
        orderItem.setType(Dictionary.SHOPPING_GOODS_TYPE_CZK);
        orderItem.setCount(1);
        orderItem.setIsFree(Dictionary.FLAG_NO);
        orderItem.setPrice(czVo.getBjmoney());
        orderItem.setStatus(Dictionary.ORDER_STATU_YFK);
        orderItem.setAchieveList(czVo.getAchaeveList());
        orderItem.setShoppingGoods(shoppingGoods);
        orderItemDao.insert(orderItem);
        List<SysOrderItem> items = new ArrayList<>();
        items.add(orderItem);
        order.setItems(items);
        //设置卡项使用流水
        MoneyCardUseFlow moneyCardUseFlow = new MoneyCardUseFlow();
        moneyCardUseFlow.setTotal(czVo.getBjmoney());
        moneyCardUseFlow.setGiftMoney(czVo.getGiftMoney());
        moneyCardUseFlow.setCarUseId(czVo.getCardId());
        moneyCardUseFlow.setVipId(czVo.getVipId());
        moneyCardUseFlow.setType(MoneyCardUseFlow.USE_TYPE_CZ);
        moneyCardUseFlow.setOrderNo(order.getOrderNo());
        moneyCardUseFlow.setCreateTime(new Date());
        moneyCardUseFlow.setOperationId(user.getSuId());
        moneyCardUseFlow.setBalance(cardUser.getGiftMoney() + cardUser.getRealMoney());
        moneyCardUseFlow.setCarUseId(cardUser.getId());
        moneyCardUseFlowDao.insert(moneyCardUseFlow);
        order.setFlows(czVo.getFlows());
        addOrderFlow(order);
        // 添加员工业绩
        achieveNewService.addAchaeveByOrder(order);
        return order;
    }
    @Override
    public SysOrder findSysOrderTjByVipId(Long vipId) {
        return sysOrderDao.selectVipOrderInfoTotal(vipId);
    }
    @Override
    public List<OrderDetailVo> findApiOrderListInPage(OrderListDto orderListDto, PaginationVO pageVo) {
        return sysOrderDao.selectApiOrderListInPage(orderListDto, pageVo);
    }
    @Override
    public int findApiOrderListTotal(OrderListDto orderListDto) {
        return sysOrderDao.selectApiOrderListTotal(orderListDto);
    }
    @Override
    public OrderDetailVo findApiOrderDetailByOrderId(Long orderId) {
        OrderDetailVo orderDetail = sysOrderDao.selectApiOrderDetailById(orderId);
        if (orderDetail == null) {
            throw new GlobleException("该订单不存在");
        }
        List<OrderDetailItemVo> items = orderItemDao.selectApiOrderDetailItemsByOrderId(orderId);
        if (CollectionUtils.isNotEmpty(items)) {
            for (OrderDetailItemVo item : items) {
                List<OrderDetailAchieveItemVo> achieveItems = achieveNewDao.selectApiOrderItemAchieve(item.getId());
                item.setAchieves(achieveItems);
            }
        }
        orderDetail.setItems(items);
        return orderDetail;
    }
    @Override
    public List<RankingVo> findApiShopAchieveRanking(SysOrder sysOrder) {
        return sysOrderDao.selectShopAchieveRanking(sysOrder);
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void refundOrderMoney(SysOrder sysOrder) {
        SysUsers user = WebUtil.getSessionAttribute(MatrixConstance.LOGIN_KEY);
        //原订单设置为退款状态
        SysOrder sourceOrder = new SysOrder();
        sourceOrder.setId(sysOrder.getOldOrderId());
        sourceOrder.setIsHasRefund(SysOrder.IS_HAS_REFUND_Y);
//        sourceOrder.setStatu(Dictionary.ORDER_STATU_TK);
        sysOrderDao.update(sourceOrder);
        SysOrder oldOrder = sysOrderDao.selectById(sysOrder.getOldOrderId());
        sysOrder.setId(null);
        sysOrder.setStaffId(user.getSuId());
        sysOrder.setCompanyId(user.getCompanyId());
        sysOrder.setShopId(user.getShopId());
        sysOrder.setOrderType(SysOrder.ORDER_TYPE_REFUND);
        sysOrder.setStatu(Dictionary.ORDER_STATU_YFK);
        Date now = new Date();
        sysOrder.setOrderTime(now);
        sysOrder.setPayTime(now);
        sysOrder.setOrderNo(codeService.getRefundOrderNo());
        sysOrder.setZkTotal(-sysOrder.getZkTotal());
        //新增订单
        sysOrderDao.insert(sysOrder);
        //插入明细
        for (SysOrderItem item : sysOrder.getItems()) {
            //更新原订单明细的可退数量
            SysOrderItem oldItem = new SysOrderItem();
            oldItem.setId(item.getId());
            oldItem.setRefundCount(item.getCount());
            orderItemDao.update(oldItem);
            //插入新的订单明细
            item.setId(null);
            item.setCount(-item.getCount());
            item.setOrderId(sysOrder.getId());
            orderItemDao.insert(item);
        }
        // 添加订单收款流水
        addOrderFlow(sysOrder);
        //退款退套餐退项目
        refundProjUse(sysOrder);
        //删除积分
        scoreVipDetailService.removeByBusinessId(oldOrder.getVipId(), oldOrder.getId());
        // 设置业绩
        achieveNewService.addAchaeveByOrder(sysOrder);
        //保存单据日志
        operationLogService.saveOperation(sysOrder.getCompanyId(), sysOrder.getShopId(), user.getSuId(),
                OperationFunctionEnum.ORDER,
                OperationButtonEnum.ORDER_TK,
                sysOrder.getId(),
                sysOrder.getOrderNo(),
                sysOrder.getVipId());
    }
    private void addRefundOrderFlow(SysOrder sourceOrder) {
        //处理支付流水
        int flowCount = 1;
        for (SysOrderFlow flow : sourceOrder.getFlows()) {
            //支付内容摘要设置
            Long goodsId = sourceOrder.getItems().get(0).getGoodsId();
            ShoppingGoods goods = shoppingGoodsDao.selectById(goodsId);
            flow.setFlowContent(goods.getName() + "等" + sourceOrder.getItems().size() + "件产品");
            // 退款,则取负数
            flow.setFlowType(SysOrderFlow.FLOW_TYPE_REFUND);
            flow.setAmount(flow.getAmount().negate());
            flow.setOrderId(sourceOrder.getOldOrderId());
            //统计储值卡支付
            if (SysOrderFlow.PAY_METHOD_CARD.equals(flow.getPayMethod())) {
                if (flow.getCardId() != null) {
                    MoneyCardUse moneyCardUse = moneyCardUseDao.selectById(flow.getCardId());
                    //修改储值卡余额
                    cardPaySk(moneyCardUse, sourceOrder, flow);
                } else {
                    throw new GlobleException("无效的储值卡支付方式");
                }
            }
            flow.setFlowNo(codeService.getFlowCode() + "-" + flowCount);
            flow.setVipId(sourceOrder.getVipId());
            flow.setShopId(sourceOrder.getShopId());
            flow.setCompanyId(sourceOrder.getCompanyId());
            sysOrderFlowDao.insert(flow);
            flowCount++;
        }
    }
    private void refundCard(MoneyCardUse moneyCardUse, SysOrder sourceOrder, SysOrderFlow flow) {
        SysUsers user = (SysUsers) WebUtil.getSession().getAttribute(MatrixConstance.LOGIN_KEY);
        MoneyCardUseFlow moneyCardUseFlow = new MoneyCardUseFlow();
        if (SysOrderFlow.IS_GIFT_Y.equals(flow.getIsGift())) {
            if (moneyCardUse.getGiftMoney() >= flow.getAmount().doubleValue()) {
                double surplus = MoneyUtil.sub(moneyCardUse.getGiftMoney(), flow.getAmount().doubleValue());
                moneyCardUse.setGiftMoney(surplus);
                moneyCardUseFlow.setGiftMoney(0D - flow.getAmount().doubleValue());
            } else {
                throw new GlobleException(moneyCardUse.getCardName() + "余额不足");
            }
        } else {
            if (moneyCardUse.getRealMoney() >= flow.getAmount().doubleValue()) {
                double surplus = MoneyUtil.sub(moneyCardUse.getRealMoney(), flow.getAmount().doubleValue());
                moneyCardUse.setRealMoney(surplus);
                moneyCardUseFlow.setTotal(0 - flow.getAmount().doubleValue());
            } else {
                throw new GlobleException(moneyCardUse.getCardName() + "余额不足");
            }
        }
        if (moneyCardUse.getIsVipCar().equals(Dictionary.FLAG_NO_N)) {
            //余额为0时充值卡变为无效
            if (moneyCardUse.getRealMoney().equals(0D) && moneyCardUse.getGiftMoney().equals(0D)) {
                moneyCardUse.setIsOver(Dictionary.FLAG_YES_Y);
                moneyCardUse.setStatus(Dictionary.MONEYCARD_STATUS_WX);
            }
        }
        ShoppingGoods shoppingGoods = shoppingGoodsService.findById(moneyCardUse.getGoodsId());
        if (shoppingGoods != null) {
            Date invalidTime = shoppingGoodsService.calInvalidTime(shoppingGoods, 2, moneyCardUse.getFailTime());
            moneyCardUse.setFailTime(invalidTime);
        }
        // 更新充值卡信息
        moneyCardUseDao.update(moneyCardUse);
        //设置卡项使用流水
        moneyCardUseFlow.setCarUseId(moneyCardUse.getId());
        moneyCardUseFlow.setOrderNo(sourceOrder.getOrderNo());
        moneyCardUseFlow.setVipId(sourceOrder.getVipId());
        moneyCardUseFlow.setTimes(-1);
        moneyCardUseFlow.setType(MoneyCardUseFlow.USE_TYPE_CONSUMER);
        moneyCardUseFlow.setCreateTime(new Date());
        moneyCardUseFlow.setOperationId(user.getSuId());
        moneyCardUseFlow.setBalance(moneyCardUse.getGiftMoney() + moneyCardUse.getRealMoney());
        moneyCardUseFlowDao.insert(moneyCardUseFlow);
    }
    /**
     * 退款退项目,套餐,卡项
     *
     * @param sysOrder
     */
    private void refundProjUse(SysOrder sysOrder) {
        SysUsers user = WebUtil.getSessionAttribute(MatrixConstance.LOGIN_KEY);
        //记录需要退库存的产品
        List<SysOrderItem> returnGoodsList = new ArrayList<>();
        for (SysOrderItem item : sysOrder.getItems()) {
            SysProjUse queryProjUse = new SysProjUse();
            queryProjUse.setOrderItemId(item.getOldItemId());
            // 修改项目信息
            if (Dictionary.SHOPPING_GOODS_TYPE_XM.equals(item.getType()) || Dictionary.SHOPPING_GOODS_TYPE_JJCP.equals(item.getType())) {
                if (Dictionary.SHOPPING_GOODS_TYPE_JJCP.equals(item.getType())) {
                    if (Dictionary.FLAG_YES_Y.equals(item.getIsReturnStore())) {
                        returnGoodsList.add(item);
                    }
                } else {
                    SysProjUse sysProjUse = sysProjUseDao.selectByModel(queryProjUse).get(0);
                    int sub = sysProjUse.getSurplusCount() - item.getCount();
                    if (sub < 0) {
                        throw new GlobleException("项目余次不足");
                    } else if (sub == 0) {
                        sysProjUse.setIsOver(Dictionary.FLAG_YES_Y);
                        sysProjUse.setStatus(Dictionary.TAOCAN_STATUS_WX);
                    }
                    sysProjUse.setSurplusCount(sub);
                    sysProjUseDao.update(sysProjUse);
                    SysProjUseFlow sysProjUseFlow = SysProjUseMapper.INSTANCE.projUseToFlow(sysProjUse);
                    sysProjUseFlow.setOptionType("退款修改");
                    sysProjUseFlow.setId(null);
                    sysProjUseFlow.setUpdateBy(user.getSuName());
                    sysProjUseFlow.setCreateBy(user.getSuName());
                    sysProjUseDao.insertFlow(sysProjUseFlow);
                }
            }
            if (Dictionary.SHOPPING_GOODS_TYPE_TC.equals(item.getType())) {
                queryProjUse.setTaocanId(-1L);
                List<SysProjUse> sysProjUses = sysProjUseDao.selectByModel(queryProjUse);
                for (int i = 0; i < sysProjUses.size(); i++) {
                    SysProjUse sysProjUse = sysProjUses.get(i);
                    sysProjUse.setIsOver(Dictionary.FLAG_YES_Y);
                    sysProjUse.setStatus(Dictionary.TAOCAN_STATUS_WX);
                    sysProjUseDao.update(sysProjUse);
                    SysProjUseFlow sysProjUseFlow = SysProjUseMapper.INSTANCE.projUseToFlow(sysProjUse);
                    sysProjUseFlow.setOptionType("退款修改");
                    sysProjUseFlow.setId(null);
                    sysProjUseFlow.setUpdateBy(user.getSuName());
                    sysProjUseFlow.setCreateBy(user.getSuName());
                    sysProjUseDao.insertFlow(sysProjUseFlow);
                }
            }
            if (Dictionary.SHOPPING_GOODS_TYPE_CZK.equals(item.getType())) {
                MoneyCardUse queryCardUse = new MoneyCardUse();
                queryCardUse.setStatus(Dictionary.TAOCAN_STATUS_YX);
                queryCardUse.setOrderItemId(item.getOldItemId());
                List<MoneyCardUse> moneyCardUses = moneyCardUseDao.selectByModel(queryCardUse);
                for (int i = 0; i < item.getCount(); i++) {
                    MoneyCardUse moneyCardUse = moneyCardUses.get(i);
                    moneyCardUse.setIsOver(Dictionary.FLAG_YES_Y);
                    moneyCardUse.setStatus(Dictionary.MONEYCARD_STATUS_WX);
                    moneyCardUseDao.update(moneyCardUse);
                }
            }
            // TODO 综合卡退款
            if (Dictionary.SHOPPING_GOODS_TYPE_ZHK.equals(item.getType())) {
            }
            ShoppingGoods goods = shoppingGoodsDao.selectById(item.getGoodsId());
            goods.setRealSealCount(goods.getRealSealCount() - item.getCount());
            shoppingGoodsDao.update(goods);
        }
        BusParameterSettings manageStockSetting = busParameterSettingsDao.selectCompanyParamByCode(AppConstance.WAREHOUSE_MANAGE_STOCK, sysOrder.getCompanyId());
        if (AppConstance.IS_Y.equals(manageStockSetting.getParamValue())) {
            // 家居产品退库存
            if (CollectionUtils.isNotEmpty(returnGoodsList)) {
                refundInstore(returnGoodsList);
            }
        }
    }
    /**
     * 退款入库
     */
    private void refundInstore(@NotEmpty List<SysOrderItem> items) {
        SysUsers user = WebUtil.getSessionAttribute(MatrixConstance.LOGIN_KEY);
        SysSupplierInfo supplierInfo = new SysSupplierInfo();
        supplierInfo.setShopId(user.getShopId());
        supplierInfo = sysSupplierInfoDao.selectByModel(supplierInfo).get(0);
        Warehouse warehouse = warehouseDao.findShopWarehouse(user.getShopId()).get(0);
        SysInstoreInfo instoreInfo = new SysInstoreInfo();
        instoreInfo.setInstoreType(SysInstoreInfo.INSTORE_TYPE_RETURN);
        instoreInfo.setInstoreDate(new Date());
        instoreInfo.setSupplierId(supplierInfo.getId().toString());
        instoreInfo.setStoreId(warehouse.getId());
        instoreInfo.setCheckStatus(Dictionary.CHECK_STATUS_DSH);
        // 设置入库单编号
        instoreInfo.setInstoreId(DateUtil.getTimeMark());
        instoreInfo.setShopId(user.getShopId());
        instoreInfo.setCompanyId(user.getCompanyId());
        sysInstoreInfoDao.insert(instoreInfo);
        Double total = 0.0;
        List<SysInstoreDetail> instoreDetails = new ArrayList<>();
        for (SysOrderItem item : items) {
            ShoppingGoods goods = shoppingGoodsDao.selectById(item.getGoodsId());
            SysInstoreDetail sysInstoreDetail = new SysInstoreDetail();
            sysInstoreDetail.setAmount(item.getCount().doubleValue());
            sysInstoreDetail.setPrice(item.getZkPrice());
            sysInstoreDetail.setSkuId(goods.getId());
            total = MoneyUtil.add(MoneyUtil.mul(Double.parseDouble(sysInstoreDetail.getAmount() + ""), sysInstoreDetail.getPrice()), total);
            sysInstoreDetail.setInstoreId(instoreInfo.getId());
            // 设置小计
            sysInstoreDetail.setPriceTotal(MoneyUtil.mul(Double.parseDouble(sysInstoreDetail.getAmount() + ""), sysInstoreDetail.getPrice()));
            instoreDetails.add(sysInstoreDetail);
        }
        instoreInfo.setSumall(total);
        sysInstoreInfoDao.update(instoreInfo);
        sysInstoreDetailDao.batchInsert(instoreDetails);
        sysInstoreInfoService.check(instoreInfo);
    }
    @Override
    public BigDecimal findVipArrearsByVipId(Long vipId) {
        return sysOrderDao.selectArrearsByVipId(vipId);
    }
}