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.service.OrderService;
import com.kmall.api.contants.Dict;
import com.kmall.api.service.merch.OmsMerchPropertiesBuilder;
import com.kmall.common.service.print.ticket.PrintTicketPropertiesBuilder;
import com.kmall.common.utils.Constant;
import com.kmall.common.utils.print.ticket.TicketPrintUtil;
import com.kmall.common.utils.print.ticket.item.*;
import com.kmall.common.utils.RRException;
import com.kmall.common.utils.ShiroUtils;
import com.kmall.common.utils.StringUtils;
import com.kmall.common.utils.express.kdn.KdniaoUtil;
import com.kmall.common.utils.wechat.WechatRefundApiResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.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;

    @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;
        }
        // 更新库存
        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(Constant.ZERO);
            }
            BigDecimal sellVolume = storeRelaEntity.getSellVolume().subtract(new BigDecimal(orderGoodsEntity.getNumber()));//销售量
            if (sellVolume.compareTo(Constant.ZERO) < 0) {
                sellVolume = Constant.ZERO;
            }
            storeRelaEntity.setSellVolume(sellVolume);
            if (null == storeRelaEntity.getStockNum()) {
                storeRelaEntity.setStockNum(0);
            }
            storeRelaEntity.setStockNum(storeRelaEntity.getStockNum() + orderGoodsEntity.getNumber());//库存数量
            productStoreRelaDao.update(storeRelaEntity);
        }
    }

    @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.valueOf(Dict.orderStatus.item_301.getItem())) {
            throw new RRException("此订单已完成！");
        }
        if (orderEntity.getOrderStatus() == Integer.valueOf(Dict.orderStatus.item_0.getItem())) {
            throw new RRException("此订单待付款！");
        }
        if (orderEntity.getOrderStatus() == Integer.valueOf(Dict.orderStatus.item_100.getItem())) {
            throw new RRException("此订单付款中！");
        }
        if (orderEntity.getOrderStatus() == Integer.valueOf(Dict.orderStatus.item_101.getItem())) {
            throw new RRException("此订单已取消！");
        }
        if (orderEntity.getOrderStatus() == Integer.valueOf(Dict.orderStatus.item_102.getItem())) {
            throw new RRException("此订单已删除！");
        }
        if (orderEntity.getOrderStatus() == Integer.valueOf(Dict.orderStatus.item_201.getItem())) {
            throw new RRException("此订单还未发货！");
        }
        if (orderEntity.getOrderStatus() == Integer.valueOf(Dict.orderStatus.item_401.getItem())) {
            throw new RRException("此订单已退款！");
        }
        if (orderEntity.getOrderStatus() == Integer.valueOf(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());
        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()));
        }
        order.setPayStatus(Integer.parseInt(Dict.payStatus.item_3.getItem()));

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

        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());
            orderRefundDao.save(orderRefund);//退款记录
        }

        if (!needUpdateStock) {
            return;
        }
        // 更新库存
        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(Constant.ZERO);
            }
            BigDecimal sellVolume = storeRelaEntity.getSellVolume().subtract(new BigDecimal(orderGoodsEntity.getNumber()));//销售量
            if (sellVolume.compareTo(Constant.ZERO) < 0) {
                sellVolume = Constant.ZERO;
            }
            storeRelaEntity.setSellVolume(sellVolume);
            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("此订单不存在！");
        } else if (orderEntity.getShippingStatus() == 0 || StringUtils.isNullOrEmpty(orderEntity.getShippingNo())) {
            throw new RRException("此订单还未发货！");
        }

        Map logisticsInfo = new HashMap();
        List<WuliuEntity> wuliuEntityList = new ArrayList<>();
        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(orderEntity.getAddTime()));
            wuliuEntity.setAcceptStation(PrintTicketPropertiesBuilder.instance().getAddress()
                    + "送达" + storeDao.queryObject(orderEntity.getStoreId()).getStoreAddress()
                    + ";交易完成，用户已提走");
            wuliuEntityList.add(wuliuEntity);
        } else if (StringUtils.isNotEmpty(orderEntity.getShippingCode())
                && StringUtils.isNotEmpty(orderEntity.getShippingNo())) {
            JSONObject traces = KdniaoUtil.getOrderTracesByJson(orderEntity.getShippingCode(), orderEntity.getShippingNo());
            List<Map> mapList = (List<Map>) traces.get("Traces");
            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").toString();
            if (Dict.logisticsStatus.item_0.getItem().equals(state) && traces.getBoolean("Success")) {
                String reason = traces.get("Reason").toString();
                WuliuEntity wuliuEntity = new WuliuEntity();
                wuliuEntity.setAcceptStation(reason);
                wuliuEntityList.add(wuliuEntity);
            }
        }

        OrderProcessRecordEntity orderProcessRecordEntity = orderProcessRecordDao.queryObjectByOrderSn(orderEntity.getOrderSn());
        if (orderProcessRecordEntity != null) {
            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_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;
    }
}
