package com.kmall.admin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.kmall.admin.dao.*;
import com.kmall.admin.entity.*;
import com.kmall.admin.entity.OrderProcessRecordEntity;
import com.kmall.admin.service.OrderService;
import com.kmall.common.constant.Dict;
import com.kmall.api.service.merch.OmsMerchPropertiesBuilder;
import com.kmall.api.util.CommonUtil;
import com.kmall.common.entity.SysUserEntity;
import com.kmall.common.service.print.ticket.PrintTicketPropertiesBuilder;
import com.kmall.common.utils.*;
import com.kmall.common.utils.print.ticket.TicketPrintUtil;
import com.kmall.common.utils.print.ticket.item.*;
import com.kmall.common.utils.express.kdn.KdniaoUtil;
import com.kmall.common.utils.wechat.WechatRefundApiResult;
import com.kmall.common.utils.wechat.wxglobal.dto.WechatGlobalRefundApiResult;
import com.kmall.common.utils.wechat.wxglobal.dto.WechatRefundAsynApiResult;
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("orderService")
public class OrderServiceImpl
        implements OrderService {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private ShippingDao shippingDao;
    @Autowired
    private OrderGoodsDao orderGoodsDao;
    @Autowired
    private SysPrinterDao printerDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserCouponDao userCouponDao;
    @Autowired
    private ProductStoreRelaDao productStoreRelaDao;
    @Autowired
    private OrderProcessRecordDao orderProcessRecordDao;
    @Autowired
    private OrderRefundDao orderRefundDao;
    @Autowired
    private StoreDao storeDao;
    @Autowired
    private OfflineCartDao offlineCartDao;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private MerchDao merchDao;

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

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

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

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

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

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

    /**
     * 取消订单
     *
     * @param order
     */
    @Override
    public void cancelOrder(OrderEntity order) {
        boolean needUpdateStock = true;
        if (order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_0.getItem())) {
            order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_101.getItem()));
        }

        // 判断是否有优惠券
        UserCouponEntity couponVo = userCouponDao.queryByOrderId(order.getId());
        if (null != couponVo) {
            userCouponDao.cancelOrder(couponVo);
        }
        orderDao.update(order);

        if (!needUpdateStock) {
            return;
        }
        // 更新库存
        updateStock(order);
    }

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

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

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

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

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

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

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

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

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

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

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

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

            if (mallOrderRefund != null) {
                orderRefund.setId(mallOrderRefund.getId());
                orderRefund.setRefundType(mallOrderRefund.getRefundType());
                orderRefundDao.update(orderRefund);
            } else {
                orderRefund.setOrderId(Integer.parseInt(order.getId() + ""));
                orderRefund.setUserId(Integer.parseInt(order.getUserId() + ""));
                orderRefund.setCreateTime(new Date());
                List<OrderEntity> list = orderDao.queryObjectByMerchOrderSn(order.getMerchOrderSn());
                if(list.size()>1){//多条订单
                    orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_2.getItem()));//部分退款
                }else{
                    orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_1.getItem()));//用户全额退款
                }
                orderRefundDao.save(orderRefund);//退款记录
            }
        }
        orderDao.update(order);//修改为退款中
        // 判断是否有优惠券
        UserCouponEntity couponVo = userCouponDao.queryByOrderId(order.getId());
        if (null != couponVo) {
            userCouponDao.cancelOrder(couponVo);
        }

        if (!needUpdateStock) {
            return;
        }
        // 更新库存
        updateStock(order);
    }

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

        OrderRefundEntity mallOrderRefund = orderRefundDao.queryObjectByOrderId(order.getId());
        if (mallOrderRefund != null) {
            orderRefund.setRefundType(mallOrderRefund.getRefundType());
            orderRefund.setId(mallOrderRefund.getId());
            orderRefundDao.update(orderRefund);
        } else {//退款记录不存在
            orderRefund.setOrderId(Integer.parseInt(order.getId() + ""));
            orderRefund.setCreateTime(new Date());
            orderRefund.setUserId(Integer.parseInt(order.getUserId() + ""));
            orderRefundDao.save(orderRefund);//退款记录
        }
        orderDao.update(order);//修改为退款中
        // 判断是否有优惠券
        UserCouponEntity couponVo = userCouponDao.queryByOrderId(order.getId());
        if (null != couponVo) {
            userCouponDao.cancelOrder(couponVo);
        }

        if (!needUpdateStock) {
            return;
        }
        // 更新库存
        updateStock(order);
    }

    /**
     * 微信国际退款逻辑处理
     * @param order
     * @param result
     */
    @Transactional
    public void globalRefund(OrderEntity order, WechatGlobalRefundApiResult result) {
        boolean needUpdateStock = true;
        if (order.getOrderStatus() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) {
            order.setOrderStatus(Integer.parseInt(Dict.orderStatus.item_401.getItem()));
        }
        order.setPayStatus(Integer.parseInt(Dict.payStatus.item_3.getItem()));
        OrderRefundEntity orderRefund = new OrderRefundEntity();
        orderRefund.setRefundId(result.getId());
        orderRefund.setOutRefundNo(result.getOut_refund_no());
        orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_5.getItem()));//退款处理中
        orderRefund.setModTime(new Date());
        orderRefund.setRefundMoney(order.getActualPrice());
        orderRefund.setRefundFeeType(result.getAmount().getCurrency());
        BigDecimal totalFee = BigDecimal.valueOf(Long.valueOf(result.getAmount().getRefund())).divide(Constant.ONE_HUNDRED);
        orderRefund.setTotalFee(totalFee);
        orderRefund.setFeeType(result.getAmount().getCurrency());
        BigDecimal cashRefundFee = BigDecimal.valueOf(Long.valueOf(result.getAmount().getPayer_refund())).divide(Constant.ONE_HUNDRED);
        orderRefund.setCashRefundFee(cashRefundFee);
        orderRefund.setCashRefundFeeType(result.getAmount().getPayer_currency());

        OrderRefundEntity mallOrderRefund = orderRefundDao.queryObjectByOrderId(order.getId());
        if (mallOrderRefund != null) {
            orderRefund.setId(mallOrderRefund.getId());
            orderRefund.setRefundType(mallOrderRefund.getRefundType());
            orderRefundDao.update(orderRefund);
        } else {//退款记录不存在
            orderRefund.setOrderId(Integer.parseInt(order.getId() + ""));
            orderRefund.setUserId(Integer.parseInt(order.getUserId() + ""));
            orderRefund.setCreateTime(new Date());
            orderRefundDao.save(orderRefund);//退款记录
        }
        orderDao.update(order);//修改为退款中
        // 判断是否有优惠券
        UserCouponEntity couponVo = userCouponDao.queryByOrderId(order.getId());
        if (null != couponVo) {
            userCouponDao.cancelOrder(couponVo);
        }

        if (!needUpdateStock) {
            return;
        }
        // 更新库存
        updateStock(order);
    }

    private void updateStock(OrderEntity order){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("orderId", order.getId());
        List<OrderGoodsEntity> orderGoodsVoList = orderGoodsDao.queryList(map);
        for (OrderGoodsEntity orderGoodsEntity : orderGoodsVoList) {
            ProductStoreRelaEntity storeRelaEntity = productStoreRelaDao
                    .queryByStoreIdProductId(Long.valueOf(order.getStoreId()),
                            Long.valueOf(orderGoodsEntity.getProductId()));
            if (null == storeRelaEntity || null == storeRelaEntity.getSellVolume()) {
                storeRelaEntity.setSellVolume(0);
            }
            BigDecimal sellVolume = new BigDecimal(storeRelaEntity.getSellVolume() - orderGoodsEntity.getNumber());//销售量
            if (sellVolume.compareTo(Constant.ZERO) < 0) {
                sellVolume = Constant.ZERO;
            }
            storeRelaEntity.setSellVolume(Integer.parseInt(sellVolume.toString()));
            if (null == storeRelaEntity.getStockNum()) {
                storeRelaEntity.setStockNum(0);
            }
            storeRelaEntity.setStockNum(storeRelaEntity.getStockNum() + orderGoodsEntity.getNumber());//库存数量
            productStoreRelaDao.update(storeRelaEntity);
        }
    }
    /**
     * 处理用户退款申请
     *
     * @param orderInfo
     */
    @Transactional
    public void applyRefundDeal(OrderEntity orderInfo, OrderRefundEntity refundEntity) {
        refundEntity.setApprovalTime(new Date());
        //        refundEntity.setApprover(ShiroUtils.getUserId());
        //  退积分
        try {
            Integer integral = 1;
            if (orderInfo.getActualPrice().intValue() > 0) {
                integral = orderInfo.getActualPrice().intValue();
            }
            if (refundEntity.getRefundStatus() == 2) {
                orderInfo.setOrderStatus(401);
                UserEntity entity = userDao.queryObject(orderInfo.getUserId());
            } else {
                orderInfo.setOrderStatus(201);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        orderRefundDao.update(refundEntity);
        orderDao.update(orderInfo);
    }

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

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

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

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

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

        Map logisticsInfo = new HashMap();
        List<WuliuEntity> wuliuEntityList = new ArrayList<>();
        OrderProcessRecordEntity orderProcessRecordEntity =
                orderProcessRecordDao.queryObjectByOrderSn(orderEntity.getOrderSn());
        if (orderProcessRecordEntity != null) {
            if (orderEntity.getOrderBizType().equals(Dict.orderBizType.item_10.getItem()) ||
                orderEntity.getOrderBizType().equals(Dict.orderBizType.item_02.getItem())) {
                WuliuEntity wuliuEntity = new WuliuEntity();
                wuliuEntity.setAcceptTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                                                  .format(orderProcessRecordEntity.getCustomsSuccTime()));
                wuliuEntity.setAcceptStation(PrintTicketPropertiesBuilder.instance().getAddress() + "送达" +
                                             storeDao.queryObject(orderEntity.getStoreId()).getStoreAddress() +
                                             ";交易完成，用户已提走");
                wuliuEntityList.add(wuliuEntity);
            }
            if (StringUtils.isNotEmpty(orderEntity.getShippingCode()) &&
                StringUtils.isNotEmpty(orderEntity.getShippingNo()) &&
                orderProcessRecordEntity.getShipmentStartTime() != null) {
                JSONObject traces =
                        KdniaoUtil.getOrderTracesByJson(orderEntity.getShippingCode(), orderEntity.getShippingNo());
                List<Map> mapList = (List<Map>) traces.get("Traces");
                if (mapList != null && mapList.size() > 0) {
                    for (Map map : mapList) {
                        WuliuEntity wuliuEntity = new WuliuEntity();
                        wuliuEntity.setAcceptTime(map.get("AcceptTime").toString());
                        wuliuEntity.setAcceptStation(map.get("AcceptStation").toString());
                        wuliuEntityList.add(wuliuEntity);
                    }
                }
                String state = traces.get("State") + "";
                if (Dict.logisticsStatus.item_0.getItem().equals(state) && traces.getBoolean("Success")) {
                    String reason = traces.get("Reason") + "";
                    WuliuEntity wuliuEntity = new WuliuEntity();
                    wuliuEntity.setAcceptStation(reason);
                    wuliuEntityList.add(wuliuEntity);
                }
            }
            if (Dict.isSend.item_1.getItem().equalsIgnoreCase(orderProcessRecordEntity.getIsCustomsSend()) &&
                orderProcessRecordEntity.getShipmentStartTime() != null) {
                WuliuEntity wuliuEntity = new WuliuEntity();
                wuliuEntity.setAcceptStation("订单已出库");
                wuliuEntity.setAcceptTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                                                  .format(orderProcessRecordEntity.getShipmentStartTime()));
                wuliuEntityList.add(wuliuEntity);
            }
            if (Dict.isSend.item_1.getItem().equals(orderProcessRecordEntity.getIsCustomsSend())) {
                WuliuEntity wuliuEntity = new WuliuEntity();
                wuliuEntity.setAcceptStation("订单清关完成，等待仓库发货");
                wuliuEntity.setAcceptTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                                                  .format(orderProcessRecordEntity.getCustomsSuccTime()));
                wuliuEntityList.add(wuliuEntity);
            }

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

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

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

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

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

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

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


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

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

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

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

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