package com.kmall.api.service;

import com.alibaba.fastjson.JSONObject;
import com.kmall.api.contants.Dict;
import com.kmall.api.dao.*;
import com.kmall.api.entity.*;
import com.kmall.api.service.merch.OmsMerchPropertiesBuilder;
import com.kmall.api.util.CommonUtil;
import com.kmall.common.dao.TemplateConfDao;
import com.kmall.common.entity.FormIdsEntity;
import com.kmall.common.entity.TemplateConfVo;
import com.kmall.common.service.FormIdsService;
import com.kmall.common.service.print.ticket.PrintTicketPropertiesBuilder;
import com.kmall.common.utils.DateUtils;
import com.kmall.common.utils.RRException;
import com.kmall.common.utils.StringUtils;
import com.kmall.common.utils.print.ticket.TicketPrintUtil;
import com.kmall.common.utils.print.ticket.item.*;
import com.kmall.common.utils.printer.FeiGeUtils;
import com.kmall.common.utils.wxtemplate.TemplateData;
import com.kmall.common.utils.wxtemplate.WxTemplate;
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 {
    @Autowired
    private ApiSysPrinterMapper apiSysPrinterMapper;
    @Autowired
    private ApiProductMapper apiProductMapper;
    @Autowired
    private ApiCartMapper apiCartMapper;
    @Autowired
    private ApiCouponMapper apiCouponMapper;
    @Autowired
    private ApiOrderMapper apiOrderMapper;
    @Autowired
    private ApiOrderGoodsMapper apiOrderGoodsMapper;
    @Autowired
    private ApiUserCouponMapper apiUserCouponMapper;
    @Autowired
    private TemplateConfDao apiTemplateConfMapper;
    @Autowired
    private ApiUserMapper apiUserMapper;
    @Autowired
    private ApiGoodsGroupOpenMapper apiGoodsGroupOpenMapper;
    @Autowired
    private ApiGoodsGroupOpenDetailMapper apiGoodsGroupOpenDetailMapper;
    @Autowired
    private FormIdsService formIdsService;
    @Autowired
    private ApiGoodsMapper apiGoodsMapper;
    @Autowired
    private ApiFreightService apiFreightService;
    @Autowired
    private ApiOrderProcessRecordMapper orderProcessRecordMapper;
    @Autowired
    private ApiStoreMapper apiStoreMapper;

    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) {
        return apiOrderMapper.queryUcenterMap(map);
    }


    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(OrderVo order) {
        Map orderGoodsParam = new HashMap();
        orderGoodsParam.put("order_id", order.getId());
        //订单的商品
        List<OrderGoodsVo> goodsList = apiOrderGoodsMapper.queryList(orderGoodsParam);
        for (OrderGoodsVo orderGoodsVo : goodsList) {
            ProductVo productInfo = apiProductMapper.queryObjectByStoreId(orderGoodsVo.getProduct_id(), order.getStore_id());
            productInfo.setStock_num(productInfo.getStock_num() + orderGoodsVo.getNumber());
            productInfo.minusSellVolume();
            apiProductMapper.updateStockNum(productInfo);
        }
        apiOrderMapper.update(order);
        // 判断是否有优惠券
        UserCouponVo couponVo = apiUserCouponMapper.queryByOrderId(order.getId());
        if (null != couponVo) {
            apiUserCouponMapper.cancelOrder(couponVo);
        }
    }

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


    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 = new HashMap();

        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");
        UserVo user = apiUserMapper.queryObjectByIdNoAndName(idNo, userName);
        UserVo userVo = new UserVo();
        userVo.setId(loginUser.getId());
        userVo.setIdNo(idNo);
        userVo.setUsername(userName);
        if(user != null){
            if(loginUser.getId() == user.getId()){
                // TODO: 2018/10/18 实名认证身份证信息，认证成功更新到用户表
                apiUserMapper.update(userVo);
            }else{
                throw new RRException("该身份证信息已被绑定");
            }
        }else{
            // TODO: 2018/10/18 实名认证身份证信息，认证成功更新到用户表
            apiUserMapper.update(userVo);
        }

        //获取要购买的商品
        Map param = new HashMap();
        param.put("user_id", loginUser.getId());
        param.put("store_id", storeId);
        param.put("checked", 1);
        List<CartVo> checkedGoodsList = apiCartMapper.queryList(param);
        if (null == checkedGoodsList) {
            resultObj.put("errno", 400);
            resultObj.put("errmsg", "请选择商品");
            return resultObj;
        }
        // 检查库存和更新库存
        List<ProductVo> productVos = new ArrayList();
        for (CartVo goodsItem : checkedGoodsList) {
            //取得规格的信息,判断规格库存
            ProductVo productInfo = apiProductMapper.queryByStoreId(goodsItem.getProduct_id(), storeId);
            if (null == productInfo || null == productInfo.getStock_num() || productInfo.getStock_num() < goodsItem.getNumber()) {
                resultObj.put("errno", 400);
                resultObj.put("errmsg", "库存不足，仅剩余" + productInfo.getStock_num());
                return resultObj;
            }
            productInfo.setStock_num(productInfo.getStock_num() - goodsItem.getNumber());
            productInfo.setStore_id(storeId);
            productInfo.addSellVolume();
            productVos.add(productInfo);
        }

        BigDecimal freightPrice00 = new BigDecimal(0.00);
        BigDecimal freightPrice02 = new BigDecimal(0.00);
        BigDecimal freightPrice10 = new BigDecimal(0.00);
        BigDecimal freightPrice11 = new BigDecimal(0.00);
        Boolean isBizType00 = false;
        Boolean isBizType02 = false;
        Boolean isBizType10 = false;
        Boolean isBizType11 = false;
        //订单按业务类型进行分单
        for (CartVo goodsItem : checkedGoodsList) {
            //订单业务类型：00:保税备货， 02:保税展示补货，10:保税展示跨境，11:普通商品
            if(Dict.orderBizType.item_00.getItem().equalsIgnoreCase(goodsItem.getGoodsBizType())){
                FreightEntity freightEntity = apiFreightService.queryObjectByGoodsId(goodsItem.getGoods_id());
                freightPrice00 =freightEntity!=null ? freightEntity.getDefaultFreight() : freightPrice00;//查询商品运费信息
                isBizType00 =true;
            }
            if(Dict.orderBizType.item_02.getItem().equalsIgnoreCase(goodsItem.getGoodsBizType())){
                FreightEntity freightEntity = apiFreightService.queryObjectByGoodsId(goodsItem.getGoods_id());
                freightPrice02 =freightEntity!=null ? freightEntity.getDefaultFreight() : freightPrice02;//查询商品运费信息
                isBizType02 =true;
            }
            if(Dict.orderBizType.item_10.getItem().equalsIgnoreCase(goodsItem.getGoodsBizType())){
                FreightEntity freightEntity = apiFreightService.queryObjectByGoodsId(goodsItem.getGoods_id());
                freightPrice10 =freightEntity!=null ? freightEntity.getDefaultFreight() : freightPrice10;//查询商品运费信息
                isBizType10 =true;
            }
            if(Dict.orderBizType.item_11.getItem().equalsIgnoreCase(goodsItem.getGoodsBizType())){
                FreightEntity freightEntity = apiFreightService.queryObjectByGoodsId(goodsItem.getGoods_id());
                freightPrice11 =freightEntity!=null ? freightEntity.getDefaultFreight() : freightPrice11;//查询商品运费信息
                isBizType11 =true;
            }
        }

        List<OrderVo> orderInfoList = new ArrayList();
        String merchOrderSn = "EMATO"+new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
        if(isBizType00){
            OrderVo order00 = setOrderVo(loginUser,jsonParam,storeId,freightPrice00,checkedGoodsList,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(loginUser,jsonParam,storeId,freightPrice02,checkedGoodsList,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(loginUser,jsonParam,storeId,freightPrice10,checkedGoodsList,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(loginUser,jsonParam,storeId,freightPrice11,checkedGoodsList,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) {
            apiOrderMapper.saveBatch(orderInfoList);

            List<OrderProcessRecordEntity> processRecordEntityList = new ArrayList<>();
            for (OrderVo orderInfo : orderInfoList) {
                if (null == orderInfo.getId()) {
                    throw new RRException("订单提交失败");
                }
                //新增订单详情
                for (CartVo goodsItem : checkedGoodsList) {
                    //统计商品总价
                    if (orderInfo.getOrderBizType().equalsIgnoreCase(goodsItem.getGoodsBizType())) {
                        GoodsVo goodsVo = apiGoodsMapper.queryObject(goodsItem.getGoods_id());
                        if(goodsVo==null){
                            throw new RRException("订单提交失败：商品不存在");
                        }
                        OrderGoodsVo orderGoodsVo = setOrderGoodsVo(orderInfo, goodsItem,goodsVo);
                        apiOrderGoodsMapper.save(orderGoodsVo);
                    }
                }
                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);//新增订单流转信息

            for (ProductVo productVo : productVos) {
                apiProductMapper.updateStockNum(productVo);
            }

            //清空已购买的商品
            apiCartMapper.deleteByCart(loginUser.getId(), storeId, 1);
            resultObj.put("errno", 0);
            resultObj.put("errmsg", "订单提交成功");
            //
            Map orderInfoMap = new HashMap();
            orderInfoMap.put("orderInfo", orderInfoList);
            resultObj.put("data", orderInfoMap);

            // 优惠券标记已用
            /*for (OrderVo orderInfo : orderInfoList) {
                if (null != userCouponId && 0 != userCouponId) {
                    UserCouponVo userCouponVo = apiUserCouponMapper.queryObject(userCouponId);
                    if (null != userCouponVo && (null == userCouponVo.getOrder_id() || 0 == userCouponVo.getOrder_id())) {
                        userCouponVo.setUsed_time(new Date());
                        userCouponVo.setOrder_id(orderInfo.getId());
                        userCouponVo.setIsUsed(Dict.isUsed.item_1.getItem());
                        apiUserCouponMapper.update(userCouponVo);
                    }
                }
            }*/
        }

        return resultObj;
    }

    /**
     * 设置订单数据
     * @param loginUser
     * @param jsonParam
     * @param storeId
     * @param freightPrice
     * @param checkedGoodsList
     * @return
     */
    public OrderVo setOrderVo(UserVo loginUser,JSONObject jsonParam,Long storeId,BigDecimal freightPrice,List<CartVo> checkedGoodsList,String bizType){
        OrderVo orderInfo = new OrderVo();
        Integer userCouponId = jsonParam.getInteger("userCouponId");
        String postscript = jsonParam.getString("postscript");
        Long fullCutCouponId = jsonParam.getLong("fullCutCouponId");//满减券
        AddressVo addressVo = jsonParam.getObject("checkedAddress", AddressVo.class);
        Date delivery_date = jsonParam.getDate("delivery_date");
        if (null == delivery_date) {
            delivery_date = new Date();
        }
        String delivery_remark = jsonParam.getString("delivery_remark");
        if (StringUtils.isNullOrEmpty(delivery_remark)) {
            delivery_remark = "尽快送达";
        }
        BigDecimal fullCutCouponDec = new BigDecimal(0);
        BigDecimal goodsTotalPrice = new BigDecimal(0.00);
        for (CartVo goodsItem : checkedGoodsList) {
            if(bizType.equalsIgnoreCase(goodsItem.getGoodsBizType())){
                goodsTotalPrice = goodsTotalPrice.add(goodsItem.getRetail_price().multiply(new BigDecimal(goodsItem.getNumber())));
            }
        }

        //查询未使用的优惠券
        String couponName = "";
        UserCouponVo couponVo = null;
        BigDecimal couponPrice = new BigDecimal(0.00);
        if (null != userCouponId && 0 != userCouponId) {
            couponVo = apiUserCouponMapper.queryObjectByIdAndUsed(userCouponId);
            if (null != couponVo && null != couponVo.getType_money()) {
                couponPrice = couponVo.getType_money();
                couponName = couponVo.getCoupon_name();
            }
        }

        /*// 获取优惠信息提示
        Map couponParam = new HashMap();
        couponParam.put("enabled", true);
        Integer[] send_types = new Integer[]{7};
        couponParam.put("send_types", send_types);
        List<CouponVo> couponVos = apiCouponMapper.queryList(couponParam);
        if (null != couponVos && couponVos.size() > 0) {
            for (CouponVo couponVo : couponVos) {
                // 是否免运费
                if (couponVo.getSend_type() == 7 && couponVo.getMin_goods_amount().compareTo(goodsTotalPrice) <= 0) {
                    freightPrice = couponVo.getType_money();
                }
            }
        }
        //todo 获取优惠信息 满减，暂时不用
        CouponVo fullCutCoupon = apiCouponMapper.queryObject(fullCutCouponId);
        if (null != fullCutCoupon) {
            fullCutCouponDec = fullCutCoupon.getType_money();
        }*/

        //订单价格计算：订单的总价+运费
        BigDecimal orderTotalPrice = goodsTotalPrice.add(freightPrice);

        //减去其它支付的金额后，要实际支付的金额   订单的总价+运费-优惠券金额
        BigDecimal actualPrice = orderTotalPrice.subtract(couponPrice);
//        BigDecimal actualPrice = orderTotalPrice.subtract(fullCutCouponDec).subtract(couponPrice);

        //商户（拼音首字母）+业务类型+编号
        String merchSn = OmsMerchPropertiesBuilder.instance().getMerchSn();
        String merchShortName = OmsMerchPropertiesBuilder.instance().getMerchShortName();
        String orderSn = merchShortName + 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(userCouponId);
        orderInfo.setCoupon_price(couponPrice);
        orderInfo.setCoupon_name(couponName);

        //留言
        orderInfo.setPostscript(postscript);
        //使用的优惠券
        orderInfo.setFull_cut_price(fullCutCouponDec);
        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(new BigDecimal(0));
        orderInfo.setIntegral(0);
        orderInfo.setIntegral_money(new BigDecimal(0));
        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());

        //标记该订单已使用优惠券
        if(couponVo != null){
            couponVo.setUsed_time(new Date());
            couponVo.setIsUsed(Dict.isUsed.item_1.getItem());
            apiUserCouponMapper.update(couponVo);
        }
        return orderInfo;
    }


    public OrderGoodsVo setOrderGoodsVo(OrderVo orderInfo,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());

        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 = new BigDecimal(0);
        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();
        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 = new HashMap();
            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 = new HashMap();
            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 = new HashMap();
            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());
        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 = new BigDecimal(0); // 商品总计
                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);
    }
}
