package com.kmall.api.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.kmall.api.dao.mk.ApiMkStoreCampMinusMapper;
import com.kmall.api.dao.mk.ApiMkStorePromMapper;
import com.kmall.api.dao.mk.ApiMkStoreTicketDiscountMapper;
import com.kmall.api.dto.CampMinusDto;
import com.kmall.api.dto.CheckOutDto;
import com.kmall.api.entity.mk.MkStoreCampMinusVo;
import com.kmall.api.entity.mk.MkStorePromStatVo;
import com.kmall.api.entity.mk.MkStorePromVo;
import com.kmall.api.entity.mk.MkStoreTicketDiscountVo;
import com.kmall.api.fromcomm.entity.FormIdsEntity;
import com.kmall.api.service.mk.ApiMkStorePromStatService;
import com.kmall.api.service.mk.ApiMkStoreTopicStatService;
import com.kmall.api.util.StockUtil;
import com.kmall.common.utils.*;
import com.kmall.manager.dao.TemplateConfDao;
import com.kmall.manager.entity.pay.TemplateConfVo;
import com.kmall.manager.manager.print.ticket.PrintTicketPropertiesBuilder;
import com.kmall.manager.manager.print.ticket.TicketPrintUtil;
import com.kmall.api.fromcomm.service.FormIdsService;
import com.kmall.common.constant.Dict;
import com.kmall.api.dao.*;
import com.kmall.api.dto.IdCardMsgVo;
import com.kmall.api.entity.*;
import com.kmall.manager.manager.merch.OmsMerchPropertiesBuilder;
import com.kmall.api.util.CommonUtil;
import com.kmall.api.util.IdCardUtil;
import com.kmall.common.utils.print.ticket.item.*;
import com.kmall.manager.manager.wechat.wxtemplate.TemplateData;
import com.kmall.manager.manager.wechat.wxtemplate.WxTemplate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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.SimpleDateFormat;
import java.util.*;


@Service
public class ApiOrderService {
    private Log logger = LogFactory.getLog(ApiOrderService.class);
    @Autowired
    private ApiProductMapper apiProductMapper;
    @Autowired
    private ApiCartMapper apiCartMapper;
    @Autowired
    private ApiOrderMapper apiOrderMapper;
    @Autowired
    private ApiOrderGoodsMapper apiOrderGoodsMapper;
    @Autowired
    private ApiUserCouponMapper apiUserCouponMapper;
    @Autowired
    private TemplateConfDao apiTemplateConfMapper;
    @Autowired
    private ApiUserMapper apiUserMapper;
    @Autowired
    private FormIdsService formIdsService;
    @Autowired
    private ApiGoodsMapper apiGoodsMapper;
    @Autowired
    private ApiFreightService apiFreightService;
    @Autowired
    private ApiOrderProcessRecordMapper orderProcessRecordMapper;
    @Autowired
    private ApiStoreMapper apiStoreMapper;
    @Autowired
    private ApiMerchMapper apiMerchMapper;
    @Autowired
    private ApiMngChangeMapper apiMngChangeMapper;
    @Autowired
    private ApiStoreMngChangeMapper apiStoreMngChangeMapper;
    @Autowired
    private ApiMkStorePromMapper apiMkStorePromMapper;
    @Autowired
    private ApiMkStorePromStatService apiMkStorePromStatService;
    @Autowired
    private ApiMkStoreTicketDiscountMapper apiMkStoreTicketDiscountMapper;
    @Autowired
    private ApiCartService cartService;
    @Autowired
    private ApiMkStoreTopicStatService apiMkStoreTopicStatService;
    @Autowired
    private ApiMkStoreCampMinusMapper apiMkStoreCampMinusMapper;
    @Autowired
    private ApiUserCampMinusMapper apiUserCampMinusMapper;
    @Autowired
    private ApiFaceLivenessRecognitionReturnDataMapper apiFaceLivenessRecognitionReturnDataMapper;
    @Autowired
    private ApiSysConfigMapper apiSysConfigMapper;

    public OrderVo queryObject(Long id) {
        return apiOrderMapper.queryObject(id);
    }

    public OrderVo queryObjectByOrderSn(String order_sn) {
        return apiOrderMapper.queryObjectByOrderSn(order_sn);
    }

    public Map queryUcenterMap(Map<String, Object> map) {
        Map queryMap = apiOrderMapper.queryUcenterMap(map);
        String value = apiSysConfigMapper.queryByKey("IS_QUERY_CROSS_QUOTAL");
        queryMap.put("isQueryCrossQuotal", value);
        return queryMap;
    }


    public List<OrderVo> queryList(Map<String, Object> map) {
        return apiOrderMapper.queryList(map);
    }


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

    public void save(OrderVo order) {
        apiOrderMapper.save(order);
    }

    @Transactional
    public void cancelOrder(Long userId, OrderVo order) {
        Map orderGoodsParam = Maps.newHashMap();
        orderGoodsParam.put("order_id", order.getId());
        String userName = "";
        if(userId != null){
            UserVo userVo = apiUserMapper.queryObject(userId);
            userName = userVo != null ? userVo.getUsername():"";
        }
        //订单的商品
        List<OrderGoodsVo> goodsList = apiOrderGoodsMapper.queryList(orderGoodsParam);
        for (OrderGoodsVo orderGoodsVo : goodsList) {
            ProductVo productInfo = apiProductMapper.queryByStoreId(orderGoodsVo.getProduct_id(), order.getStore_id());

            GoodsVo goodsInfo = apiGoodsMapper.queryObjectByStoreId(orderGoodsVo.getGoods_id(), order.getStore_id());
            if (null == goodsInfo || goodsInfo.getIs_delete() == 1 || goodsInfo.getIs_on_sale() == 0) {
                throw new RRException("订单提交失败：商品不存在");
            }
            //普通、门店商品不受共享库存影响，直接取门店配置库存
//            Integer stockNum = StockUtil.setStockNumByGoodsVo(goodsInfo);
            String isStockShare = StockUtil.getIsStockShareByGoodsVo(goodsInfo);
            //还原商户商品总库存
            resetGoodsStock(goodsInfo.getGoods_number(), productInfo, goodsInfo, orderGoodsVo, userName);
            //该商品所属第三方商户不是共享库存
            if(isStockShare.equalsIgnoreCase(Dict.isStockShare.item_0.getItem())) {
                resetStoreGoodsStock(goodsInfo.getStockNum(), productInfo, goodsInfo, orderGoodsVo, userName);//还原门店库存
            }else{
                //该商品所属第三方商户是共享库存，但商品业务类型不是00保税备货
                if(!goodsInfo.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_00.getItem())){
                    resetStoreGoodsStock(goodsInfo.getStockNum(), productInfo, goodsInfo, orderGoodsVo, userName);//还原门店库存
                }
            }
            //该商品所属第三方商户为共享库存，且是保税备货商品，取消订单时改变
            updateGoodsByIsShareStock(isStockShare, goodsInfo);
        }
        update(order);
        // 判断是否有优惠券
        UserCouponVo couponVo = apiUserCouponMapper.queryByOrderId(order.getId());
        if (null != couponVo) {
            apiUserCouponMapper.cancelOrder(couponVo);
        }
        //释放促销满减券
        UserCampMinusVo userCampMinusVo = apiUserCampMinusMapper.queryUserCampByOrderId(order.getId());
        if (null != userCampMinusVo) {
            apiUserCampMinusMapper.cancelUserCampOrder(userCampMinusVo);
        }
    }

    /**
     * 还原商户商品总库存
     */
    private void resetGoodsStock(Integer stockNum, ProductVo productInfo, GoodsVo goodsInfo, OrderGoodsVo orderGoodsVo, String userName){
        stockNum = stockNum == null? 0 : stockNum;
        goodsInfo.setGoods_number(stockNum + orderGoodsVo.getNumber());
//                    goodsInfo.setSell_volume(goodsInfo.getGoods_sell_volume() - orderGoodsVo.getNumber());
        apiGoodsMapper.updateGoodsStock(goodsInfo);

//        productInfo.setSell_volume(productInfo.getSell_volume() - orderGoodsVo.getNumber());
//        productInfo.setGoods_id(goodsInfo.getId());
//        apiProductMapper.updateStockNum(productInfo);

        MngChangeVo mngChangeVo = new MngChangeVo();
        mngChangeVo.setGoodsId(Integer.parseInt(String.valueOf(goodsInfo.getId())));
        mngChangeVo.setThirdPartyMerchCode(goodsInfo.getThirdPartyMerchCode());
        mngChangeVo.setChangeReason("小程序取消订单");
        mngChangeVo.setChangeType(Dict.changeType.item_0.getItem());
        mngChangeVo.setChangeNum(orderGoodsVo.getNumber());//变化数
        mngChangeVo.setOriginalNum(stockNum);//原库存数
        mngChangeVo.setValidNum(stockNum + orderGoodsVo.getNumber());//可用数
        mngChangeVo.setCreateTime(new Date());
        mngChangeVo.setModTime(new Date());
        mngChangeVo.setCreaterSn("小程序用户"+userName);
        mngChangeVo.setModerSn("小程序用户"+userName);
        mngChangeVo.setIsValid(0);
        mngChangeVo.setMerchSn(goodsInfo.getMerchSn());
        apiMngChangeMapper.save(mngChangeVo);
    }

    /**
     * 还原门店商品库存
     */
    private void resetStoreGoodsStock(Integer stockNum, ProductVo productInfo, GoodsVo goodsInfo, OrderGoodsVo orderGoodsVo, String userName){
        stockNum = stockNum == null? 0 : stockNum;

        productInfo.setStock_num(stockNum + orderGoodsVo.getNumber());
        productInfo.setGoods_id(goodsInfo.getId());
        productInfo.setSell_volume(productInfo.getSell_volume() - orderGoodsVo.getNumber());
        apiProductMapper.updateStockNum(productInfo);

        StoreMngChangeVo storeMngChangeVo = new StoreMngChangeVo();
        storeMngChangeVo.setChangeType(Dict.changeType.item_0.getItem());
        storeMngChangeVo.setChangeReason("小程序取消订单");
        storeMngChangeVo.setGoodsId(Integer.parseInt(String.valueOf(goodsInfo.getId())));
        storeMngChangeVo.setStoreId(Integer.parseInt(String.valueOf(productInfo.getStore_id())));
        storeMngChangeVo.setMerchSn(goodsInfo.getMerchSn());
        storeMngChangeVo.setStoreChangeNum(orderGoodsVo.getNumber());
        storeMngChangeVo.setStoreOriginalNum(stockNum);
        storeMngChangeVo.setStoreValidNum(stockNum + orderGoodsVo.getNumber());
        storeMngChangeVo.setCreateTime(new Date());
        storeMngChangeVo.setModTime(new Date());
        storeMngChangeVo.setCreaterSn("小程序用户"+userName);
        storeMngChangeVo.setModerSn("小程序用户"+userName);
        storeMngChangeVo.setIsValid(0);
        apiStoreMngChangeMapper.save(storeMngChangeVo);
    }

    public void update(OrderVo order) {
        order.setIsScan("0");
        order.setModTime(new Date());
        apiOrderMapper.update(order);
    }

    public void updateOrderByMerchOrderSn(OrderVo order) {
        apiOrderMapper.updateOrderByMerchOrderSn(order);
    }

    public void updateBatch(List<OrderVo> list) {
        for (OrderVo order : list) {
            order.setIsScan("0");
            order.setModTime(new Date());
        }
        apiOrderMapper.updateBatch(list);
    }

    public void delete(Integer id) {
        apiOrderMapper.delete(id);
    }


    public void deleteBatch(Integer[] ids) {
        apiOrderMapper.deleteBatch(ids);
    }

    @Transactional
    public Map submit(JSONObject jsonParam, UserVo loginUser, Long storeId) {
        Map resultObj = Maps.newHashMap();
        AddressVo addressVo = jsonParam.getObject("checkedAddress", AddressVo.class);
        if (addressVo == null) {
            resultObj.put("errno", 400);
            resultObj.put("errmsg", "地址不能为空");
            return resultObj;
        }
        String formId = jsonParam.getString("formId");
        String idNo = jsonParam.getString("idNo");
        String userName = jsonParam.getString("userName");
        String postscript00 = jsonParam.getString("postscript00");
        String postscript02 = jsonParam.getString("postscript02");
        String postscript10 = jsonParam.getString("postscript10");
        String postscript11 = jsonParam.getString("postscript11");//留言备注
        String checkCart = jsonParam.getString("checkCart");//业务区分，11为普通商品，00为保税商品
        Integer tickDiscId00 = jsonParam.getInteger("tickDiscId00");//优惠券id
        Integer tickDiscId02 = jsonParam.getInteger("tickDiscId02");//优惠券id
        Integer tickDiscId10 = jsonParam.getInteger("tickDiscId10");//优惠券id
        Integer tickDiscId11 = jsonParam.getInteger("tickDiscId11");//优惠券id
        Integer campId00 = jsonParam.getInteger("campId00");//促销id
        Integer campId02 = jsonParam.getInteger("campId02");//促销id
        Integer campId10 = jsonParam.getInteger("campId10");//促销id
        Integer campId11 = jsonParam.getInteger("campId11");//促销id
        Integer isLoadStatus = jsonParam.getInteger("isLoadStatus");
        Integer number = jsonParam.getInteger("number");
        Long goodsId = jsonParam.getLong("goodsId");
        UserVo user = apiUserMapper.queryObjectByIdNoAndName(idNo, userName);
        UserVo userVo = new UserVo();
        userVo.setId(loginUser.getId());
        userVo.setIdNo(idNo);
        userVo.setUsername(userName);
        logger.info("param userId："+ loginUser.getId());
        logger.info("param idNo："+ userVo.getIdNo());
        logger.info("param userName："+ userVo.getUsername());
        if(user != null){
            logger.info("query userId："+ user.getId());
            if(loginUser.getId().compareTo(user.getId()) != 0){
                logger.info("该身份证信息已被绑定，登陆用户："+ user.getId()+"，查询用户："+ user.getId());
                resultObj.put("errno", 400);
                resultObj.put("errmsg", "该身份证信息已被绑定");
                return resultObj;
            }
            //已被当前用户绑定过，且没被占用的身份证信息不需要再次实名认证
            apiUserMapper.update(userVo);
        }else{
            //如没被任何人绑定过，新用户绑定则进行实名认证身份证信息，认证成功更新到用户表
            String result = IdCardUtil.checkIdCard(userVo.getIdNo(), userVo.getUsername());
            IdCardMsgVo vo = JSON.parseObject(result,IdCardMsgVo.class);
            if(vo.getRespCode().equalsIgnoreCase("0000")){
                apiUserMapper.update(userVo);
            }else{
                logger.info(vo.getRespMessage());
                resultObj.put("errno", 400);
                resultObj.put("errmsg", vo.getRespMessage());
                return resultObj;
            }
        }
        CheckOutDto checkOutDto = new CheckOutDto();
        checkOutDto.setCheckCart(checkCart);
        //商品id不为空，则提交订单是从商品详情页立即购买过来的
        if(goodsId != null){
            checkOutDto.setGoodsId(goodsId);
            checkOutDto.setNumber(number);
        }
        checkOutDto.setLoginUser(loginUser);
        if(tickDiscId00 != null){
            checkOutDto.setTickDiscId00(Long.valueOf(tickDiscId00));
        }
        if(tickDiscId02 != null){
            checkOutDto.setTickDiscId02(Long.valueOf(tickDiscId02));
        }
        if(tickDiscId10 != null){
            checkOutDto.setTickDiscId10(Long.valueOf(tickDiscId10));
        }
        if(tickDiscId11 != null){
            checkOutDto.setTickDiscId11(Long.valueOf(tickDiscId11));
        }
        if(campId00 != null){
            checkOutDto.setCampId00(campId00);
        }
        if(campId02 != null){
            checkOutDto.setCampId02(campId02);
        }
        if(campId10 != null){
            checkOutDto.setCampId10(campId10);
        }
        if(campId11 != null){
            checkOutDto.setCampId11(campId11);
        }
        checkOutDto.setIsLoadStatus(isLoadStatus);
        checkOutDto.setStoreId(storeId);
        //获取要购买的商品
        Map<String, Object> cartData = cartService.getCartMoney(loginUser, checkOutDto, storeId);
        List<CartVo> checkedGoodsList = (List<CartVo>) cartData.get("cartList");
//        Map param = Maps.newHashMap();
//        param.put("user_id", loginUser.getId());
//        param.put("store_id", storeId);
//        param.put("checked", 1);
//        param.put("checkCart", checkCart);
//        List<CartVo> checkedGoodsList = apiCartMapper.queryList(param);
        if (null == checkedGoodsList) {
            resultObj.put("errno", 400);
            resultObj.put("errmsg", "请选择商品");
            logger.error("请选择商品");
            return resultObj;
        }

        checkOutDto.setCartData(cartData);
        Map<String, Object> cartResultObj = cartService.getCheckOut(checkOutDto);

        Boolean isBizType00 =  (Boolean) cartResultObj.get("isBizType00");
        Boolean isBizType02 =  (Boolean) cartResultObj.get("isBizType02");
        Boolean isBizType10 =  (Boolean) cartResultObj.get("isBizType10");
        Boolean isBizType11 =  (Boolean) cartResultObj.get("isBizType11");

        // 检查库存和更新库存
        checkStock(checkedGoodsList, storeId, userName);

        List<OrderVo> orderInfoList = new ArrayList();
        String merchOrderSn = "EMATO" + CommonUtil.generateOrderNumber();
        //订单按业务类型进行分单
        if(isBizType00){
            OrderVo order00 = setOrderVo(jsonParam, loginUser, storeId, cartResultObj, Dict.orderBizType.item_00.getItem());
            order00.setOrderBizType(Dict.orderBizType.item_00.getItem());
            order00.setMerchOrderSn(merchOrderSn);
            if(org.apache.commons.lang.StringUtils.isNotEmpty(postscript00)) {
                order00.setPostscript(postscript00);
            }
            orderInfoList.add(order00);
        }
        if(isBizType02){
            OrderVo order02 = setOrderVo(jsonParam, loginUser, storeId, cartResultObj, Dict.orderBizType.item_02.getItem());
            order02.setOrderBizType(Dict.orderBizType.item_02.getItem());
            order02.setMerchOrderSn(merchOrderSn);
            if(org.apache.commons.lang.StringUtils.isNotEmpty(postscript02)) {
                order02.setPostscript(postscript02);
            }
            orderInfoList.add(order02);
        }
        if(isBizType10){
            OrderVo order10 = setOrderVo(jsonParam, loginUser, storeId, cartResultObj, Dict.orderBizType.item_10.getItem());
            order10.setOrderBizType(Dict.orderBizType.item_10.getItem());
            order10.setMerchOrderSn(merchOrderSn);
            if(org.apache.commons.lang.StringUtils.isNotEmpty(postscript10)) {
                order10.setPostscript(postscript10);
            }
            orderInfoList.add(order10);
        }
        if(isBizType11){
            OrderVo order11 = setOrderVo(jsonParam, loginUser, storeId, cartResultObj, Dict.orderBizType.item_11.getItem());
            order11.setOrderBizType(Dict.orderBizType.item_11.getItem());
            order11.setMerchOrderSn(merchOrderSn);
            if(org.apache.commons.lang.StringUtils.isNotEmpty(postscript11)) {
                order11.setPostscript(postscript11);
            }
            orderInfoList.add(order11);
        }

        //开启事务，插入订单信息和订单商品
        if(orderInfoList != null && orderInfoList.size() > 0) {
            Boolean isOrderBizType10 = false;//订单中是否有保税展示跨境商品
            List<String> orderSnList = new ArrayList<>();
            apiOrderMapper.saveBatch(orderInfoList);

            List<OrderProcessRecordEntity> processRecordEntityList = new ArrayList<>();
            for (OrderVo orderInfo : orderInfoList) {
                if (null == orderInfo.getId()) {
                    logger.error("订单提交失败");
                    throw new RRException("订单提交失败");
                }
                //新增订单详情
                for (CartVo goodsItem : checkedGoodsList) {
                    //统计商品总价
                    if (orderInfo.getOrderBizType().equalsIgnoreCase(goodsItem.getGoodsBizType())) {
                        if(Dict.orderBizType.item_10.getItem().equalsIgnoreCase(goodsItem.getGoodsBizType())){
                            isOrderBizType10 = true;//订单中是否有保税展示跨境商品
                            orderSnList.add(orderInfo.getOrder_sn());
                        }
                        GoodsVo goodsVo = apiGoodsMapper.queryObjectByStoreId(goodsItem.getGoods_id(), storeId);
                        if (goodsVo == null) {
                            logger.error("订单提交失败：商品不存在");
                            throw new RRException("订单提交失败：商品不存在");
                        }
                        OrderGoodsVo orderGoodsVo = setOrderGoodsVo(orderInfo, cartResultObj, goodsItem, goodsVo);
                        apiOrderGoodsMapper.save(orderGoodsVo);
                        //购物车id为空，则提交订单是从商品详情页立即购买过来的
                        if(goodsItem.getId() == null){
                            //获取渠道信息
                            MkStorePromVo mkStorePromVo = apiMkStorePromMapper.queryObjectByGoodsIdAndStoreId(Integer.parseInt(String.valueOf(goodsItem.getGoods_id())),
                                    Integer.parseInt(String.valueOf(storeId)));
                            if(mkStorePromVo != null){
                                MkStorePromStatVo statVo = apiMkStorePromStatService.queryObjectByPromId(mkStorePromVo.getPromId());
                                if(statVo != null){//更新渠道追踪统计下单量数据
                                    apiMkStorePromStatService.updateStorePromStat(orderGoodsVo, orderInfo, loginUser, statVo);
                                }
                            }
                        }else {
                            Integer cartId = Integer.parseInt(String.valueOf(goodsItem.getId()));
                            //更新渠道追踪统计下单量数据
                            apiMkStorePromStatService.updateMkStorePromStat(orderGoodsVo, orderInfo, loginUser, cartId);
                        }
                    }
                }
                if(orderInfo.getCoupon_id() != 0 && orderInfo.getCoupon_id()!= null) {
                    //记录优惠券活动营销统计下单量数据
                    apiMkStoreTopicStatService.saveTicketTopicStatBySubmitData(orderInfo.getCoupon_id());
                }

                if(orderInfo.getCampMinusId() != 0 && orderInfo.getCampMinusId()!= null) {
                    //记录促销满减活动营销统计下单量数据
                    apiMkStoreTopicStatService.saveCampTopicStatBySubmitData(orderInfo.getActivity_id(), orderInfo.getCampMinusId());
                }
                OrderProcessRecordEntity entity = new OrderProcessRecordEntity();
                entity.setOrderSn(orderInfo.getOrder_sn());
                entity.setUserId(Integer.valueOf(loginUser.getId()+""));
                entity.setAddOrderStartTime(orderInfo.getAdd_time());
                entity.setAddOrderSuccTime(orderInfo.getAdd_time());
                entity.setIsAddOrderSend(Dict.isSend.item_1.getItem());
                entity.setOrderBizType(orderInfo.getOrderBizType());
                processRecordEntityList.add(entity);
            }

            orderProcessRecordMapper.saveBatch(processRecordEntityList);//新增订单流转信息


            //商品id不为空，则提交订单是从商品详情页立即购买过来的
            if(goodsId == null) {
                //清空已购买的商品
                apiCartMapper.deleteByCart(loginUser.getId(), storeId, 1, checkCart);
            }

            if (apiOrderMapper.queryCountByMerchOrderSn(merchOrderSn) > 1) {//不止一笔订单则为拆单订单
                OrderVo orderVo = new OrderVo();
                orderVo.setIsMergePay("2");//多笔订单单笔支付
                orderVo.setMerchOrderSn(merchOrderSn);
                apiOrderMapper.updateOrderByMerchOrderSn(orderVo);
            }
            // formIds保存，已废弃_2020-1-10
            // formIdsService.save(loginUser.getId(), formId, 1, merchOrderSn);

            //保税展示跨境商品保存是否核验信息
            if(isOrderBizType10) {
                saveFaceData(merchOrderSn, orderSnList, userVo);
            }

            resultObj.put("errno", 0);
            resultObj.put("errmsg", "订单提交成功");
            //
            Map orderInfoMap = Maps.newHashMap();
            orderInfoMap.put("orderInfo", orderInfoList);
            orderInfoMap.put("isOrderBizType10", isOrderBizType10);
            resultObj.put("data", orderInfoMap);

            // 优惠券标记已用，或促销满减活动保存已用
            for (OrderVo orderInfo : orderInfoList) {
                if(orderInfo.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_00.getItem())){
                    updateCoupon(orderInfo);
                    saveUserCamp(orderInfo);
                }
                if(orderInfo.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_02.getItem())){
                    updateCoupon(orderInfo);
                    saveUserCamp(orderInfo);
                }
                if(orderInfo.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_10.getItem())){
                    updateCoupon(orderInfo);
                    saveUserCamp(orderInfo);
                }
                if(orderInfo.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_11.getItem())){
                    updateCoupon(orderInfo);
                    saveUserCamp(orderInfo);
                }
            }
        }
        return resultObj;
    }

    /**
     * 保税展示跨境商品保存是否核验信息
     * @param merchOrderSn
     * @param userVo
     */
    private void saveFaceData(String merchOrderSn, List<String> orderSnList, UserVo userVo){
        for(int i=0;i<orderSnList.size();i++) {
            FaceLivenessRecognitionReturnDataVo face = new FaceLivenessRecognitionReturnDataVo();
            face.setMerchOrderSn(merchOrderSn);
            face.setOrderSn(orderSnList.get(i));
            face.setUserId(Integer.parseInt(String.valueOf(userVo.getId())));
            face.setIsFaceCheck("0");
            face.setIsTempNoti("0");
            face.setCreateTime(new Date());
            apiFaceLivenessRecognitionReturnDataMapper.save(face);
        }
    }

    /**
     * 标记优惠券使用的订单id
     * @param orderInfo
     */
    private void updateCoupon(OrderVo orderInfo){
        if (null != orderInfo.getCoupon_id() && 0 != orderInfo.getCoupon_id()) {
            UserCouponVo userCouponVo = apiUserCouponMapper.queryObject(orderInfo.getCoupon_id());
            //如未使用
            if (null != userCouponVo && (null == userCouponVo.getOrderId() || 0 == userCouponVo.getOrderId())) {
                userCouponVo.setUsedTime(new Date());
                userCouponVo.setOrderId(orderInfo.getId());
                userCouponVo.setIsUsed(Dict.isUsed.item_1.getItem());
                apiUserCouponMapper.update(userCouponVo);
            }
        }
    }

    /**
     * 订单提交成功后，新增用户促销满减活动信息为已使用
     * @param orderInfo
     */
    private void saveUserCamp(OrderVo orderInfo){
        if (null != orderInfo.getActivity_id() && 0 != orderInfo.getActivity_id()) {
            UserCampMinusVo campMinusVo = apiUserCampMinusMapper.queryCampByStoreTopicId(orderInfo.getActivity_id());
            //如未使用
            if (null == campMinusVo) {
                UserCampMinusVo userCampMinusVo = new UserCampMinusVo();
                userCampMinusVo.setUsedTime(new Date());
                userCampMinusVo.setOrderId(Integer.parseInt(String.valueOf(orderInfo.getId())));
                userCampMinusVo.setIsUsed(Dict.isUsed.item_1.getItem());
                userCampMinusVo.setStoreTopicId(Integer.parseInt(String.valueOf(orderInfo.getActivity_id())));
                userCampMinusVo.setCreateTime(new Date());
                userCampMinusVo.setUserId(Integer.parseInt(String.valueOf(orderInfo.getUser_id())));
                apiUserCampMinusMapper.save(userCampMinusVo);
            }else {
                campMinusVo.setUsedTime(new Date());
                campMinusVo.setOrderId(Integer.parseInt(String.valueOf(orderInfo.getId())));
                campMinusVo.setIsUsed(Dict.isUsed.item_1.getItem());
                campMinusVo.setUserId(Integer.parseInt(String.valueOf(orderInfo.getUser_id())));
                apiUserCampMinusMapper.update(campMinusVo);
            }
        }
    }

    /**
     * 扣减商户商品总库存
     * @param goodsVo
     * @param goodsItem
     * @param userName
     */
    private void updateGoodsStock(GoodsVo goodsVo, CartVo goodsItem,String userName){
        goodsVo.setGoods_number(goodsVo.getGoods_number() - goodsItem.getNumber());
        goodsVo.setId(goodsVo.getId());
        apiGoodsMapper.updateGoodsStock(goodsVo);
//        //修改门店商品销量
//        productInfo.setSell_volume(productInfo.getSell_volume() + goodsItem.getNumber());
//        productInfo.setGoods_id(goodsVo.getId());
//        apiProductMapper.updateStockNum(productInfo);

        MngChangeVo mngChangeVo = new MngChangeVo();
        mngChangeVo.setGoodsId(Integer.parseInt(String.valueOf(goodsVo.getId())));
        mngChangeVo.setThirdPartyMerchCode(goodsVo.getThirdPartyMerchCode());
        mngChangeVo.setChangeReason("小程序购买商品");
        mngChangeVo.setChangeType(Dict.changeType.item_1.getItem());
        mngChangeVo.setChangeNum(goodsItem.getNumber());//变化数
        mngChangeVo.setOriginalNum(goodsVo.getGoods_number());//原库存数
        mngChangeVo.setValidNum(goodsVo.getGoods_number());//可用数
        mngChangeVo.setCreateTime(new Date());
        mngChangeVo.setModTime(new Date());
        mngChangeVo.setCreaterSn("小程序用户"+userName);
        mngChangeVo.setModerSn("小程序用户"+userName);
        mngChangeVo.setIsValid(0);
        mngChangeVo.setMerchSn(goodsVo.getMerchSn());
        apiMngChangeMapper.save(mngChangeVo);
    }

    /**
     * 扣减商户门店商品库存
     * @param productInfo
     * @param goodsVo
     * @param stockNum
     * @param goodsItem
     * @param storeId
     * @param userName
     */
    private void updateStock(ProductVo productInfo,GoodsVo goodsVo,Integer stockNum,CartVo goodsItem,Long storeId,String userName){
        //修改门店商品库存
        productInfo.setStock_num(stockNum - goodsItem.getNumber());
        productInfo.setStore_id(storeId);
        //修改门店商品销量
        productInfo.setSell_volume(productInfo.getSell_volume() + goodsItem.getNumber());
        productInfo.setGoods_id(goodsVo.getId());
        apiProductMapper.updateStockNum(productInfo);

        StoreMngChangeVo storeMngChangeVo = new StoreMngChangeVo();
        storeMngChangeVo.setChangeType(Dict.changeType.item_1.getItem());
        storeMngChangeVo.setChangeReason("小程序购买商品");
        storeMngChangeVo.setGoodsId(Integer.parseInt(String.valueOf(goodsVo.getId())));
        storeMngChangeVo.setStoreId(Integer.parseInt(String.valueOf(storeId)));
        storeMngChangeVo.setMerchSn(goodsVo.getMerchSn());
        storeMngChangeVo.setStoreChangeNum(goodsItem.getNumber());
        storeMngChangeVo.setStoreOriginalNum(stockNum);
        storeMngChangeVo.setStoreValidNum(productInfo.getStock_num());
        storeMngChangeVo.setCreateTime(new Date());
        storeMngChangeVo.setModTime(new Date());
        storeMngChangeVo.setCreaterSn("小程序用户"+userName);
        storeMngChangeVo.setModerSn("小程序用户"+userName);
        storeMngChangeVo.setIsValid(0);
        apiStoreMngChangeMapper.save(storeMngChangeVo);
    }

    /**
     * 更新商品库存数量变化后是否已共享为0“未共享”
     * @param isStockShare
     * @param goodsInfo
     */
    private void updateGoodsByIsShareStock(String isStockShare, GoodsVo goodsInfo){
        //该商品为共享库存，且是保税备货商品
        if(isStockShare.equalsIgnoreCase(Dict.isStockShare.item_1.getItem())
                && goodsInfo.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_00.getItem())) {
            GoodsVo goodsVo = new GoodsVo();
            goodsVo.setId(goodsInfo.getId());
            //商品库存数量变化后是否已共享,0：否，1：是(下单、退款、取消订单触发)
            goodsVo.setIsGoodsShareStock(Dict.isGoodsShareStock.item_0.getItem());
            apiGoodsMapper.updateByGoodsShareStock(goodsVo);
        }
    }

    /**
     * 检查库存和更新库存
     * @param checkedGoodsList
     * @param storeId
     * @param userName
     */
    private void checkStock(List<CartVo> checkedGoodsList,Long storeId,String userName){
        for (CartVo goodsItem : checkedGoodsList) {
            Integer stockNum = 0;
            //取得规格的信息,判断规格库存
            GoodsVo goodsInfo = apiGoodsMapper.queryObjectByStoreId(goodsItem.getGoods_id(), storeId);
            if (null == goodsInfo || goodsInfo.getIs_delete() == 1 || goodsInfo.getIs_on_sale() == 0) {
                logger.error("订单提交失败：商品不存在");
                throw new RRException("订单提交失败：商品不存在");
            }
            ProductVo productInfo = apiProductMapper.queryByStoreId(goodsItem.getProduct_id(), storeId);
            synchronized (productInfo){
                if (null == productInfo) {
                    logger.error("订单提交失败：商品已下架");
                    throw new RRException("订单提交失败：商品已下架");
                }
                String isStockShare = StockUtil.getIsStockShareByGoodsVo(goodsInfo);
                // TODO: 2019/3/5  普通商品不受共享库存影响，直接取门店配置库存
                stockNum = StockUtil.setStockNumByGoodsVo(goodsInfo);
                if (null == stockNum || stockNum < goodsItem.getNumber() || stockNum <= 0) {
                    logger.error("订单提交失败：库存不足，仅剩余" + stockNum);
                    throw new RRException("订单提交失败：库存不足，仅剩余" + stockNum);
                }else{
                    productInfo.setStore_id(storeId);
                    //扣减商户商品总库存
                    updateGoodsStock(goodsInfo, goodsItem, userName);
                    //该商品所属第三方商户不是共享库存
                    if(isStockShare.equalsIgnoreCase(Dict.isStockShare.item_0.getItem())) {
                        updateStock(productInfo, goodsInfo, stockNum, goodsItem, storeId, userName);//扣减门店库存
                    }else{
                        //该商品所属第三方商户是共享库存，但商品业务类型不是00保税备货
                        if(!goodsInfo.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_00.getItem())){
                            updateStock(productInfo, goodsInfo, stockNum, goodsItem, storeId, userName);//扣减门店库存
                        }
                    }
                    //该商品所属第三方商户为共享库存，且是保税备货商品，下单时改变，定时任务触发
                    updateGoodsByIsShareStock(isStockShare, goodsInfo);
                }
            }
        }
    }
    /**
     * 设置订单数据
     * @param jsonParam
     * @param loginUser
     * @param storeId
     * @param cartResultObj
     * @param bizType
     * @return
     */
    public OrderVo setOrderVo(JSONObject jsonParam, UserVo loginUser, Long storeId, Map<String, Object> cartResultObj, String bizType){
        OrderVo orderInfo = new OrderVo();
        Integer tickDiscId = 0;
        Integer campId = 0;
        Long couponId = 0L;
        Long storeTopicId = 0L;
        String campName = "";
        BigDecimal fullCutCouponDec = Constant.ZERO;
        BigDecimal cond = Constant.ZERO;
        BigDecimal money = Constant.ZERO;
        BigDecimal goodsTotalPrice = new BigDecimal(0.00);
        BigDecimal freightPrice = Constant.ZERO;
        //实付金额:商品销售价*数量-优惠金额+运费的总和
        BigDecimal actualPrice = new BigDecimal(0.00);
        CampMinusDto campMinusDto = new CampMinusDto();
        Integer tickDiscId00 = jsonParam.getInteger("tickDiscId00");//优惠券id
        Integer tickDiscId02 = jsonParam.getInteger("tickDiscId02");//优惠券id
        Integer tickDiscId10 = jsonParam.getInteger("tickDiscId10");//优惠券id
        Integer tickDiscId11 = jsonParam.getInteger("tickDiscId11");//优惠券id
        Integer campId00 = jsonParam.getInteger("campId00");//促销满减id
        Integer campId02 = jsonParam.getInteger("campId02");//促销满减id
        Integer campId10 = jsonParam.getInteger("campId10");//促销满减id
        Integer campId11 = jsonParam.getInteger("campId11");//促销满减id
        CampMinusDto campMinusDto00 = (CampMinusDto)cartResultObj.get("campMinusDto00");
        CampMinusDto campMinusDto02 = (CampMinusDto)cartResultObj.get("campMinusDto02");
        CampMinusDto campMinusDto10 = (CampMinusDto)cartResultObj.get("campMinusDto10");
        CampMinusDto campMinusDto11 = (CampMinusDto)cartResultObj.get("campMinusDto11");
        String postscript = jsonParam.getString("postscript");
        AddressVo addressVo = jsonParam.getObject("checkedAddress", AddressVo.class);
        Date delivery_date = jsonParam.getDate("delivery_date");
        String merchSn = (String)jsonParam.get("merchSn");
        String delivery_remark = jsonParam.getString("delivery_remark");
        BigDecimal freightPrice00 = MapUtils.getBigDecimal("freightPrice00", cartResultObj);
        BigDecimal freightPrice02 = MapUtils.getBigDecimal("freightPrice02", cartResultObj);
        BigDecimal freightPrice10 = MapUtils.getBigDecimal("freightPrice10", cartResultObj);
        BigDecimal freightPrice11 = MapUtils.getBigDecimal("freightPrice11", cartResultObj);
        BigDecimal goodsTotalPrice00 = MapUtils.getBigDecimal("goodsTotalPrice00", cartResultObj);
        BigDecimal goodsTotalPrice02 = MapUtils.getBigDecimal("goodsTotalPrice02", cartResultObj);
        BigDecimal goodsTotalPrice10 = MapUtils.getBigDecimal("goodsTotalPrice10", cartResultObj);
        BigDecimal goodsTotalPrice11 = MapUtils.getBigDecimal("goodsTotalPrice11", cartResultObj);
        //实付金额:商品销售价*数量-优惠金额+运费的总和
        BigDecimal actualPrice00 = MapUtils.getBigDecimal("actualPrice00", cartResultObj);
        BigDecimal actualPrice02 = MapUtils.getBigDecimal("actualPrice02", cartResultObj);
        BigDecimal actualPrice10 = MapUtils.getBigDecimal("actualPrice10", cartResultObj);
        BigDecimal actualPrice11 = MapUtils.getBigDecimal("actualPrice11", cartResultObj);
        if(bizType.equalsIgnoreCase(Dict.orderBizType.item_00.getItem())){
            tickDiscId = tickDiscId00;
            freightPrice = freightPrice00;
            goodsTotalPrice = goodsTotalPrice00;
            actualPrice = actualPrice00;
            campId = campId00;
            campMinusDto = campMinusDto00;
        }
        if(bizType.equalsIgnoreCase(Dict.orderBizType.item_02.getItem())){
            tickDiscId = tickDiscId02;
            freightPrice = freightPrice02;
            goodsTotalPrice = goodsTotalPrice02;
            actualPrice = actualPrice02;
            campId = campId02;
            campMinusDto = campMinusDto02;
        }
        if(bizType.equalsIgnoreCase(Dict.orderBizType.item_10.getItem())){
            tickDiscId = tickDiscId10;
            freightPrice = freightPrice10;
            goodsTotalPrice = goodsTotalPrice10;
            actualPrice = actualPrice10;
            campId = campId10;
            campMinusDto = campMinusDto10;
        }
        if(bizType.equalsIgnoreCase(Dict.orderBizType.item_11.getItem())){
            tickDiscId = tickDiscId11;
            freightPrice = freightPrice11;
            goodsTotalPrice = goodsTotalPrice11;
            actualPrice = actualPrice11;
            campId = campId11;
            campMinusDto = campMinusDto11;
        }
//        goodsTotalPrice = MapUtils.getBigDecimal("goodsTotalPrice", cartResultObj);//整个订单商品总价，不包含运费和优惠金额
        MkStoreTicketDiscountVo mkStoreTicketDiscountVo = null;
        if (null != tickDiscId && 0 != tickDiscId && campId == 0) {
            //校验该订单所选的优惠券
            mkStoreTicketDiscountVo = apiMkStoreTicketDiscountMapper.queryObject(tickDiscId);
            if(mkStoreTicketDiscountVo != null) {
                if (mkStoreTicketDiscountVo.getTickDiscType().equalsIgnoreCase(Dict.tickDiscType.item_00.getItem())) {
                    cond = mkStoreTicketDiscountVo.getVoucherCond();
                    money = mkStoreTicketDiscountVo.getVoucherMoney();
                }
                if (mkStoreTicketDiscountVo.getTickDiscType().equalsIgnoreCase(Dict.tickDiscType.item_01.getItem())) {
                    cond = mkStoreTicketDiscountVo.getDiscCond();
                    money = mkStoreTicketDiscountVo.getDiscRatio();//满多少打几折
                }
                // TODO: 2019/5/21 代金券暂时无用
                /*if (mkStoreTicketDiscountVo.getTickDiscType().equalsIgnoreCase(Dict.tickDiscType.item_02.getItem())) {
                    cond = mkStoreTicketDiscountVo.getExchCond();
                    money = mkStoreTicketDiscountVo.getExchCond();
                }*/
            }
        }

        String couponName = "";
        UserCouponVo couponVo = null;
        //扣减金额
        BigDecimal couponPrice = new BigDecimal(0.00);
        if (null != tickDiscId && 0 != tickDiscId && campId == 0) {
            //查询未使用且未过期的优惠券
            List<UserCouponVo> couponVoList = apiUserCouponMapper.queryObjectByIdAndUsed(tickDiscId, loginUser.getId());
            if(couponVoList!= null && couponVoList.size() > 0){
                couponVo = couponVoList.get(0);
            }
            if (null != couponVo && null != couponVo.getTypeMoney()) {
                //判断不同业务的订单总金额是否满足优惠条件，满足则标记该订单已使用优惠券
                if(goodsTotalPrice.compareTo(cond) >= 0){
                    //标记该订单已使用优惠券
                    if(couponVo != null){
                        couponVo.setUsedTime(new Date());
                        couponVo.setIsUsed(Dict.isUsed.item_1.getItem());
                        apiUserCouponMapper.update(couponVo);
                        if(mkStoreTicketDiscountVo != null) {
                            if (mkStoreTicketDiscountVo.getTickDiscType().equalsIgnoreCase(Dict.tickDiscType.item_00.getItem())) {
                                couponPrice = money;
                            }
                            if (mkStoreTicketDiscountVo.getTickDiscType().equalsIgnoreCase(Dict.tickDiscType.item_01.getItem())) { //折扣
                                //商品销售价 - 扣减优惠折扣金额后的实付金额 = 订单优惠金额
                                couponPrice = goodsTotalPrice.subtract(actualPrice);
                            }
                            // TODO: 2019/5/21 代金券暂时无用
                            /*if (mkStoreTicketDiscountVo.getTickDiscType().equalsIgnoreCase(Dict.tickDiscType.item_02.getItem())) {
                                cond = mkStoreTicketDiscountVo.getExchCond();
                                money = mkStoreTicketDiscountVo.getExchCond();
                            }*/
                        }
                        couponId = couponVo.getId();
                        couponName = couponVo.getCouponName();
                        Map map = apiUserCouponMapper.queryStoreTopicByDictId(tickDiscId);
                        storeTopicId = MapUtils.getLong("storeTopicId", map);
                    }
                }else{
                    couponId = 0L;
                    storeTopicId = 0L;
                }
            }
        }

        MkStoreCampMinusVo mkStoreCampMinusVo = null;
        if(null != campId && 0 != campId){
            mkStoreCampMinusVo = apiMkStoreCampMinusMapper.queryObject(campId);
            if(mkStoreCampMinusVo != null) {
                storeTopicId = Long.valueOf(mkStoreCampMinusVo.getStoreTopicId());
                campName = mkStoreCampMinusVo.getCampName();
                if (mkStoreCampMinusVo.getCampMinusType().equalsIgnoreCase(Dict.campMinusType.item_00.getItem()) || mkStoreCampMinusVo.getCampMinusType().equalsIgnoreCase(Dict.campMinusType.item_01.getItem())) {
                    fullCutCouponDec = campMinusDto.getMoney();
                }
                if (mkStoreCampMinusVo.getCampMinusType().equalsIgnoreCase(Dict.campMinusType.item_10.getItem()) || mkStoreCampMinusVo.getCampMinusType().equalsIgnoreCase(Dict.campMinusType.item_11.getItem())) {
                    //商品销售价 - 扣减优惠折扣金额后的实付金额 = 订单优惠金额
                    fullCutCouponDec = goodsTotalPrice.subtract(actualPrice);
                }
            }
        }

        if (null == delivery_date) {
            delivery_date = new Date();
        }
        if (StringUtils.isNullOrEmpty(delivery_remark)) {
            delivery_remark = "尽快送达";
        }

        //订单价格计算：订单的总价+运费
        BigDecimal orderTotalPrice = goodsTotalPrice.add(freightPrice);
//        BigDecimal orderTotalPrice = MapUtils.getBigDecimal("orderTotalPrice", cartResultObj);
//        actualPrice = cartService.mathActualPrice(couponVo, actualPrice);
//        BigDecimal actualPrice = orderTotalPrice.subtract(fullCutCouponDec).subtract(couponPrice);

        String thirdMerchSn = "";
        StoreVo storeVo = apiStoreMapper.queryObject(storeId);
        if(storeVo != null){
            thirdMerchSn = storeVo.getThirdPartyMerchCode()==null?"":storeVo.getThirdPartyMerchCode();
        }
        //一级商户 + 三级商户(拼音首字母) + 业务类型 + 编号
        String orderSn = "ZW" + thirdMerchSn + bizType + CommonUtil.generateOrderNumber();
        orderInfo.setOrder_sn(orderSn);
        orderInfo.setMerchSn(merchSn);
        orderInfo.setUser_id(loginUser.getId());
        //收货地址和运费
        orderInfo.setConsignee(addressVo.getUserName());
        orderInfo.setMobile(addressVo.getTelNumber());
        orderInfo.setCountry(addressVo.getNationalCode());
        orderInfo.setProvince(addressVo.getProvinceName());
        orderInfo.setCity(addressVo.getCityName());
        orderInfo.setDistrict(addressVo.getCountyName());
        orderInfo.setAddress(addressVo.getDetailInfo());
        orderInfo.setAddress_id(addressVo.getId());
        orderInfo.setDelivery_date(delivery_date);
        orderInfo.setDelivery_remark(delivery_remark);
        orderInfo.setStore_id(storeId);
        orderInfo.setFreight_price(freightPrice.intValue());

        orderInfo.setCoupon_id(Integer.parseInt(String.valueOf(couponId)));
        orderInfo.setCoupon_price(couponPrice);
        orderInfo.setCoupon_name(couponName);
        orderInfo.setActivity_id(storeTopicId);

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

        //留言
        orderInfo.setPostscript(postscript);
        orderInfo.setAdd_time(new Date());
        orderInfo.setGoods_price(goodsTotalPrice);
        orderInfo.setOrder_price(orderTotalPrice);
        orderInfo.setActual_price(actualPrice);
        orderInfo.setOrder_type("1");
        // 待付款
        orderInfo.setOrder_status(0);
        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");//默认未扫描
        UserVo userVo = apiUserMapper.queryObject(orderInfo.getUser_id());

        orderInfo.setPayMobile(userVo.getMobile());
        orderInfo.setPay_name(userVo.getUsername());
        orderInfo.setIsOnfflineOrder(Dict.isOnfflineOrder.item_0.getItem());

        return orderInfo;
    }

    public OrderGoodsVo setOrderGoodsVo(OrderVo orderInfo,Map<String, Object> cartResultObj,CartVo goodsItem,GoodsVo goodsVo){
        OrderGoodsVo orderGoodsVo = new OrderGoodsVo();
        orderGoodsVo.setOrder_id(orderInfo.getId());
        orderGoodsVo.setGoods_id(goodsItem.getGoods_id());
        orderGoodsVo.setGoods_sn(goodsItem.getGoods_sn());
        orderGoodsVo.setProduct_id(goodsItem.getProduct_id());
        orderGoodsVo.setGoods_name(goodsItem.getGoods_name());
        orderGoodsVo.setList_pic_url(goodsItem.getList_pic_url());
        orderGoodsVo.setMarket_price(goodsItem.getMarket_price());
        orderGoodsVo.setRetail_price(goodsItem.getRetail_price());
        orderGoodsVo.setNumber(goodsItem.getNumber());
        orderGoodsVo.setGoods_specification_name_value(goodsItem.getGoods_specification_name_value());
        orderGoodsVo.setGoods_specification_ids(goodsItem.getGoods_specification_ids());
        orderGoodsVo.setOrderBizType(goodsItem.getGoodsBizType());
        orderGoodsVo.setCreateTime(new Date());
        orderGoodsVo.setModTime(new Date());
        CampMinusDto campMinusDto = new CampMinusDto();
        UserCouponVo userCouponVo = new UserCouponVo();
        CampMinusDto campMinusDto00 = (CampMinusDto)cartResultObj.get("campMinusDto00");
        CampMinusDto campMinusDto02 = (CampMinusDto)cartResultObj.get("campMinusDto02");
        CampMinusDto campMinusDto10 = (CampMinusDto)cartResultObj.get("campMinusDto10");
        CampMinusDto campMinusDto11 = (CampMinusDto)cartResultObj.get("campMinusDto11");
        UserCouponVo checkedCoupon00 = (UserCouponVo)cartResultObj.get("checkedCoupon00");
        UserCouponVo checkedCoupon02 = (UserCouponVo)cartResultObj.get("checkedCoupon02");
        UserCouponVo checkedCoupon10 = (UserCouponVo)cartResultObj.get("checkedCoupon10");
        UserCouponVo checkedCoupon11 = (UserCouponVo)cartResultObj.get("checkedCoupon11");
        if(goodsVo.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_00.getItem())){
            if(campMinusDto00 != null){
                campMinusDto = campMinusDto00;
                userCouponVo = checkedCoupon00;
            }
        }
        if(goodsVo.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_02.getItem())){
            if(campMinusDto02 != null){
                campMinusDto = campMinusDto02;
                userCouponVo = checkedCoupon02;
            }
        }
        if(goodsVo.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_10.getItem())){
            if(campMinusDto10 != null){
                campMinusDto = campMinusDto10;
                userCouponVo = checkedCoupon10;
            }
        }
        if(goodsVo.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_11.getItem())){
            if(campMinusDto11 != null){
                campMinusDto = campMinusDto11;
                userCouponVo = checkedCoupon11;
            }
        }

        if(campMinusDto != null){
            List<Integer> goodsList = campMinusDto.getGoodsIds();
            if(goodsList != null) {
                for (Integer goodsId : goodsList) {
                    if (goodsId == Integer.parseInt(String.valueOf(goodsVo.getId()))) {
                        orderGoodsVo.setStoreTopicId(Integer.parseInt(String.valueOf(orderInfo.getActivity_id())));
                    }
                }
            }
        }
        if(userCouponVo != null){
            List<Integer> goodsList = userCouponVo.getGoodsList();
            if(goodsList != null) {
                for (Integer goodsId : goodsList) {
                    if (goodsId == Integer.parseInt(String.valueOf(goodsVo.getId()))) {
                        orderGoodsVo.setStoreTopicId(Integer.parseInt(String.valueOf(orderInfo.getActivity_id())));
                    }
                }
            }
        }
        orderGoodsVo.setGoodsRate(goodsVo.getGoodsRate());

        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);//商品结算平摊价格
        }
        orderGoodsVo.setSku(goodsVo.getSku());
        return orderGoodsVo;
    }
    /**
     * 支付成功通知
     */
    @Transactional
    public void notifyPaySuccess(OrderVo orderInfo) {
        WxTemplate tem = new WxTemplate();
        //查询formid，发送支付成功通知，暂无开放
        FormIdsEntity formIdsEntity = formIdsService.getFormIdsByMerchOrderSn(orderInfo.getMerchOrderSn());
        if (null == formIdsEntity || !StringUtils.isNotEmpty(formIdsEntity.getFormId())) {
            return;
        }
        if (orderInfo.getOrder_type().equals("1")) { // 订单类型 1：普通订单 2：团购订单
            TemplateConfVo templateConfVo = apiTemplateConfMapper.queryByTypeId(1); //  模板类型 1订单付款成功 2团购成功 3拼团失败通知 4拼团进度 5 6 7订单配送 8订单评价提醒
            if (null == templateConfVo) {
                return;
            }
            UserVo userVo = apiUserMapper.queryObject(orderInfo.getUser_id());

            tem.setTemplate_id(templateConfVo.getTemplateId());
//            tem.setTopcolor("#00DD00");
            tem.setTouser(userVo.getWeixin_openid());
            tem.setPage("/pages/ucenter/orderDetail/orderDetail?id=" + orderInfo.getId());
            tem.setForm_id(formIdsEntity.getFormId());

            List<TemplateData> paras = new ArrayList<TemplateData>();
            paras.add(new TemplateData("first", templateConfVo.getDesc(), "#000000"));
            paras.add(new TemplateData("keyword1", orderInfo.getMerchOrderSn(), "#000000"));

            //订单的商品
            Map orderGoodsParam = Maps.newHashMap();
            orderGoodsParam.put("order_id", orderInfo.getId());
            List<OrderGoodsVo> orderGoods = apiOrderGoodsMapper.queryList(orderGoodsParam);
            String body = "";
            if (null != orderGoods) {
                for (OrderGoodsVo goodsVo : orderGoods) {
                    body = body + goodsVo.getGoods_name() + "、";
                }
                if (body.length() > 0) {
                    body = body.substring(0, body.length() - 1);
                }
            }
            paras.add(new TemplateData("keyword2", body, "#000000"));
            paras.add(new TemplateData("keyword3", orderInfo.getActual_price().setScale(2, BigDecimal.ROUND_HALF_DOWN).toString(), "#000000"));
            paras.add(new TemplateData("keyword4", DateUtils.format(orderInfo.getAdd_time(), DateUtils.DATE_TIME_PATTERN), "#000000"));

            tem.setData(paras);
        }
        // TODO: 2018/10/25 暂时不实现团购订单
        /*if (orderInfo.getOrder_type().equals("2")) { // 订单类型 1：普通订单 2：团购订单
            TemplateConfVo templateConfVo = apiTemplateConfMapper.queryByTypeId(2); //  模板类型 1订单付款成功 2团购成功 3拼团失败通知 4拼团进度 5 6 7订单配送 8订单评价提醒
            if (null == templateConfVo) {
                return;
            }
            UserVo userVo = apiUserMapper.queryObject(orderInfo.getUser_id());

            // 团购明细
            GoodsGroupOpenDetailVo openDetailVo = apiGoodsGroupOpenDetailMapper.queryObject(orderInfo.getActivity_id());

            // 获取团购
            GoodsGroupOpenVo groupOpenVo = apiGoodsGroupOpenMapper.queryObject(openDetailVo.getOpen_id());

            tem.setTemplate_id(templateConfVo.getTemplateId());
            tem.setTopcolor("#00DD00");
            tem.setTouser(userVo.getWeixin_openid());
            tem.setPage("/pages/ucenter/orderDetail/orderDetail?id=" + orderInfo.getId());
            tem.setForm_id(formIdsEntity.getFormId());

            List<TemplateData> paras = new ArrayList<TemplateData>();
            paras.add(new TemplateData("keyword1", groupOpenVo.getTitle(), "#000000"));
            paras.add(new TemplateData("keyword2", DateUtils.format(groupOpenVo.getOpen_time(), DateUtils.DATE_TIME_PATTERN), "#000000"));

            //订单的商品
            Map orderGoodsParam = Maps.newHashMap();
            orderGoodsParam.put("order_id", orderInfo.getId());
            List<OrderGoodsVo> orderGoods = apiOrderGoodsMapper.queryList(orderGoodsParam);
            String body = "";
            if (null != orderGoods) {
                for (OrderGoodsVo goodsVo : orderGoods) {
                    body = body + goodsVo.getGoods_name() + "、";
                }
                if (body.length() > 0) {
                    body = body.substring(0, body.length() - 1);
                }
            }
            paras.add(new TemplateData("keyword3", body, "#000000"));
            // 团成员
            Map groupParam = Maps.newHashMap();
            groupParam.put("open_id", orderInfo.getActivity_id());
            List<GoodsGroupOpenDetailVo> openDetailVos = apiGoodsGroupOpenDetailMapper.queryList(groupParam);
            String attendMember = "";
            if (null != openDetailVos) {
                for (GoodsGroupOpenDetailVo detailVo : openDetailVos) {
                    attendMember = attendMember + detailVo.getNickname() + "、";
                }
                if (attendMember.length() > 0) {
                    attendMember = attendMember.substring(0, attendMember.length() - 1);
                }
            }
            paras.add(new TemplateData("keyword4", attendMember, "#000000"));
            paras.add(new TemplateData("keyword5", orderInfo.getActual_price().setScale(2, BigDecimal.ROUND_HALF_DOWN).toString(), "#000000"));
            paras.add(new TemplateData("keyword5", templateConfVo.getDesc(), "#000000"));
            tem.setData(paras);
        }*/
        try {
//            WxTemplateUtil.sendMessage(tem);
//            formIdsService.releaseFormIds(formIdsEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 确认收货
     *
     * @param orderId
     */
    @Transactional
    public void confirmOrder(Long orderId) {
        OrderVo orderVo = apiOrderMapper.queryObject(orderId);
        orderVo.setOrder_status(301);
        orderVo.setShipping_status(2);
        orderVo.setConfirm_time(new Date());
        orderVo.setModTime(new Date());
        apiOrderMapper.update(orderVo);
    }

    /*public String printMsgs(Long orderId) {
        OrderVo orderEntity = queryObject(orderId);
        Map<String, Object> map = new HashMap<String, Object>();

        map.put("order_id", orderEntity.getId());
        List<OrderGoodsVo> orderGoodsEntities = apiOrderGoodsMapper.queryList(map);

        UserVo userVo = apiUserMapper.queryObject(orderEntity.getUser_id());

        String content = "<CB>商城超市</CB><BR>";
        content += "名称/商品编码       单价   数量   金额<BR>";
        for (OrderGoodsVo orderGoodsEntity : orderGoodsEntities) {
            content += "--------------------------------<BR>";
            content += orderGoodsEntity.getGoods_name() + "<BR>" + orderGoodsEntity.getGoods_sn() + "             " + orderGoodsEntity.getRetail_price() + "    " + orderGoodsEntity.getNumber()
                    + "   " + orderGoodsEntity.getRetail_price().multiply(new BigDecimal(orderGoodsEntity.getNumber())) + "<BR>";
        }
        content += "--------------------------------<BR>";
        content += "备注：" + orderEntity.getPostscript() + "<BR>";
        content += "--------------------------------<BR>";
        content += "订单编号：" + orderEntity.getOrder_sn() + "<BR>";
        content += "配送配用：" + orderEntity.getShipping_fee() + "元<BR>";
        content += "优惠价格：" + orderEntity.getCoupon_price() + "元<BR>";
        content += "合计：" + orderEntity.getOrder_price() + "元<BR>";
        content += "实付：" + orderEntity.getActual_price() + "元<BR>";
        content += "姓名：" + null != userVo.getNickname() ? userVo.getNickname() : "" + "<BR>";
        content += "送货地点：" + orderEntity.getProvince() + orderEntity.getCity() + orderEntity.getDistrict() + orderEntity.getAddress() + "<BR>";
        content += "联系电话：" + orderEntity.getMobile() + "<BR>";
        content += "付款时间：" + DateUtils.format(orderEntity.getPay_time(), DateUtils.DATE_TIME_PATTERN) + "<BR>";
        content += "<QR>" + orderEntity.getId() + "</QR>";
        if ("2".equals(orderEntity.getOrder_type())) {
            content += "<RIGHT><BOLD>【团购】</BOLD></RIGHT>";
        }

        //所属门店
        Long storeId = orderEntity.getStore_id();

        //获取门店的打印机编号，每个门店只有一个打票机
        Map<String, Object> printParams = new HashMap<String, Object>();
        List<SysPrinterVo> printerEntities = apiSysPrinterMapper.queryList(printParams);
        printParams.put("storeId", storeId);
        String sn = "";
        if (printerEntities != null && printerEntities.size() != 0) {
            sn = printerEntities.get(0).getSn();
        }
        return FeiGeUtils.printMsg(sn, content, "1");
    }*/
    public Ticket printMsg(Long orderId) {
        OrderVo orderEntity = queryObject(orderId);
        if(orderEntity != null) {
            if (orderEntity.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_10.getItem())
                    || orderEntity.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_02.getItem())) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("order_id", orderEntity.getId());
                List<OrderGoodsVo> orderGoodsEntityList = apiOrderGoodsMapper.queryList(map);
                // 获取门店
                StoreVo storeEntity = apiStoreMapper.queryObject(orderEntity.getStore_id());
                // 获取清关信息
                OrderProcessRecordEntity orderProcessRecordEntity = orderProcessRecordMapper.queryObjectByOrderSn(orderEntity.getOrder_sn());

                UserVo userVo = apiUserMapper.queryObject(orderEntity.getUser_id());
                // 小票头
                TicketHead head = new TicketHead();
                head.setTitle(OmsMerchPropertiesBuilder.instance().getMerchName() + storeEntity.getStoreName());
                head.setMemberId(userVo.getUsername().toString());
                head.setOrderId(orderEntity.getOrder_sn());
                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 (OrderGoodsVo orderGoods : orderGoodsEntityList) {
                    goodsTotal += orderGoods.getNumber();
                    total = total.add(orderGoods.getRetail_price().subtract(new BigDecimal(orderGoods.getNumber()))).setScale(2, BigDecimal.ROUND_HALF_UP);
                    Goods goods = new Goods(orderGoods.getGoods_name(), orderGoods.getRetail_price().toString(), orderGoods.getNumber().toString()
                                            ,orderGoods.getRetail_price().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.getActual_price().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                cashInfo.setOddChange("0.00");
                cashInfo.setCoupon(orderEntity.getCoupon_price().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                cashInfo.setFreight(new BigDecimal(orderEntity.getFreight_price()).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                cashInfo.setPaymentMode("微信支付");

                // 海关清单
                CusListing cusListing = new CusListing();
                cusListing.setOrderId(orderEntity.getOrder_sn());
                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);
            }else{
                return null;
            }
        }else{
            return null;
        }
    }

    public List<OrderVo> queryObjectByIdList(List<Long> orderIdList){
        return apiOrderMapper.queryObjectByIdList(orderIdList);
    }

    public List<OrderVo> queryObjectByMerchOrderSn(String merchOrderSn){
        return apiOrderMapper.queryObjectByMerchOrderSn(merchOrderSn);
    }
    public int queryCountByMerchOrderSn(String merchOrderSn){
        return apiOrderMapper.queryCountByMerchOrderSn(merchOrderSn);
    }
    public int queryCountByPayId(String payId){
        return apiOrderMapper.queryCountByPayId(payId);
    }
    public List<OrderVo> queryOrderByMerchOrderSnAndRefundStatus(String merchOrderSn){
        return apiOrderMapper.queryOrderByMerchOrderSnAndRefundStatus(merchOrderSn);
    }

}
