package com.kmall.admin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.Maps;
import com.kmall.admin.dao.*;
import com.kmall.admin.dao.mk.store.MkStorePromOrderRealDao;
import com.kmall.admin.dto.GoodsDto;
import com.kmall.admin.dto.OrderExpressDto;
import com.kmall.admin.dto.OrderRecognitionDto;
import com.kmall.admin.entity.*;
import com.kmall.admin.entity.OrderProcessRecordEntity;
import com.kmall.admin.entity.mk.store.MkStorePromOrderRealEntity;
import com.kmall.admin.fromcomm.dao.SysConfigDao;
import com.kmall.admin.service.*;
import com.kmall.admin.websocket.WebSocketServer;
import com.kmall.api.dto.CampMinusDto;
import com.kmall.api.entity.*;
import com.kmall.api.entity.mk.MkStoreCampMinusVo;
import com.kmall.api.entity.mk.MkStoreTicketDiscountVo;
import com.kmall.common.utils.ResponseData;
import com.kmall.common.utils.wechat.WechatMicropayApiResult;
import com.kmall.common.utils.wechat.WechatReverseApiResult;
import com.kmall.manager.manager.express.sf.properties.SFPropertiesBuilder;
import com.kmall.manager.manager.express.sf.properties.SFUtil;
import com.kmall.manager.manager.express.sf.entity.SfRouteServiceResponseEntity;
import com.kmall.manager.manager.express.sf.entity.RouteEntity;
import com.kmall.manager.manager.express.sf.entity.RouteResponseEntity;
import com.kmall.manager.manager.print.ticket.TicketPrintUtil;
import com.kmall.manager.manager.wechat.WechatUtil;
import com.kmall.manager.manager.wechat.wxglobal.dto.WechatGlobalRefundApiResult;
import com.kmall.admin.utils.ShiroUtils;
import com.kmall.common.constant.Dict;
import com.kmall.manager.manager.merch.OmsMerchPropertiesBuilder;
import com.kmall.api.util.CommonUtil;
import com.kmall.admin.fromcomm.entity.SysUserEntity;
import com.kmall.manager.manager.print.ticket.PrintTicketPropertiesBuilder;
import com.kmall.common.utils.*;
import com.kmall.common.utils.print.ticket.item.*;
import com.kmall.manager.manager.express.kdn.KdniaoUtil;
import com.kmall.common.utils.wechat.WechatRefundApiResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Service("orderService")
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private ShippingDao shippingDao;
    @Autowired
    private OrderGoodsDao orderGoodsDao;
    @Autowired
    private SysPrinterDao printerDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserCouponDao userCouponDao;
    @Autowired
    private ProductStoreRelaDao productStoreRelaDao;
    @Autowired
    private OrderProcessRecordDao orderProcessRecordDao;
    @Autowired
    private OrderRefundDao orderRefundDao;
    @Autowired
    private StoreDao storeDao;
    @Autowired
    private OfflineCartDao offlineCartDao;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private MerchDao merchDao;
    @Autowired
    private MngChangeDao mngChangeDao;
    @Autowired
    private StoreMngChangeDao storeMngChangeDao;
    @Autowired
    private ThirdMerchExpressDao thirdMerchExpressDao;
    @Autowired
    private MkStorePromOrderRealDao mkStorePromOrderRealDao;
    @Autowired
    private UserCampMinusDao userCampMinusDao;
    @Autowired
    private UserService userService;
    @Autowired
    private SysConfigDao sysConfigDao;
    @Autowired
    private ProductDao productDao;

    @Autowired
    private OrderWXPayRecordService orderWXPayRecordService;
    @Autowired
    private StoreService storeService;
    @Autowired
    private PickUpCodeService pickUpCodeService;

    @Override
    public OrderEntity queryObject(Long id) {
        return orderDao.queryObject(id);
    }

    @Override
    public Double getTotalActualPrice(String merchOrderSn) {
        return orderDao.getTotalActualPrice(merchOrderSn);
    }

    @Override
    public List<OrderEntity> queryList(Map<String, Object> map) {
        return orderDao.queryList(map);
    }

    @Override
    public int queryTotal(Map<String, Object> map) {
        return orderDao.queryTotal(map);
    }

    @Override
    public int save(OrderEntity order) {
        return orderDao.save(order);
    }

    @Override
    public int update(OrderEntity order) {
        return orderDao.update(order);
    }

    /**
     * 取消订单
     *
     * @param order
     */
    @Override
    public void cancelOrder(OrderEntity order) {
        boolean needUpdateStock = true;
        if (order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_0.getItem())) {
            order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_101.getItem()));
        }
        orderDao.update(order);
        if (!needUpdateStock) {
            return;
        }
        // 更新库存
        updateStock(order, "管理后台取消订单");
        // 释放优惠券
        UserCouponEntity couponVo = userCouponDao.queryByOrderId(order.getId());
        if (null != couponVo) {
            userCouponDao.cancelOrder(couponVo);
        }
        //释放促销满减券
        UserCampMinusEntity userCampMinusVo = userCampMinusDao.queryUserCampByOrderId(order.getId());
        if (null != userCampMinusVo) {
            userCampMinusDao.cancelUserCampOrder(userCampMinusVo);
        }
    }

    @Override
    public int delete(Long id) {
        return orderDao.delete(id);
    }

    @Override
    public int deleteBatch(Long[] ids) {
        return orderDao.deleteBatch(ids);
    }

    @Override
    public int confirm(Long id) {
        OrderEntity orderEntity = queryObject(id);
        Integer shippingStatus = orderEntity.getShippingStatus();//发货状态
        Integer payStatus = orderEntity.getPayStatus();//付款状态
        if (2 != payStatus) {
            throw new RRException("此订单未付款，不能确认收货！");
        }
        if (4 == shippingStatus) {
            throw new RRException("此订单处于退货状态，不能确认收货！");
        }
        if (0 == shippingStatus) {
            throw new RRException("此订单未发货，不能确认收货！");
        }
        if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_301.getItem())) {
            throw new RRException("此订单已完成！");
        }
        if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_0.getItem())) {
            throw new RRException("此订单待付款！");
        }
        if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_100.getItem())) {
            throw new RRException("此订单付款中！");
        }
        if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_101.getItem())) {
            throw new RRException("此订单已取消！");
        }
        if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_102.getItem())) {
            throw new RRException("此订单已删除！");
        }
        if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) {
            throw new RRException("此订单还未发货！");
        }
        if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_401.getItem())) {
            throw new RRException("此订单已退款！");
        }
        if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_402.getItem())) {
            throw new RRException("此订单已退款！");
        }
        orderEntity.setShippingStatus(2);
        orderEntity.setOrderStatus(301);
        orderEntity.setConfirmTime(new Date());
        orderDao.update(orderEntity);
        return 0;
    }

    @Override
    public int sendGoods(OrderEntity order) {
        Integer payStatus = order.getPayStatus();//付款状态
        if (2 != payStatus) {
            throw new RRException("此订单未付款！");
        }

        ShippingEntity shippingEntity = shippingDao.queryObject(order.getShippingId());
        if (null != shippingEntity) {
            order.setShippingName(shippingEntity.getName());
        }
        order.setOrderStatus(300);//订单已发货
        order.setShippingStatus(1);//已发货
        return orderDao.update(order);
    }

    @Override
    public Ticket printMsg(Long id) {
        OrderEntity orderEntity = queryInfos(id);
        List<OrderGoodsEntity> orderGoodsEntityList = orderEntity.getOrderGoodsEntityList();
        // 获取门店
        StoreEntity storeEntity = storeDao.queryObject(orderEntity.getStoreId());
        // 获取清关信息
        OrderProcessRecordEntity orderProcessRecordEntity =
                orderProcessRecordDao.queryObjectByOrderSn(orderEntity.getOrderSn());

        // 小票头
        TicketHead head = new TicketHead();
        head.setTitle(OmsMerchPropertiesBuilder.instance().getMerchName() + storeEntity.getStoreName());
        //        head.setMemberId(orderEntity.getUserName().toString());
        head.setOrderId(orderEntity.getOrderSn());
        head.setTradeTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss EEE").format(new Date()));

        // 商品信息
        Integer goodsTotal = 0; // 商品总个数
        BigDecimal total = Constant.ZERO; // 商品总计
        List<Goods> goodsList = new ArrayList<>();
        for (OrderGoodsEntity orderGoods : orderGoodsEntityList) {
            goodsTotal += orderGoods.getNumber();
            total = total.add(orderGoods.getRetailPrice().multiply(new BigDecimal(orderGoods.getNumber())))
                         .setScale(2, BigDecimal.ROUND_HALF_UP);
            Goods goods = new Goods(orderGoods.getGoodsName(), orderGoods.getRetailPrice().toString(),
                                    orderGoods.getNumber().toString(),
                                    orderGoods.getRetailPrice().multiply(new BigDecimal(orderGoods.getNumber()))
                                              .setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            goodsList.add(goods);
        }

        // 收银信息
        CashInfo cashInfo = new CashInfo();
        cashInfo.setGoodsTotal(goodsTotal.toString());
        cashInfo.setTotal(total.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        cashInfo.setReceipts(orderEntity.getActualPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        cashInfo.setOddChange("0.00");
        cashInfo.setCoupon(orderEntity.getCouponPrice().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        cashInfo.setFreight(
                new BigDecimal(orderEntity.getFreightPrice()).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        cashInfo.setPaymentMode("微信支付");

        // 海关清单
        CusListing cusListing = new CusListing();
        cusListing.setOrderId(orderEntity.getOrderSn());
        if (!orderEntity.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_11.getItem())) {
            cusListing.setWaybillId(orderProcessRecordEntity.getLogisticsNo());
            cusListing.setInvtNo(orderProcessRecordEntity.getInvtNo());
            cusListing.setConsignee(orderEntity.getConsignee());
            cusListing.setConsigneeTel(orderEntity.getMobile());
        }
        cusListing.setOriginAddress(PrintTicketPropertiesBuilder.instance().getAddress());
        cusListing.setDeliveryAddress(storeEntity.getStoreAddress());

        return TicketPrintUtil.print(head, goodsList, cashInfo, cusListing);
    }

    /**
     * 退款
     */
    @Transactional
    public void refund(OrderEntity order, WechatRefundApiResult result) {
        boolean needUpdateStock = true;
        if (order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) {
            order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_401.getItem()));
        }
        if (Dict.payFlag.item_cash.getItem().equals(order.getPayFlag())) {
            order.setPayStatus(Integer.parseInt(Dict.payStatus.item_4.getItem()));
        }else{
            order.setPayStatus(Integer.parseInt(Dict.payStatus.item_3.getItem()));
            OrderRefundEntity mallOrderRefund = orderRefundDao.queryObjectByOrderId(order.getId());
            OrderRefundEntity orderRefund = new OrderRefundEntity();
            orderRefund.setRefundId(result.getRefund_id());
            orderRefund.setOutRefundNo(result.getOut_refund_no());
            orderRefund
                    .setRefundMoney(BigDecimal.valueOf(Long.valueOf(result.getRefund_fee())).divide(Constant.ONE_HUNDRED));
            orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_5.getItem()));//退款处理中
            orderRefund.setModTime(new Date());

            if (mallOrderRefund != null) {
                orderRefund.setId(mallOrderRefund.getId());
                orderRefund.setRefundType(mallOrderRefund.getRefundType());
                orderRefundDao.update(orderRefund);
            } else {
                orderRefund.setOrderId(Integer.parseInt(order.getId() + ""));
                orderRefund.setUserId(Integer.parseInt(order.getUserId() + ""));
                orderRefund.setCreateTime(new Date());
                List<OrderEntity> list = orderDao.queryObjectByMerchOrderSn(order.getMerchOrderSn());
                if(list.size()>1){//多条订单
                    orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_2.getItem()));//部分退款
                }else{
                    orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_1.getItem()));//用户全额退款
                }
                orderRefundDao.save(orderRefund);//退款记录
            }
        }
        orderDao.update(order);//修改为退款中
        // TODO: 2019/6/13 定时任务查询退款成功后释放库存、优惠券
        /*// 判断是否有优惠券
        UserCouponEntity couponVo = userCouponDao.queryByOrderId(order.getId());
        if (null != couponVo) {
            userCouponDao.cancelOrder(couponVo);
        }

        if (!needUpdateStock) {
            return;
        }
        // 更新库存
        updateStock(order, "管理后台订单退款");*/

        queryStorePromRealUpdateIsScan(order);
    }

    /**
     * 平安退款逻辑处理
     * @param order
     * @param result
     */
    @Transactional
    public void pinganRefund(OrderEntity order, net.sf.json.JSONObject result, String refundId) {
        boolean needUpdateStock = true;
        if (order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) {
            order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_401.getItem()));
        }
        order.setPayStatus(Integer.parseInt(Dict.payStatus.item_3.getItem()));
        OrderRefundEntity orderRefund = new OrderRefundEntity();
        orderRefund.setRefundId(refundId);
        orderRefund.setOutRefundNo(result.getString("ord_no"));
        orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_5.getItem()));//退款处理中
        orderRefund.setModTime(new Date());
        orderRefund.setRefundMoney(BigDecimal.valueOf(result.getInt("trade_amount")).divide(Constant.ONE_HUNDRED));

        OrderRefundEntity mallOrderRefund = orderRefundDao.queryObjectByOrderId(order.getId());
        if (mallOrderRefund != null) {
            orderRefund.setRefundType(mallOrderRefund.getRefundType());
            orderRefund.setId(mallOrderRefund.getId());
            orderRefundDao.update(orderRefund);
        } else {//退款记录不存在
            orderRefund.setOrderId(Integer.parseInt(order.getId() + ""));
            orderRefund.setUserId(Integer.parseInt(order.getUserId() + ""));
            orderRefund.setCreateTime(new Date());
            orderRefundDao.save(orderRefund);//退款记录
        }
        orderDao.update(order);//修改为退款中
        // TODO: 2019/6/13 定时任务查询退款成功后释放库存、优惠券
        /*// 判断是否有优惠券
        UserCouponEntity couponVo = userCouponDao.queryByOrderId(order.getId());
        if (null != couponVo) {
            userCouponDao.cancelOrder(couponVo);
        }

        if (!needUpdateStock) {
            return;
        }
        // 更新库存
        updateStock(order, "管理后台平安退款订单");*/

        queryStorePromRealUpdateIsScan(order);
    }

    /**
     * 微信国际退款逻辑处理
     * @param order
     * @param result
     */
    @Transactional
    public void globalRefund(OrderEntity order, WechatGlobalRefundApiResult result) {
        boolean needUpdateStock = true;
        if (order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) {
            order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_401.getItem()));
        }
        order.setPayStatus(Integer.parseInt(Dict.payStatus.item_3.getItem()));
        OrderRefundEntity orderRefund = new OrderRefundEntity();
        orderRefund.setRefundId(result.getRefund_id());
        orderRefund.setOutRefundNo(result.getOut_refund_no());
        orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_5.getItem()));//退款处理中
        orderRefund.setModTime(new Date());
        orderRefund.setRefundMoney(BigDecimal.valueOf(Long.valueOf(result.getRefund_fee())).divide(Constant.ONE_HUNDRED));
        orderRefund.setRefundFeeType(result.getRefund_fee_type());
        if(org.apache.commons.lang3.StringUtils.isNotEmpty(result.getTotal_fee())) {
            orderRefund.setTotalFee(Integer.parseInt(BigDecimal.valueOf(Long.valueOf(result.getTotal_fee())).divide(Constant.ONE_HUNDRED).toString()));
        }
        orderRefund.setFeeType(result.getFee_type());
        if(org.apache.commons.lang3.StringUtils.isNotEmpty(result.getCash_fee())) {
            orderRefund.setCashFee(Integer.parseInt(BigDecimal.valueOf(Long.valueOf(result.getCash_fee())).divide(Constant.ONE_HUNDRED).toString()));
        }
        orderRefund.setCashFeeType(result.getCash_fee_type());
        if(org.apache.commons.lang3.StringUtils.isNotEmpty(result.getCash_refund_fee())) {
            orderRefund.setCashRefundFee(Integer.parseInt(BigDecimal.valueOf(Long.valueOf(result.getCash_refund_fee())).divide(Constant.ONE_HUNDRED).toString()));
        }
        orderRefund.setCashRefundFeeType(result.getCash_refund_fee_type());

        OrderRefundEntity mallOrderRefund = orderRefundDao.queryObjectByOrderId(order.getId());
        if (mallOrderRefund != null) {
            orderRefund.setRefundType(mallOrderRefund.getRefundType());
            orderRefund.setId(mallOrderRefund.getId());
            orderRefundDao.update(orderRefund);
        } else {//退款记录不存在
            orderRefund.setOrderId(Integer.parseInt(order.getId() + ""));
            orderRefund.setUserId(Integer.parseInt(order.getUserId() + ""));
            orderRefund.setCreateTime(new Date());
            orderRefundDao.save(orderRefund);//退款记录
        }
        orderDao.update(order);//修改为退款中
        // TODO: 2019/6/13 定时任务查询退款成功后释放库存、优惠券
        /*// 判断是否有优惠券
        UserCouponEntity couponVo = userCouponDao.queryByOrderId(order.getId());
        if (null != couponVo) {
            userCouponDao.cancelOrder(couponVo);
        }

        if (!needUpdateStock) {
            return;
        }
        // 更新库存
        updateStock(order, "管理后台微信国际退款订单");*/

        queryStorePromRealUpdateIsScan(order);
    }

    private void updateStock(OrderEntity order, String changeReason){
        Map<String, Object> map = new HashMap();
        SysUserEntity user = ShiroUtils.getUserEntity();
        map.put("orderId", order.getId());
        List<OrderGoodsEntity> orderGoodsVoList = orderGoodsDao.queryList(map);
        for (OrderGoodsEntity orderGoodsEntity : orderGoodsVoList) {
            ProductStoreRelaEntity storeRelaEntity = productStoreRelaDao
                    .queryByStoreIdProductId(Long.valueOf(order.getStoreId()),Long.valueOf(orderGoodsEntity.getProductId()));
            if (null == storeRelaEntity || null == storeRelaEntity.getSellVolume()) {
                storeRelaEntity.setSellVolume(0);
            }
            BigDecimal sellVolume = new BigDecimal(storeRelaEntity.getSellVolume() - orderGoodsEntity.getNumber());//销售量
            if (sellVolume.compareTo(Constant.ZERO) < 0) {
                sellVolume = Constant.ZERO;
            }

            Integer stockNum = 0;
            GoodsEntity goodsEntity = goodsDao.queryObject(orderGoodsEntity.getGoodsId());
            if(goodsEntity != null){
                stockNum = goodsEntity.getGoodsNumber();
                //还原商户商品库存
                resetGoodsStock(stockNum, storeRelaEntity, orderGoodsEntity, sellVolume, changeReason, user);
            }
            if (null != storeRelaEntity.getStockNum()) {
                stockNum = storeRelaEntity.getStockNum();
                //普通商品不受共享库存影响，直接取门店配置库存
                //该商品所属第三方商户不是共享库存
                if(goodsEntity.getIsStockShare().equalsIgnoreCase(Dict.isStockShare.item_0.getItem())) {
                    resetStoreGoodsStock(stockNum, storeRelaEntity, orderGoodsEntity, sellVolume, changeReason, user);//还原门店库存
                }else{
                    //该商品所属第三方商户是共享库存，但商品业务类型不是00保税备货
                    if(!goodsEntity.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_00.getItem())){
                        resetStoreGoodsStock(stockNum, storeRelaEntity, orderGoodsEntity, sellVolume, changeReason, user);//还原门店库存
                    }
                }
            }
            //该商品所属第三方商户为共享库存，且是保税备货商品，取消订单时改变
            updateGoodsByIsShareStock(goodsEntity);
        }
    }

    /**
     * 更新商品库存数量变化后是否已共享为0“未共享”
     * @param goodsInfo
     */
    private void updateGoodsByIsShareStock(GoodsEntity goodsInfo){
        //该商品所属第三方商户为共享库存，且是保税备货商品
        if(goodsInfo.getIsStockShare().equalsIgnoreCase(Dict.isStockShare.item_1.getItem())
                && goodsInfo.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_00.getItem())) {
            GoodsEntity goodsVo = new GoodsEntity();
            goodsVo.setId(goodsInfo.getId());
            //商品库存数量变化后是否已共享,0：否，1：是(下单、退款、取消订单触发)
            goodsVo.setIsGoodsShareStock(Dict.isGoodsShareStock.item_0.getItem());
            goodsDao.update(goodsVo);
        }
    }
    /**
     * 还原商品总库存
     * @param stockNum
     * @param storeRelaEntity
     * @param orderGoodsEntity
     * @param sellVolume
     * @param changeReason
     * @param user
     */
    private void resetGoodsStock(Integer stockNum, ProductStoreRelaEntity storeRelaEntity,
                                 OrderGoodsEntity orderGoodsEntity, BigDecimal sellVolume, String changeReason, SysUserEntity user){
        GoodsEntity goodsEntity = goodsDao.queryObject(storeRelaEntity.getGoodsId());
        if(goodsEntity!=null){
            goodsEntity.setGoodsNumber(stockNum + orderGoodsEntity.getNumber());
//                        goodsEntity.setSellVolume(Integer.parseInt(goodsSellVolume.toString()));
            goodsDao.update(goodsEntity);

//            storeRelaEntity.setSellVolume(Integer.parseInt(sellVolume.toString()));
//            productStoreRelaDao.update(storeRelaEntity);

            MngChangeEntity mngChangeEntity = new MngChangeEntity();
            mngChangeEntity.setGoodsId(Integer.parseInt(String.valueOf(goodsEntity.getId())));
            mngChangeEntity.setThirdPartyMerchCode(goodsEntity.getThirdPartyMerchCode());
            mngChangeEntity.setChangeReason(changeReason);
            mngChangeEntity.setChangeType(Dict.changeType.item_0.getItem());
            mngChangeEntity.setChangeNum(orderGoodsEntity.getNumber());//变化数
            mngChangeEntity.setOriginalNum(stockNum);//原库存数
            mngChangeEntity.setValidNum(stockNum + orderGoodsEntity.getNumber());//可用数
            mngChangeEntity.setCreateTime(new Date());
            mngChangeEntity.setModTime(new Date());
            mngChangeEntity.setCreaterSn(user.getUsername());
            mngChangeEntity.setModerSn(user.getUsername());
            mngChangeEntity.setIsValid(0);
            mngChangeEntity.setMerchSn(goodsEntity.getMerchSn());
            mngChangeDao.save(mngChangeEntity);
        }
    }

    /**
     * 还原门店商品库存
     * @param stockNum
     * @param storeRelaEntity
     * @param orderGoodsEntity
     * @param sellVolume
     * @param changeReason
     * @param user
     */
    private void resetStoreGoodsStock(Integer stockNum, ProductStoreRelaEntity storeRelaEntity,
                                 OrderGoodsEntity orderGoodsEntity, BigDecimal sellVolume, String changeReason, SysUserEntity user){
        storeRelaEntity.setSellVolume(Integer.parseInt(sellVolume.toString()));
        storeRelaEntity.setStockNum(stockNum + orderGoodsEntity.getNumber());//库存数量
        productStoreRelaDao.update(storeRelaEntity);

        StoreMngChangeEntity storeMngChangeEntity = new StoreMngChangeEntity();
        storeMngChangeEntity.setChangeType(Dict.changeType.item_0.getItem());
        storeMngChangeEntity.setChangeReason(changeReason);
        storeMngChangeEntity.setGoodsId(Integer.parseInt(String.valueOf(storeRelaEntity.getGoodsId())));
        storeMngChangeEntity.setStoreId(Integer.parseInt(String.valueOf(storeRelaEntity.getStoreId())));
        storeMngChangeEntity.setMerchSn(storeRelaEntity.getMerchSn());
        storeMngChangeEntity.setStoreChangeNum(orderGoodsEntity.getNumber());
        storeMngChangeEntity.setStoreOriginalNum(stockNum);
        storeMngChangeEntity.setStoreValidNum(stockNum + orderGoodsEntity.getNumber());
        storeMngChangeEntity.setCreateTime(new Date());
        storeMngChangeEntity.setModTime(new Date());
        storeMngChangeEntity.setCreaterSn(user.getUsername());
        storeMngChangeEntity.setModerSn(user.getUsername());
        storeMngChangeEntity.setIsValid(0);
        storeMngChangeDao.save(storeMngChangeEntity);
    }

    /**
     * 查询该退款订单编号是否是推广渠道订单，是则修改渠道定时扫描状态
     * @param orderInfo
     */
    private void queryStorePromRealUpdateIsScan(OrderEntity orderInfo){
        Map map = new HashMap();
        map.put("orderId", orderInfo.getId());
        List<MkStorePromOrderRealEntity> list = mkStorePromOrderRealDao.queryPromRealListByMap(map);
        if(list.size() > 0) {
            for (MkStorePromOrderRealEntity mkStorePromOrderRealEntity : list) {
                mkStorePromOrderRealEntity.setIsPromStatScan(Dict.isDistSellScan.item_0.getItem());
                mkStorePromOrderRealDao.update(mkStorePromOrderRealEntity);
            }
        }
    }

    /**
     * 处理用户退款申请
     *
     * @param orderInfo
     */
    @Transactional
    public void applyRefundDeal(OrderEntity orderInfo, OrderRefundEntity refundEntity) {
        refundEntity.setApprovalTime(new Date());
        //        refundEntity.setApprover(ShiroUtils.getUserId());
        //  退积分
        try {
            Integer integral = 1;
            if (orderInfo.getActualPrice().intValue() > 0) {
                integral = orderInfo.getActualPrice().intValue();
            }
            if (refundEntity.getRefundStatus() == 2) {
                orderInfo.setOrderStatus(401);
//                UserEntity entity = userDao.queryObject(orderInfo.getUserId());
            } else {
                orderInfo.setOrderStatus(201);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        orderRefundDao.update(refundEntity);
        orderDao.update(orderInfo);
    }

    @Override
    public OrderRefundEntity queryRefundObject(Long refundId) {
        return orderRefundDao.queryObject(refundId);
    }

    @Override
    public List<OrderRefundEntity> queryRefundList(Map<String, Object> map) {
        return orderRefundDao.queryList(map);
    }

    @Override
    public int queryRefundTotal(Map<String, Object> map) {
        return orderRefundDao.queryTotal(map);
    }

    @Override
    public int getUserOrderInfo(Map<String, Object> map) {
        int result = 0;
        String type = (String) map.get("type");
        if ("yfkOrderUserSum".equals(type)) {
            result = orderDao.getYfkOrderUserSum(map);
        } else if ("oderUserSum".equals(type)) {
            result = orderDao.getOderUserSum(map);
        } else if ("todayUserOrder".equals(type)) {
            result = orderDao.getTodayUserOrder(map);
        } else if ("todayUserSales".equals(type)) {
            result = orderDao.getTodayUserSales(map);
        } else if ("incomeSum".equals(type)) {
            result = orderDao.getIncomeSum(map);
        } else if ("payedOrderCount".equals(type)) {
            result = orderDao.getPayedOrderCount(map);
        }
        return result;
    }

    @Override
    public Map getLogistics(Long id) {
        OrderEntity orderEntity = queryObject(id);
        if (orderEntity == null) {
            throw new RRException("此订单不存在！");
        }
        if (orderEntity.getShippingStatus() == 0) {
            if (orderEntity.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_00.getItem()) ||
                orderEntity.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_02.getItem())) {
                throw new RRException("此订单还未发货！");
            } else {
                if (StringUtils.isNullOrEmpty(orderEntity.getShippingNo())) {
                    throw new RRException("此订单还未发货！");
                }
            }
        }

        Map logisticsInfo = Maps.newHashMap();
        List<WuliuEntity> wuliuEntityList = new ArrayList<>();
        OrderProcessRecordEntity orderProcessRecordEntity =
                orderProcessRecordDao.queryObjectByOrderSn(orderEntity.getOrderSn());
        if (orderProcessRecordEntity != null) {
            if (orderEntity.getOrderBizType().equals(Dict.orderBizType.item_10.getItem()) ||
                orderEntity.getOrderBizType().equals(Dict.orderBizType.item_02.getItem())) {
                WuliuEntity wuliuEntity = new WuliuEntity();
                wuliuEntity.setAcceptTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                                                  .format(orderProcessRecordEntity.getCustomsSuccTime()));
                wuliuEntity.setAcceptStation(PrintTicketPropertiesBuilder.instance().getAddress() + "送达" +
                                             storeDao.queryObject(orderEntity.getStoreId()).getStoreAddress() +
                                             ";交易完成，用户已提走");
                wuliuEntityList.add(wuliuEntity);
            }
            if (StringUtils.isNotEmpty(orderEntity.getShippingCode()) &&
                StringUtils.isNotEmpty(orderEntity.getShippingNo()) &&
                orderProcessRecordEntity.getShipmentStartTime() != null) {
                if(orderEntity.getShippingCode().equalsIgnoreCase("SF")){
                    StoreEntity storeEntity = storeDao.queryObject(orderEntity.getStoreId());
                    if(storeEntity == null){
                        throw new RRException("查询顺丰订单异常，订单的门店信息不存在");
                    }
                    ThirdMerchExpressEntity thirdMerchExpressEntity = thirdMerchExpressDao.getThirdMerchExpressByThirdCode(storeEntity.getThirdPartyMerchCode());
                    if(thirdMerchExpressEntity == null){
                        throw new RRException("查询顺丰订单异常，缺失商户快递账号信息");
                    }
                    SfRouteServiceResponseEntity entity = SFUtil.routeService(orderEntity.getShippingNo(), thirdMerchExpressEntity.getExpressAccount(),
                            thirdMerchExpressEntity.getExpressPwd(), SFPropertiesBuilder.instance().getUrl());
//                    SfRouteServiceResponseEntity entity = SFUtil.routeService("254355029325", thirdMerchExpressEntity.getExpressAccount(),
//                    thirdMerchExpressEntity.getExpressPwd(), SFPropertiesBuilder.instance().getUrl());//444072971585
                    if(entity.getHead().equalsIgnoreCase("OK")){
                        if(entity.getBody() == null){
                            WuliuEntity wuliuEntity = new WuliuEntity();
                            wuliuEntity.setAcceptStation("暂无物流轨迹");
                            wuliuEntityList.add(wuliuEntity);
                        }else{
                            if(entity.getBody().getRouteResponse() == null){
                                WuliuEntity wuliuEntity = new WuliuEntity();
                                wuliuEntity.setAcceptStation("暂无物流轨迹");
                                wuliuEntityList.add(wuliuEntity);
                            }else{
                                RouteResponseEntity routeResponseEntity =  entity.getBody().getRouteResponse().get(0);
                                if(routeResponseEntity != null){
                                    List<RouteEntity> entityList = routeResponseEntity.getRouteResponse();
                                    for (RouteEntity route : entityList) {
                                        WuliuEntity wuliuEntity = new WuliuEntity();
                                        wuliuEntity.setAcceptTime(route.getAccept_time());
                                        wuliuEntity.setAcceptStation(route.getAccept_address() + route.getRemark());
                                        wuliuEntityList.add(wuliuEntity);
                                    }
                                }
                            }
                        }
                    }else{
                        throw new RRException("查询顺丰订单异常，"+entity.getErrors());
                    }

                }else{
                    JSONObject traces =
                            KdniaoUtil.getOrderTracesByJson(orderEntity.getShippingCode(), orderEntity.getShippingNo());
                    List<Map> mapList = (List<Map>) traces.get("Traces");
                    if (mapList != null && mapList.size() > 0) {
                        for (Map map : mapList) {
                            WuliuEntity wuliuEntity = new WuliuEntity();
                            wuliuEntity.setAcceptTime(map.get("AcceptTime").toString());
                            wuliuEntity.setAcceptStation(map.get("AcceptStation").toString());
                            wuliuEntityList.add(wuliuEntity);
                        }
                    }
                    String state = traces.get("State") + "";
                    if (Dict.logisticsStatus.item_0.getItem().equals(state) && traces.getBoolean("Success")) {
                        String reason = traces.get("Reason") + "";
                        WuliuEntity wuliuEntity = new WuliuEntity();
                        wuliuEntity.setAcceptStation(reason);
                        wuliuEntityList.add(wuliuEntity);
                    }
                }
            }
            if (Dict.isSend.item_1.getItem().equalsIgnoreCase(orderProcessRecordEntity.getIsCustomsSend()) &&
                orderProcessRecordEntity.getShipmentStartTime() != null) {
                WuliuEntity wuliuEntity = new WuliuEntity();
                wuliuEntity.setAcceptStation("订单已出库");
                wuliuEntity.setAcceptTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                                                  .format(orderProcessRecordEntity.getShipmentStartTime()));
                wuliuEntityList.add(wuliuEntity);
            }
            if (Dict.isSend.item_1.getItem().equals(orderProcessRecordEntity.getIsCustomsSend())) {
                WuliuEntity wuliuEntity = new WuliuEntity();
                wuliuEntity.setAcceptStation("订单清关完成，等待仓库发货");
                wuliuEntity.setAcceptTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                                                  .format(orderProcessRecordEntity.getCustomsSuccTime()));
                wuliuEntityList.add(wuliuEntity);
            }

            if (Dict.isSend.item_0.getItem().equalsIgnoreCase(orderProcessRecordEntity.getIsCustomsSend())) {
                WuliuEntity wuliuEntity = new WuliuEntity();
                wuliuEntity.setAcceptStation("订单清关失败");
                wuliuEntityList.add(wuliuEntity);
            }
            if (Dict.isSend.item_1.getItem().equalsIgnoreCase(orderProcessRecordEntity.getIsEleOrderSend()) &&
                orderProcessRecordEntity.getWaybillSuccTime() != null) {
                WuliuEntity wuliuEntity = new WuliuEntity();
                wuliuEntity.setAcceptStation("海关三单发送成功");
                wuliuEntity.setAcceptTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                                                  .format(orderProcessRecordEntity.getWaybillSuccTime()));
                wuliuEntityList.add(wuliuEntity);
            }
            if (Dict.isSend.item_1.getItem().equals(orderProcessRecordEntity.getIsPaymentSend())) {
                WuliuEntity wuliuEntity = new WuliuEntity();
                wuliuEntity.setAcceptStation("订单支付成功");
                wuliuEntity.setAcceptTime(
                        new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(orderProcessRecordEntity.getPaySuccTime()));
                wuliuEntityList.add(wuliuEntity);
            }
            if (Dict.isSend.item_1.getItem().equalsIgnoreCase(orderProcessRecordEntity.getIsAddOrderSend())) {
                WuliuEntity wuliuEntity = new WuliuEntity();
                wuliuEntity.setAcceptStation("订单下单成功");
                wuliuEntity.setAcceptTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                                                  .format(orderProcessRecordEntity.getAddOrderSuccTime()));
                wuliuEntityList.add(wuliuEntity);
            }
        }
        logisticsInfo.put("tracesList", wuliuEntityList);
        logisticsInfo.put("logisticCode", orderEntity.getShippingNo());
        logisticsInfo.put("shipperCode", orderEntity.getShippingCode());
        return logisticsInfo;
    }

    @Override
    public OrderEntity queryInfos(Long id) {
        OrderEntity orderEntity = orderDao.queryObject(id);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("orderId", id);
        List<OrderGoodsEntity> orderGoodsEntityList = orderGoodsDao.queryList(map);
        orderEntity.setOrderGoodsEntityList(orderGoodsEntityList);
        return orderEntity;
    }

    /**
     * 普货商品生成线下订单
     * @param offlineCartList
     * @param user
     * @return
     */
    @Transactional
    @Override
    public Map orderSubmit(List<OfflineCartEntity> offlineCartList, SysUserEntity user) {
        Map resultObj = Maps.newHashMap();
        try {
            if (user == null) {
                resultObj.put("errno", 400);
                resultObj.put("errmsg", "用户登录超时，请重新登录");
                return resultObj;
            }
            if (!user.getRoleType().equalsIgnoreCase("2")) {
                resultObj.put("errno", 400);
                resultObj.put("errmsg", "该操作只允许店员账户操作");
                return resultObj;
            }
            if (org.apache.commons.lang3.StringUtils.isEmpty(user.getMerchSn())) {
                resultObj.put("errno", 400);
                resultObj.put("errmsg", "操作用户的商户编号为空，请先维护用户商户编号信息再来操作");
                return resultObj;
            }
            Long userId = user.getUserId();
            Integer storeId = user.getStoreId();
            //获取要购买的商品
            Map param = Maps.newHashMap();
            param.put("userId", userId);
            param.put("storeId", storeId);
            if (null == offlineCartList && offlineCartList.size() == 0) {
                resultObj.put("errno", 400);
                resultObj.put("errmsg", "购买商品数据为空");
                return resultObj;
            }
            List<OfflineCartEntity> offlineCartEntityList = offlineCartDao.queryOfflineCartByBizType(param);
            if (offlineCartEntityList.size() == 0 && offlineCartList.size() > 0) {
                resultObj.put("errno", 0);
                resultObj.put("errmsg", "该单已下单成功，请重新扫描商品进行购买");
                return resultObj;
            }
            // 检查库存和更新库存
            for (OfflineCartEntity cartEntity : offlineCartEntityList) {
                GoodsEntity goodsEntity = goodsDao.queryObject(cartEntity.getGoodsId());
                if (goodsEntity == null) {
                    resultObj.put("errno", 400);
                    resultObj.put("errmsg", "订单提交失败：商品不存在");
                    return resultObj;
                }
                //取得规格的信息,判断规格库存
                ProductStoreRelaEntity productInfo = productStoreRelaDao
                        .queryByGoodsIdAndStoreId(Long.valueOf(storeId), Long.valueOf(cartEntity.getGoodsId()));
                synchronized (productInfo) {
                    if (null == productInfo || null == productInfo.getStockNum() ||
                        productInfo.getStockNum() < cartEntity.getNumber()) {
                        resultObj.put("errno", 400);
                        resultObj.put("errmsg", "库存不足，仅剩余" + productInfo.getStockNum());
                        return resultObj;
                    } else {
                        productInfo.setStockNum(productInfo.getStockNum() - cartEntity.getNumber());
                        productInfo.setStoreId(Long.valueOf(storeId));
                        productInfo.addSellVolume();
                        productStoreRelaDao.updateStockNum(productInfo);//修改普通商品库存

                        if(goodsEntity != null) {
                            goodsEntity.setGoodsNumber(goodsEntity.getGoodsNumber() - cartEntity.getNumber());
                            goodsDao.update(goodsEntity);
                        }
                    }
                }
            }
            String merchOrderSn = "EMATO" + CommonUtil.generateOrderNumber();
            OrderEntity order = setOrderVo(user, offlineCartEntityList, user.getMerchSn());
            order.setStoreId(storeId);
            order.setMerchOrderSn(merchOrderSn);

            //开启事务，插入订单信息和订单商品
            if (order != null) {
                orderDao.save(order);
                if (null == order.getId()) {
                    resultObj.put("errno", 400);
                    resultObj.put("errmsg", "订单提交失败");
                    return resultObj;
                }
                for (OfflineCartEntity cartEntity : offlineCartEntityList) {
                    OrderGoodsEntity orderGoodsEntity = setOrderGoodsVo(order, cartEntity);
                    //新增订单详情
                    orderGoodsDao.save(orderGoodsEntity);
                }
                //清空预订单商品临时表
                offlineCartDao.deleteByUserId(userId);
                Map orderInfoMap = Maps.newHashMap();
                orderInfoMap.put("orderInfo", order);
                resultObj.put("errno", 0);
                resultObj.put("errmsg", "订单提交成功");
                resultObj.put("data", orderInfoMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultObj.put("errno", 400);
            resultObj.put("errmsg", "订单异常");
            return resultObj;
        }
        return resultObj;
    }

    /**
     * 设置订单数据
     *
     * @param loginUser
     * @return
     */
    public OrderEntity setOrderVo(SysUserEntity loginUser, List<OfflineCartEntity> offlineCartEntityList,
                                  String merchSn) {
        OrderEntity orderInfo = new OrderEntity();
        BigDecimal freightPrice = new BigDecimal(0.00);
        BigDecimal goodsTotalPrice = new BigDecimal(0.00);
        for (OfflineCartEntity offlineCartEntity : offlineCartEntityList) {
            goodsTotalPrice = goodsTotalPrice
                    .add(offlineCartEntity.getRetailPrice().multiply(new BigDecimal(offlineCartEntity.getNumber())));
        }
        //订单价格计算：订单的总价+运费
        BigDecimal orderTotalPrice = goodsTotalPrice.add(freightPrice);
        //查询未使用的优惠券
        /*String couponName = "";
        BigDecimal fullCutCouponDec = Constant.ZERO;
        UserCouponVo couponVo = null;*/
        BigDecimal couponPrice = new BigDecimal(0.00);
        //减去其它支付的金额后，要实际支付的金额   订单的总价+运费-优惠券金额
        BigDecimal actualPrice = orderTotalPrice.subtract(couponPrice);

        //商户（拼音首字母）+业务类型+编号
        //        String merchSn = OmsMerchPropertiesBuilder.instance().getMerchSn();
        //        String merchShortName = OmsMerchPropertiesBuilder.instance().getMerchShortName();
        MerchEntity merchEntity = merchDao.findByMerchSn(merchSn);
        String merchShortName = "";
        if (merchEntity != null) {
            merchShortName = merchEntity.getMerchShortName();
        }
        String orderSn = merchShortName + Dict.orderBizType.item_11.getItem() + CommonUtil.generateOrderNumber();
        orderInfo.setOrderSn(orderSn);
        orderInfo.setMerchSn(merchSn);
        orderInfo.setUserId(Integer.parseInt(loginUser.getUserId() + ""));
        orderInfo.setFreightPrice(freightPrice.intValue());
        orderInfo.setOrderBizType(Dict.orderBizType.item_11.getItem());

        /*orderInfo.setCoupon_id(userCouponId);
        orderInfo.setCoupon_name(couponName);*/
        //        orderInfo.setFullCutPrice(fullCutCouponDec);//使用的优惠券
        orderInfo.setCouponPrice(couponPrice);
        orderInfo.setPostscript("");//留言
        orderInfo.setAddTime(new Date());
        orderInfo.setGoodsPrice(goodsTotalPrice);
        orderInfo.setOrderPrice(orderTotalPrice);
        orderInfo.setActualPrice(actualPrice);
        orderInfo.setOrderType("1");
        orderInfo.setOrderStatus(0);// 待付款
        orderInfo.setShippingStatus(0);
        orderInfo.setPayStatus(0);
        orderInfo.setShippingId(0L);
        orderInfo.setShippingFee(Constant.ZERO);
        orderInfo.setIntegral(0);
        orderInfo.setIntegralMoney(Constant.ZERO);
        orderInfo.setCreateTime(new Date());
        orderInfo.setModTime(new Date());
        orderInfo.setIsOnfflineOrder(Dict.isOnfflineOrder.item_1.getItem());//线下购买
        /*//标记该订单已使用优惠券
        if(couponVo != null){
            couponVo.setUsed_time(new Date());
            couponVo.setIsUsed(Dict.isUsed.item_1.getItem());
            apiUserCouponMapper.update(couponVo);
        }*/
        return orderInfo;
    }

    /**
     * 设置订单数据
     *
     * @param
     * @return
     */
    public OrderEntity setOrder(Integer userId, List<LinkedHashMap> goodsList,
                                  String merchSn) {
        OrderEntity orderInfo = new OrderEntity();
        BigDecimal freightPrice = new BigDecimal(0.00);
        BigDecimal goodsTotalPrice = new BigDecimal(0.00);
        for (LinkedHashMap goods : goodsList) {
            goodsTotalPrice = goodsTotalPrice
                    .add(new BigDecimal((Double) goods.get("retailPrice")).multiply(new BigDecimal((Integer) goods.get("sellVolume"))));
        }
        //订单价格计算：订单的总价+运费
        BigDecimal orderTotalPrice = goodsTotalPrice.add(freightPrice);
        //查询未使用的优惠券
        /*String couponName = "";
        BigDecimal fullCutCouponDec = Constant.ZERO;
        UserCouponVo couponVo = null;*/
        BigDecimal couponPrice = new BigDecimal(0.00);
        //减去其它支付的金额后，要实际支付的金额   订单的总价+运费-优惠券金额
        BigDecimal actualPrice = orderTotalPrice.subtract(couponPrice);

        //商户（拼音首字母）+业务类型+编号
        //        String merchSn = OmsMerchPropertiesBuilder.instance().getMerchSn();
        //        String merchShortName = OmsMerchPropertiesBuilder.instance().getMerchShortName();
        MerchEntity merchEntity = merchDao.findByMerchSn(merchSn);
        String merchShortName = "";
        if (merchEntity != null) {
            merchShortName = merchEntity.getMerchShortName();
        }
        String orderSn = merchShortName + Dict.orderBizType.item_10.getItem() + CommonUtil.generateOrderNumber();
        orderInfo.setOrderSn(orderSn);
        orderInfo.setMerchSn(merchSn);
        orderInfo.setUserId(userId);
        orderInfo.setFreightPrice(freightPrice.intValue());
        orderInfo.setOrderBizType(Dict.orderBizType.item_10.getItem());

        /*orderInfo.setCoupon_id(userCouponId);
        orderInfo.setCoupon_name(couponName);*/
        //        orderInfo.setFullCutPrice(fullCutCouponDec);//使用的优惠券
        orderInfo.setCouponPrice(couponPrice);
        orderInfo.setPostscript("");//留言
        orderInfo.setAddTime(new Date());
        orderInfo.setGoodsPrice(goodsTotalPrice);
        orderInfo.setOrderPrice(orderTotalPrice);
        orderInfo.setActualPrice(actualPrice);
        orderInfo.setOrderType("1");
        orderInfo.setOrderStatus(0);// 待付款
        orderInfo.setShippingStatus(0);
        orderInfo.setPayStatus(0);
        orderInfo.setShippingId(0L);
        orderInfo.setShippingFee(Constant.ZERO);
        orderInfo.setIntegral(0);
        orderInfo.setIntegralMoney(Constant.ZERO);
        orderInfo.setCreateTime(new Date());
        orderInfo.setModTime(new Date());
        orderInfo.setIsOnfflineOrder(Dict.isOnfflineOrder.item_1.getItem());//线下购买
//        orderInfo.setIsScan("0");//默认未扫描
        /*//标记该订单已使用优惠券
        if(couponVo != null){
            couponVo.setUsed_time(new Date());
            couponVo.setIsUsed(Dict.isUsed.item_1.getItem());
            apiUserCouponMapper.update(couponVo);
        }*/
        return orderInfo;
    }


    public OrderGoodsEntity setOrderGoodsVo(OrderEntity orderInfo, OfflineCartEntity goodsItem) {
        GoodsEntity goodsVo = goodsDao.queryObject(goodsItem.getGoodsId());
        OrderGoodsEntity orderGoodsVo = new OrderGoodsEntity();
        orderGoodsVo.setOrderId(Integer.parseInt(orderInfo.getId() + ""));
        orderGoodsVo.setGoodsId(goodsItem.getGoodsId());
        orderGoodsVo.setGoodsSn(goodsItem.getGoodsSn());
        orderGoodsVo.setProductId(goodsItem.getProductId());
        orderGoodsVo.setGoodsName(goodsItem.getGoodsName());
        orderGoodsVo.setListPicUrl(goodsItem.getListPicUrl());
        orderGoodsVo.setMarketPrice(goodsItem.getMarketPrice());
        orderGoodsVo.setRetailPrice(goodsItem.getRetailPrice());
        orderGoodsVo.setNumber(goodsItem.getNumber());
        orderGoodsVo.setOrderBizType(Dict.orderBizType.item_11.getItem());
        orderGoodsVo.setCreateTime(new Date());
        orderGoodsVo.setModTime(new Date());
        orderGoodsVo.setGoodsRate(goodsVo.getGoodsRate());
        orderGoodsVo.setSku(goodsVo.getSku());
        return orderGoodsVo;
    }

//    public OrderGoodsEntity setOrderGoods(OrderEntity orderInfo, LinkedHashMap goods) {
//        GoodsEntity goodsVo = goodsDao.queryObject(goods.get("goodsId"));
//        ProductEntity productEntity = productDao.queryObjectByGoodsIdAndStoreId(goodsVo.getId() + "", null);
//        OrderGoodsEntity orderGoodsVo = new OrderGoodsEntity();
//        orderGoodsVo.setOrderId(Integer.parseInt(orderInfo.getId() + ""));
//        orderGoodsVo.setGoodsId(goodsVo.getId().intValue());
//        orderGoodsVo.setGoodsSn(goodsVo.getGoodsSn());
//        orderGoodsVo.setProductId(productEntity.getId().intValue());
//        orderGoodsVo.setGoodsName(goodsVo.getName());
//        orderGoodsVo.setListPicUrl(goodsVo.getListPicUrl());
//
//
//        orderGoodsVo.setMarketPrice((BigDecimal) goods.get("storeMarketPrice"));
//        orderGoodsVo.setRetailPrice((BigDecimal) goods.get("storeRetailPrice"));
//        orderGoodsVo.setNumber((Integer) goods.get("sellVolume"));
//        orderGoodsVo.setOrderBizType(Dict.orderBizType.item_10.getItem());
//        orderGoodsVo.setCreateTime(new Date());
//        orderGoodsVo.setModTime(new Date());
//        orderGoodsVo.setGoodsRate(goodsVo.getGoodsRate());
//        orderGoodsVo.setSku(goodsVo.getSku());
//
//
//        BigDecimal number = new BigDecimal(Long.valueOf(goodsItem.getNumber()));
//        BigDecimal goodsTotal = goodsItem.getRetail_price().multiply(number);//单商品总价
//        BigDecimal rate = goodsTotal.divide(orderInfo.getGoods_price(),2, BigDecimal.ROUND_HALF_UP);//当前商品总价/订单总价（不含运费、不含优惠券）
//        BigDecimal freightPrice = BigDecimal.valueOf(orderInfo.getFreight_price());
//        BigDecimal settlePrice = Constant.ZERO;
//        if(orderInfo.getFreight_price() != 0 && !"0".equalsIgnoreCase(orderInfo.getCoupon_price()+"")){
//            //运费-优惠券
//            BigDecimal rateTotal = freightPrice.subtract(orderInfo.getCoupon_price());
//            //商品结算平摊价格（含优惠券、运费金额） = 单商品总价 + 当前商品总价/订单总价（不含运费、不含优惠券） * 运费与优惠券合计税率
//            settlePrice = goodsTotal.add(rate.multiply(rateTotal));
//        }else{
//            if(orderInfo.getFreight_price()!=0){
//                //运费税率 = 单商品总价/订单总价（不含运费）* 运费金额
//                BigDecimal freightRate = rate.multiply(freightPrice);
//                //商品结算平摊价格（含运费金额） = 单商品总价+运费税率
//                settlePrice = goodsTotal.add(freightRate);
//            }
//            if(!"0".equalsIgnoreCase(orderInfo.getCoupon_price()+"")){
//                //优惠券税率 = 单商品总价/订单总价（不含优惠券）* 优惠券金额
//                BigDecimal couponRate = rate.multiply(orderInfo.getCoupon_price());
//                //商品结算平摊价格（含优惠券金额） = 单商品总价-优惠券税率
//                settlePrice = goodsTotal.subtract(couponRate);
//            }
//        }
//        if(settlePrice.compareTo(BigDecimal.valueOf(0)) == 0){
//            orderGoodsVo.setSettlePrice(goodsTotal);//商品结算平摊价格
//        }else{
//            orderGoodsVo.setSettlePrice(settlePrice);//商品结算平摊价格
//        }
//
//        return orderGoodsVo;
//    }


    @Override
    public OrderEntity queryObjectBySysUser(Long id) {
        OrderEntity orderEntity = orderDao.queryObjectBySysUser(id);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("orderId", id);
        List<OrderGoodsEntity> orderGoodsEntityList = orderGoodsDao.queryList(map);
        orderEntity.setOrderGoodsEntityList(orderGoodsEntityList);
        return orderEntity;
    }

    @Override
    public int confirmPay(Long id, String payFlag,String orderSnWx) {
        SysUserEntity user = ShiroUtils.getUserEntity();
        if (user == null) {
            throw new RRException("用户登录超时，请重新登录");
        }
        if (!user.getRoleType().equalsIgnoreCase("2")) {
            throw new RRException("该操作只允许店员账户操作");
        }
        OrderEntity orderEntity = queryObject(id);
        if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) {
            throw new RRException("此订单已付款！");
        }
        if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_301.getItem())) {
            throw new RRException("此订单已完成！");
        }
        if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_101.getItem())) {
            throw new RRException("此订单已取消！");
        }
        if (orderEntity.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_102.getItem())) {
            throw new RRException("此订单已删除！");
        }
        orderEntity.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_201.getItem()));
        orderEntity.setPayStatus(Integer.parseInt(Dict.payStatus.item_2.getItem()));
        orderEntity.setPayFlag(payFlag);
        orderEntity.setPayTime(new Date());
        if(orderSnWx != null){
            orderEntity.setOrderSnWx(orderSnWx);
        }
        orderDao.update(orderEntity);
        return 0;
    }

    @Override
    public List<OrderEntity> queryExportList(Map<String, Object> map) {
        List<OrderEntity> list = orderDao.queryExportList(map);
        for (OrderEntity order : list) {
            OrderProcessRecordEntity orderProcessRecord = orderProcessRecordDao.queryObjectByOrderSn(order.getOrderSn());
            order.setOrderProcessRecord(orderProcessRecord);
        }
        return list;
    }

    @Override
    public List<OrderEntity> queryOffilineOrderList(Map<String, Object> map) {
        return orderDao.queryOffilineOrderList(map);
    }

    @Override
    public int uploadExcel(List<OrderExpressDto> orderExpressDtoList) {
        SysUserEntity user = ShiroUtils.getUserEntity();
        boolean isFail = false;
        List<String> failShippingNameList = new ArrayList<>();
        List<String> failOrderSnList = new ArrayList<>();
        List<String> failShippingCodeList = new ArrayList<>();
        List<String> failCodeSnList = new ArrayList<>();
        List<String> failNameSnList = new ArrayList<>();
        List<String> failStatusOrderSnList = new ArrayList<>();
        if (orderExpressDtoList != null && orderExpressDtoList.size() > 0) {
            for (int i = 0; i < orderExpressDtoList.size(); i++) {
                OrderExpressDto orderExpressDto = orderExpressDtoList.get(i);
                OrderEntity orderEntity = new OrderEntity();
                Map<String, Object> valideDate = MapBeanUtil.fromObject(orderExpressDto);
                ImmutableBiMap.Builder builder = new ImmutableBiMap.Builder();
                builder.put("orderSn", "订单编号");
                builder.put("shippingNo", "快递单号");
                builder.put("shippingName", "快递公司");
                builder.put("shippingCode", "快递简写");
                R r = ValidatorUtil.isEmpty(builder.build(), valideDate);
                if (Integer.valueOf(r.get("code").toString()) != 0) {
                    throw new RRException(r.get("msg").toString());
                } else {
                    r = ValidatorUtil.isEmpty(builder.build(), valideDate);
                    if (Integer.valueOf(r.get("code").toString()) != 0) {
                        throw new RRException(r.get("msg").toString());
                    }
                }
                OrderEntity order = orderDao.queryObjectByOrderSn(orderExpressDto.getOrderSn());
                if(order == null){
                    isFail = true;
                    failOrderSnList.add(orderExpressDto.getOrderSn());
                }else{
                    if(!(order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())
                            && order.getPayStatus() == Integer.parseInt(Dict.payStatus.item_2.getItem()))){
                        isFail = true;
                        failStatusOrderSnList.add(orderExpressDto.getOrderSn());
                    }
                }
                ShippingEntity shippingEntity = shippingDao.queryObjectByCode(orderExpressDto.getShippingCode());
                if(shippingEntity == null){
                    isFail = true;
                    failShippingCodeList.add(orderExpressDto.getShippingCode());
                    failCodeSnList.add(orderExpressDto.getOrderSn());
                }else{
                    if(!orderExpressDto.getShippingName().equalsIgnoreCase(shippingEntity.getName())){
                        isFail = true;
                        failShippingNameList.add(orderExpressDto.getShippingName());
                        failNameSnList.add(orderExpressDto.getOrderSn());
                    }
                }
                if(!isFail){//false则有错误的数据
                    if(order != null) {// 修改商品
//                        orderEntity.setOrderSn(orderExpressDto.getOrderSn());
                        orderEntity.setShippingNo(orderExpressDto.getShippingNo());
                        orderEntity.setShippingCode(orderExpressDto.getShippingCode());
                        orderEntity.setShippingName(orderExpressDto.getShippingName());
                        orderEntity.setShippingStatus(Integer.parseInt(Dict.shippingStatus.item_1.getItem()));
                        orderEntity.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_300.getItem()));
                        orderEntity.setModerSn(user.getUsername());
                        orderEntity.setCreateTime(new Date());
                        orderEntity.setModTime(new Date());
                        orderEntity.setId(order.getId());
                        orderDao.update(orderEntity);
                    }
                }
            }
            if(failOrderSnList != null && failOrderSnList.size() > 0){
                throw new RRException("导入数据异常，订单编号不存在，不存在的订单编号【"+failOrderSnList+"】，请删除掉再继续操作");
            }
            if(failStatusOrderSnList != null && failStatusOrderSnList.size() > 0){
                throw new RRException("导入数据异常，修改订单快递功能只支持已付款未发货的订单，以下订单编号无效【"+failStatusOrderSnList+"】，请删除掉再继续操作");
            }
            if(failShippingCodeList != null && failShippingCodeList.size() > 0){
                throw new RRException("导入数据异常，快递简写不在可支持的范围中，简写错误的订单编号【"+failCodeSnList+"】，错误的快递简写【"+failShippingCodeList+"】，" +
                        "正确数据可下载订单页面的快递公司简写Excel中查看");
            }
            if(failShippingNameList != null && failShippingNameList.size() > 0){
                throw new RRException("导入数据异常，快递简写对应的快递公司不一致，快递公司错误的订单编号【"+failNameSnList+"】，请修改Excel数据中订单编号对应的快递公司错误信息，" +
                        "正确数据可下载订单页面的快递公司简写Excel中查看");
            }
//            if(failFreightGoodsSnList != null && failFreightGoodsSnList.size() > 0){
//                exportExceptionDataEntity.setExportExceptionData("运费信息请在商城配置》运费模板中维护，运费与商户信息对应，请检查该商品商户信息下的运费是否维护，不存在的商品编码【"+failFreightGoodsSnList+"】,运费【"+failFreightList+"】");
//                exportExceptionDataDao.save(exportExceptionDataEntity);
//                throw new RRException("导入数据异常，异常信息请在商品管理》》商品导入异常数据中查看检查");
//            }
        }else{
            throw new RRException("导入数据为空，或者检查商品编码数据是否为空");
        }
        return 1;
    }

    @Override
    public List<OrderEntity> promOrderList(Map<String, Object> map) {
        Integer[] statusList = {201};
        List<OrderEntity> list = orderDao.promOrderList(map);
        for (OrderEntity orderEntity: list) {
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("goodsId", orderEntity.getGoodsId());
            queryMap.put("statusList", statusList);
            queryMap.put("orderId", orderEntity.getId());
            Double promActualPrice = orderDao.getActualPriceByOutProm(queryMap);
            if(promActualPrice == null){
                promActualPrice = 0d;
            }
            orderEntity.setPromActualPrice(BigDecimal.valueOf(promActualPrice));
        }
        return list;
    }

    @Override
    public int queryPromOrderTotal(Map<String, Object> map) {
        return orderDao.queryPromOrderTotal(map);
    }

    @Override
    public List<OrderEntity> promOrderListExport(Map<String, Object> map){
        Integer[] statusList = {201};
        List<OrderEntity> list = orderDao.promOrderListExport(map);
        for (OrderEntity orderEntity: list) {
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("goodsId", orderEntity.getGoodsId());
            queryMap.put("orderId", orderEntity.getId());
            queryMap.put("statusList", statusList);
            Double promActualPrice = orderDao.getActualPriceByOutProm(queryMap);
            if(promActualPrice == null){
                promActualPrice = 0d;
            }
            orderEntity.setPromActualPrice(BigDecimal.valueOf(promActualPrice));
        }
        return list;
    }

    @Override
    public List<OrderEntity> storeTopicOrderList(Map<String, Object> map) {
        List<OrderEntity> list = orderDao.storeTopicOrderList(map);
        return list;
    }

    @Override
    public int queryStoreTopicOrderTotal(Map<String, Object> map) {
        return orderDao.queryStoreTopicOrderTotal(map);
    }

    @Override
    public List<WxOrderEntity> wxOrderResendQueryAllList(Map<String, Object> map){
//        String requestData = JacksonUtil.toJson(map);
        String url = OmsMerchPropertiesBuilder.instance().getWxOrderResendUrl();
        // 同步访问,返回结果字符串
        String response = OkHttpUtils.post(map, url, "SSL");
        ResponseData responseData = JacksonUtils.fromStringJson(response, ResponseData.class);
        if(responseData.getCode().equalsIgnoreCase("0")){
            List<WxOrderEntity> list = responseData.getData().getRows();
            return list;
        }
        return null;
    }
    @Override
    public List<OrderRecognitionDto> queryOrderListByRecognition(Map<String, Object> map){
        String value = sysConfigDao.queryByKey("FACE_COLLECT_FREQUENCY_TIME");
        if(value==null){
            throw new RRException("请联系管理员配系统参数置FACE_COLLECT_FREQUENCY_TIME信息！");
        }
        List<OrderRecognitionDto> list = orderDao.queryOrderListByRecognition(map);
        for (OrderRecognitionDto orderRecognitionDto: list){
            Integer frequencySecondTime = Integer.parseInt(value);
            String lastFaceTime = orderRecognitionDto.getLastFaceTime();
            if(StringUtils.isNotEmpty(lastFaceTime)) {
                Date lastFaceDate = DateUtils.convertStringToDate(lastFaceTime, DateUtils.DATE_TIME_PATTERN);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(lastFaceDate);
                calendar.add(Calendar.SECOND, frequencySecondTime);
                Date addSecondTime = calendar.getTime();
                Date nowDate = new Date();
                if (addSecondTime.getTime() > nowDate.getTime()) {
                    orderRecognitionDto.setAddSecondTime(DateUtils.format(addSecondTime,DateUtils.DATE_TIME_PATTERN));
                    orderRecognitionDto.setIsDateLast("false");
                } else {
                    //可调用身份验证范围内
                    orderRecognitionDto.setIsDateLast("true");
                }
            }else{//可调用身份验证范围内
                orderRecognitionDto.setIsDateLast("true");
            }
        }
        return list;
    }

    @Override
    public int queryOrderListByRecognitionTotal(Map<String, Object> map){
        return orderDao.queryOrderListByRecognitionTotal(map);
    }

    /**
     * 提交订单并付款
     *
     * @param param
     * @param user
     * @return
     */
    @Override
    public Map offlineRetailSubmit(Map param, SysUserEntity user) {
        // 解析订单数据 List
        List<LinkedHashMap> goodsList = (List<LinkedHashMap>) param.get("goodsList");
        // 解析用户信息 LinkedHashMap
        Map userInfo = (Map) param.get("userInfo");
        // 解析支付码 String
        String parCode = (String) param.get("payCode");
        // 解析sessionId（WebSocket） String
        String sessionId = (String) param.get("sessionId");

        Map resultObj = Maps.newHashMap();
        try {
            if (user == null) {
                resultObj.put("errno", 400);
                resultObj.put("errmsg", "用户登录超时，请重新登录");
                return resultObj;
            }
            if (!user.getRoleType().equalsIgnoreCase("2")) {
                resultObj.put("errno", 400);
                resultObj.put("errmsg", "该操作只允许店员账户操作");
                return resultObj;
            }
            if (org.apache.commons.lang3.StringUtils.isEmpty(user.getMerchSn())) {
                resultObj.put("errno", 400);
                resultObj.put("errmsg", "操作用户的商户编号为空，请先维护用户商户编号信息再来操作");
                return resultObj;
            }
            Long userId = user.getUserId();
            Integer storeId = user.getStoreId();

            List<GoodsEntity> goodsEntities = new ArrayList<>();
            // 检查库存和更新库存
            for (LinkedHashMap goodsDto : goodsList) {
                //
                GoodsEntity goodsEntity = goodsDao.queryObjectByProdBarcodeAndStore((String) goodsDto.get("prodBarcode"),storeId);
                if (goodsEntity == null) {
                    resultObj.put("errno", 400);
                    resultObj.put("errmsg", "订单提交失败：商品不存在");
                    return resultObj;
                }
                Integer sellVolume = (Integer)goodsDto.get("sellVolume");
                goodsEntity.setGoodsNumber(sellVolume);
                goodsEntities.add(goodsEntity);
                goodsDto.put("goodsId",goodsEntity.getId());
                goodsDto.put("goodsSn",goodsEntity.getGoodsSn());
                goodsDto.put("productId",goodsEntity.getProductId());
                goodsDto.put("storeMarketPrice",goodsEntity.getStoreMarketPrice());
                goodsDto.put("storeRetailPrice",goodsEntity.getStoreRetailPrice());

                //取得规格的信息,判断规格库存
                ProductStoreRelaEntity productInfo = productStoreRelaDao
                        .queryByGoodsIdAndStoreId(Long.valueOf(storeId), Long.valueOf(goodsEntity.getId()));
                synchronized (productInfo) {
                    if (null == productInfo || null == productInfo.getStockNum() ||
                            productInfo.getStockNum() < (sellVolume)) {
                        resultObj.put("errno", 400);
                        resultObj.put("errmsg", "库存不足，仅剩余" + productInfo.getStockNum());
                        return resultObj;
                    } else {
                        productInfo.setStockNum(productInfo.getStockNum() - sellVolume);
                        productInfo.setStoreId(Long.valueOf(storeId));
                        productInfo.addSellVolume();
//                        productStoreRelaDao.updateStockNum(productInfo);//修改普通商品库存

                        if(goodsEntity != null) {
                            goodsEntity.setStockNum((Integer.parseInt(goodsEntity.getStockNum()) - sellVolume)+"");
//                            goodsDao.update(goodsEntity);
                        }
                    }
                }
            }

            UserEntity userEntity = userDao.queryByMobile((String) userInfo.get("customPhone"));
            if(userEntity == null) {
                // 保存用户信息
                userEntity = new UserEntity();
                userEntity.setUsername((String) userInfo.get("customName"));
                userEntity.setPassword("");
                userEntity.setIdNo((String) userInfo.get("customIDCard"));
                userEntity.setMobile((String) userInfo.get("customPhone"));
                userEntity.setGender(1);
                userEntity.setRegisterTime(new Date());
                userEntity.setLastLoginTime(new Date());
                userDao.save(userEntity);
            }



            // 生成订单
            String merchOrderSn = "EMATO" + CommonUtil.generateOrderNumber();
            OrderVo order = setOrderVo(goodsList, userEntity,storeId.longValue(), user.getMerchSn());
            order.setStore_id(storeId.longValue());
            order.setMerchOrderSn(merchOrderSn);

            //开启事务，插入订单信息和订单商品
            orderDao.saveOrderVo(order);

            // TODO 订单流转表
            OrderProcessRecordEntity processRecordEntity = new OrderProcessRecordEntity();
            processRecordEntity.setOrderSn(order.getOrder_sn());
            processRecordEntity.setUserId(Integer.valueOf(userEntity.getId()+""));
            processRecordEntity.setAddOrderStartTime(order.getCreateTime());

            processRecordEntity.setIsAddOrderSend(Dict.isSend.item_1.getItem());
            processRecordEntity.setOrderBizType(Dict.orderBizType.item_10.getItem());

            if (null == order.getId()) {
                resultObj.put("errno", 400);
                resultObj.put("errmsg", "订单提交失败");
                return resultObj;
            }
            for (GoodsEntity goodsDto : goodsEntities) {

                OrderGoodsVo orderGoodsVo = setOrderGoodsVo(order,goodsDto);
                //新增订单详情
                orderGoodsDao.saveOrderGoodsVo(orderGoodsVo);
            }
            //清空预订单商品临时表
            Map orderInfoMap = Maps.newHashMap();
            orderInfoMap.put("orderInfo", order);
            resultObj.put("errno", 0);
            resultObj.put("errmsg", "订单提交成功");
            resultObj.put("data", orderInfoMap);

            //判断支付类型，并支付订单
            R r = null;
            //保存支付记录
            OrderWXPayRecordEntity orderWXPayRecordCurrent = orderWXPayRecordService.saveRecordVo(order);

            StoreEntity store = storeService.queryObject(order.getStore_id().intValue());

            // 设置支付单开始时间
            processRecordEntity.setPaymentStartTime(new Date());


            // 微信支付
            wxPay(user, parCode, resultObj, order, processRecordEntity, orderWXPayRecordCurrent, store);
            // 支付宝支付
//            AliPay();

            // 保存订单流转表
            // 设置下单完成时间
            processRecordEntity.setAddOrderSuccTime(order.getPay_time());
            orderProcessRecordDao.save(processRecordEntity);


            // 生成取票码
            PickUpCodeEntity pickUpCodeEntity = new PickUpCodeEntity();
            pickUpCodeEntity.setOrderSn(order.getOrder_sn());
            pickUpCodeService.save(pickUpCodeEntity);

            resultObj.put("code",pickUpCodeEntity.getPickUpCodeSn()); // 系统中累加

            resultObj.put("time",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            resultObj.put("orderNo",order.getOrder_sn()); //

            // 通知WebSocket
            WebSocketServer.sendMessage(sessionId,order.getOrder_sn(),order.getStore_id()
                    +"");
        } catch (Exception e) {
            e.printStackTrace();
            resultObj.put("errno", 400);
            resultObj.put("errmsg", "订单异常");
            return resultObj;
        }




        return resultObj;
    }

    private void wxPay(SysUserEntity user, String parCode, Map resultObj, OrderVo order, OrderProcessRecordEntity processRecordEntity, OrderWXPayRecordEntity orderWXPayRecordCurrent, StoreEntity store) throws ParseException {
        R r;
        WechatMicropayApiResult wechatMicropayApiResult = WechatUtil
                .wxMicropay(store.getMerchName() + "-" + store.getStoreName(), order.getOrderBizType(), null,
                        orderWXPayRecordCurrent.getOutTradeNoWX(), order.getActual_price().doubleValue(),
                        "127.0.0.1", parCode);
        orderWXPayRecordService.updateRecord(orderWXPayRecordCurrent.getId(), wechatMicropayApiResult);


        resultObj.put("shopName",store.getStoreName()); // 根据门店编号查询
        resultObj.put("userName",user.getUsername());
        // 修改订单状态
        //当支付成功时,修改订单,并把其他支付记录撤销
        if (WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatMicropayApiResult.getTrade_state())) {
            //查询当前订单所有的支付记录
            List<OrderWXPayRecordEntity> orderWXPayRecordEntitys =
                    orderWXPayRecordService.getRecordsByOutTradeNo(order.getOrder_sn());
            for (OrderWXPayRecordEntity orderWXPayRecordTemp : orderWXPayRecordEntitys) {
                //查询出来的记录排除当前已支付成功的记录,对其他记录交易状态为未撤销,未关闭的订单，调用撤销订单
                if (orderWXPayRecordTemp.getId() != orderWXPayRecordCurrent.getId() &&
                        (!WechatUtil.WXTradeState.REVOKED.getCode().equals(orderWXPayRecordTemp.getTradeState()) ||
                                !WechatUtil.WXTradeState.CLOSED.getCode().equals(orderWXPayRecordTemp.getTradeState()))) {
                    WechatReverseApiResult wechatReverseApiResult =
                            WechatUtil.wxReverse(orderWXPayRecordTemp.getOutTradeNoWX());
                    //撤销订单成功
                    if (WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatReverseApiResult.getReturn_code()) &&
                            WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatReverseApiResult.getResult_code())) {
                        //调用订单查询接口
                        WechatRefundApiResult wechatRefundApiResult =
                                WechatUtil.wxOrderQuery(orderWXPayRecordTemp.getOutTradeNoWX());
                        if (WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatRefundApiResult.getReturn_code()) &&
                                WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatRefundApiResult.getResult_code())) {
                            // 修改订单支付记录
                            orderWXPayRecordService
                                    .updateWXPayRecordTradeState(orderWXPayRecordTemp.getId(), wechatRefundApiResult);
                        }
                    }
                }
            }
            this.confirmPay(order.getId(), Dict.payFlag.item_weixin.getItem(), orderWXPayRecordCurrent.getOutTradeNoWX());

            // 设置支付单完成时间
            processRecordEntity.setPaymentSuccTimeStr(wechatMicropayApiResult.getTime_end());
            processRecordEntity.setPaymentSuccTime(
                    new SimpleDateFormat("yyyyMMddHHmmss").parse(wechatMicropayApiResult.getTime_end()));
            processRecordEntity.setPayTransactionId(wechatMicropayApiResult.getTransaction_id());

            //用户支付中
        } else if (WechatUtil.WXTradeState.USERPAYING.getCode().equals(wechatMicropayApiResult.getTrade_state())) {
            r = R.error(WechatUtil.WXTradeState.USERPAYING.getCodeZn() + ",稍等片刻后请刷新页面重新查看订单状态");
            //用户支付失败
        } else if (WechatUtil.WXTradeState.PAYERROR.getCode().equals(wechatMicropayApiResult.getTrade_state())) {
            WechatReverseApiResult wechatReverseApiResult =
                    WechatUtil.wxReverse(orderWXPayRecordCurrent.getOutTradeNoWX());
            //撤销订单成功
            if (WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatReverseApiResult.getReturn_code()) &&
                    WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatReverseApiResult.getResult_code())) {
                //调用订单查询接口
                WechatRefundApiResult wechatRefundApiResult =
                        WechatUtil.wxOrderQuery(orderWXPayRecordCurrent.getOutTradeNoWX());
                if (WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatRefundApiResult.getReturn_code()) &&
                        WechatUtil.WXTradeState.SUCCESS.getCode().equals(wechatRefundApiResult.getResult_code())) {
                    // 修改订单支付记录
                    orderWXPayRecordService
                            .updateWXPayRecordTradeState(orderWXPayRecordCurrent.getId(), wechatRefundApiResult);
                }
                r = R.error(orderWXPayRecordCurrent.getErrCodeDes());
            } else {
                r = R.error(wechatReverseApiResult.getErr_code_des());
            }

        }
    }

    @Override
    public OrderEntity queryObjectByOrderSn(String orderSn) {
        return orderDao.queryObjectByOrderSn(orderSn);
    }


    /**
     * 设置订单数据
     * @return
     */
    public OrderVo setOrderVo(List<LinkedHashMap> goodsList, UserEntity loginUser,Long storeId, String merchSn){
        OrderVo orderInfo = new OrderVo();

        BigDecimal goodsTotalPrice = new BigDecimal(0.00);
        BigDecimal freightPrice = Constant.ZERO;
        for (LinkedHashMap goods : goodsList) {
            goodsTotalPrice = goodsTotalPrice
                    .add(new BigDecimal((Double) goods.get("retailPrice")).multiply(new BigDecimal((Integer) goods.get("sellVolume"))));
        }


        //订单价格计算：订单的总价+运费
        BigDecimal orderTotalPrice = goodsTotalPrice.add(new BigDecimal(0));
        BigDecimal fullCutCouponDec = Constant.ZERO;
        BigDecimal couponPrice = new BigDecimal(0.00);
        BigDecimal actualPrice = orderTotalPrice.subtract(couponPrice);

        String orderSn = "CW" +  CommonUtil.generateOrderNumber();
        orderInfo.setOrder_sn(orderSn);
        orderInfo.setMerchSn(merchSn);
        orderInfo.setUser_id(loginUser.getId().longValue());


        StoreEntity storeEntity = storeDao.queryObject(storeId);
        //收货地址和运费
        orderInfo.setConsignee(loginUser.getUsername());
        orderInfo.setMobile(loginUser.getMobile());
        orderInfo.setCountry("");
        orderInfo.setProvince(storeEntity.getProvinceName());
        orderInfo.setCity(storeEntity.getCityName());
        orderInfo.setDistrict(storeEntity.getCountyName());
        orderInfo.setAddress(storeEntity.getStoreName());
        orderInfo.setAddress_id(1L);
        orderInfo.setDelivery_date(new Date());
        orderInfo.setDelivery_remark("无");
        orderInfo.setStore_id(storeId);
        orderInfo.setFreight_price(freightPrice.intValue());

        orderInfo.setCoupon_id(Integer.parseInt(String.valueOf(0L)));
        orderInfo.setCoupon_price(couponPrice);
        orderInfo.setCoupon_name("无");
        orderInfo.setActivity_id(0L);

        //使用的促销费用
        orderInfo.setFull_cut_price(fullCutCouponDec);
        orderInfo.setCampMinusId(0);
        orderInfo.setCampName("");

        //留言
        orderInfo.setPostscript("无");
        orderInfo.setAdd_time(new Date());
        orderInfo.setGoods_price(goodsTotalPrice);
        orderInfo.setOrder_price(orderTotalPrice);
        orderInfo.setActual_price(actualPrice);
        orderInfo.setOrder_type("1");
        orderInfo.setOrder_status(201);
        orderInfo.setShipping_status(0);
        orderInfo.setPay_status(0);
        orderInfo.setShipping_id(0L);
        orderInfo.setShipping_fee(Constant.ZERO);
        orderInfo.setIntegral(0);
        orderInfo.setIntegral_money(Constant.ZERO);
        orderInfo.setCreateTime(new Date());
        orderInfo.setModTime(new Date());
        orderInfo.setPayMobile(loginUser.getMobile());
        orderInfo.setPayTransactionId("");
        orderInfo.setIsScan("0");//默认未扫描

        orderInfo.setPayMobile(loginUser.getMobile());
        orderInfo.setPay_name(loginUser.getUsername());
        orderInfo.setIsOnfflineOrder(Dict.isOnfflineOrder.item_1.getItem());
        orderInfo.setOrderBizType(Dict.orderBizType.item_10.getItem());

        return orderInfo;
    }


    public OrderGoodsVo setOrderGoodsVo(OrderVo orderInfo,GoodsEntity goodsDto){
        OrderGoodsVo orderGoodsVo = new OrderGoodsVo();
        orderGoodsVo.setOrder_id(orderInfo.getId());
        orderGoodsVo.setGoods_id(goodsDto.getId());
        orderGoodsVo.setGoods_sn(goodsDto.getGoodsSn());
        orderGoodsVo.setProduct_id(Long.valueOf(goodsDto.getProductId()));
        orderGoodsVo.setGoods_name(goodsDto.getName());
        orderGoodsVo.setList_pic_url(goodsDto.getListPicUrl());
        orderGoodsVo.setMarket_price(goodsDto.getStoreMarketPrice());
        orderGoodsVo.setRetail_price(goodsDto.getStoreRetailPrice());
        orderGoodsVo.setNumber(goodsDto.getGoodsNumber());
//        orderGoodsVo.setGoods_specification_name_value(goodsDto.get);
//        orderGoodsVo.setGoods_specification_ids(goodsItem.getGoods_specification_ids());
        orderGoodsVo.setOrderBizType(Dict.orderBizType.item_10.getItem());
        orderGoodsVo.setCreateTime(new Date());
        orderGoodsVo.setModTime(new Date());


        orderGoodsVo.setGoodsRate(goodsDto.getGoodsRate());
        orderGoodsVo.setSku(goodsDto.getSku());

        BigDecimal number = new BigDecimal(Long.valueOf(goodsDto.getGoodsNumber()));
        BigDecimal goodsTotal = goodsDto.getStoreRetailPrice().multiply(number);//单商品总价
        BigDecimal rate = goodsTotal.divide(orderInfo.getGoods_price(),2, BigDecimal.ROUND_HALF_UP);//当前商品总价/订单总价（不含运费、不含优惠券）
        BigDecimal freightPrice = BigDecimal.valueOf(orderInfo.getFreight_price());
        BigDecimal settlePrice = Constant.ZERO;
        if(orderInfo.getFreight_price() != 0 && !"0".equalsIgnoreCase(orderInfo.getCoupon_price()+"")){
            //运费-优惠券
            BigDecimal rateTotal = freightPrice.subtract(orderInfo.getCoupon_price());
            //商品结算平摊价格（含优惠券、运费金额） = 单商品总价 + 当前商品总价/订单总价（不含运费、不含优惠券） * 运费与优惠券合计税率
            settlePrice = goodsTotal.add(rate.multiply(rateTotal));
        }else{
            if(orderInfo.getFreight_price()!=0){
                //运费税率 = 单商品总价/订单总价（不含运费）* 运费金额
                BigDecimal freightRate = rate.multiply(freightPrice);
                //商品结算平摊价格（含运费金额） = 单商品总价+运费税率
                settlePrice = goodsTotal.add(freightRate);
            }
            if(!"0".equalsIgnoreCase(orderInfo.getCoupon_price()+"")){
                //优惠券税率 = 单商品总价/订单总价（不含优惠券）* 优惠券金额
                BigDecimal couponRate = rate.multiply(orderInfo.getCoupon_price());
                //商品结算平摊价格（含优惠券金额） = 单商品总价-优惠券税率
                settlePrice = goodsTotal.subtract(couponRate);
            }
        }
        if(settlePrice.compareTo(BigDecimal.valueOf(0)) == 0){
            orderGoodsVo.setSettlePrice(goodsTotal);//商品结算平摊价格
        }else{
            orderGoodsVo.setSettlePrice(settlePrice);//商品结算平摊价格
        }

        return orderGoodsVo;
    }

}
