/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 */

package com.yami.shop.delivery.comment.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.enums.OrderStatus;
import com.yami.shop.bean.model.Order;
import com.yami.shop.bean.model.OrderItem;
import com.yami.shop.bean.model.ShopDetail;
import com.yami.shop.bean.model.UserAddrOrder;
import com.yami.shop.bean.param.CancelOrderParam;
import com.yami.shop.dao.OrderItemMapper;
import com.yami.shop.dao.OrderRefundMapper;
import com.yami.shop.delivery.comment.api.paotui.PaoTuiApi;
import com.yami.shop.delivery.comment.api.paotui.model.request.AddOrderRequest;
import com.yami.shop.delivery.comment.api.paotui.model.response.OrderResponse;
import com.yami.shop.delivery.comment.dao.DeliveryOrderMapper;
import com.yami.shop.delivery.comment.model.DeliveryOrder;
import com.yami.shop.delivery.comment.model.DeliveryOrderItem;
import com.yami.shop.delivery.comment.param.DeliveryOrderItemParam;
import com.yami.shop.delivery.comment.service.DeliveryOrderItemService;
import com.yami.shop.delivery.comment.service.DeliveryOrderService;
import com.yami.shop.service.OrderService;
import com.yami.shop.service.ShopDetailService;
import com.yami.shop.service.UserAddrOrderService;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFacade;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author lhd
 * @date 2020-04-22 15:46:05
 */
@Service
@AllArgsConstructor
@Slf4j
public class DeliveryOrderServiceImpl extends ServiceImpl<DeliveryOrderMapper, DeliveryOrder> implements DeliveryOrderService {

    private final DeliveryOrderMapper deliveryOrderMapper;
    private final DeliveryOrderItemService deliveryOrderItemService;
    private final OrderService orderService;
    private final OrderItemMapper orderItemMapper;
    private final OrderRefundMapper orderRefundMapper;
    private final MapperFacade mapperFacade;
    private final UserAddrOrderService userAddrOrderService;
    private PaoTuiApi paoTuiApi;

    /**
     * 生成物流信息及保存物流与订单关联
     *
     * @param deliveryOrderParam 物流信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveDeliveriesInfo(DeliveryOrderItemParam deliveryOrderParam) {
        boolean isDelivery = true;
        List<OrderItem> selectOrderItems = deliveryOrderParam.getSelectOrderItems();
        selectOrderItems.forEach(i -> i.setDvyType(deliveryOrderParam.getDeliveryType()));
        String orderNumber = deliveryOrderParam.getOrderNumber();
        Order order = orderService.getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNumber, orderNumber));
        UserAddrOrder userAddrOrder = userAddrOrderService.getById(order.getAddrOrderId());
        if (deliveryOrderParam.getDeliveryType() == 1) {
            AddOrderRequest addOrderRequest = new AddOrderRequest();
            addOrderRequest.setShop_id(String.valueOf(order.getShopId()));
            addOrderRequest.setOrigin_id(order.getOrderNumber());
            addOrderRequest.setSubscribe_time(Instant.now().getEpochSecond() + 60 * 60);
            addOrderRequest.setReceiver_longitude(String.valueOf(userAddrOrder.getLongitude()));
            addOrderRequest.setReceiver_latitude(String.valueOf(userAddrOrder.getLatitude()));
            addOrderRequest.setReceiver_address(userAddrOrder.getAddress() + userAddrOrder.getAddressName());
            addOrderRequest.setReceiver_address_detail(userAddrOrder.getAddrDetail());
            addOrderRequest.setReceiver_name(userAddrOrder.getReceiver());
            addOrderRequest.setReceiver_phone(userAddrOrder.getMobile());
            addOrderRequest.setGoods_value(order.getTotal().intValue() * 100);
            OrderResponse orderResponse = paoTuiApi.addOrder(addOrderRequest);
            log.error("配送结果：{}", orderResponse);
            if(orderResponse.getOrder_id() == null){
                CancelOrderParam cancelOrderParam = new CancelOrderParam();
                cancelOrderParam.setOrderNumber(orderNumber);
                cancelOrderParam.setRefundType(1);
                cancelOrderParam.setApplyType(1);
                cancelOrderParam.setIsReceiver(true);
                orderResponse.setOrder_id("配送费账户余额不足，请先充值！");
                orderService.cancelOrder(cancelOrderParam);
            }

            //校验数量及获取发货的总数
            int prodNumSum = checkDelivery(selectOrderItems);
            DeliveryOrder deliveryOrder = new DeliveryOrder();
            deliveryOrder.setOrderNumber(deliveryOrderParam.getOrderNumber());
            deliveryOrder.setDvyId(deliveryOrderParam.getDvyId());
            deliveryOrder.setDvyFlowId(orderResponse.getOrder_id());
            deliveryOrder.setCreateTime(new Date());
            deliveryOrder.setStatus(1);
            deliveryOrder.setProductNums(prodNumSum);
            order.setDvyId(deliveryOrderParam.getDvyId());
            order.setDvyFlowId(orderResponse.getOrder_id());
            //保存订单物流信息
            save(deliveryOrder);
            //保存需要添加的关联信息
            List<DeliveryOrderItem> addDeliveries = new ArrayList<>();
            for (OrderItem selectOrderItem : selectOrderItems) {
                DeliveryOrderItem deliveryOrderItem = new DeliveryOrderItem();
                deliveryOrderItem.setOrderItemId(selectOrderItem.getOrderItemId());
                deliveryOrderItem.setProdCount(selectOrderItem.getChangeNum());
                deliveryOrderItem.setOrderDeliveryId(deliveryOrder.getOrderDeliveryId());
                addDeliveries.add(deliveryOrderItem);
            }
            if (CollectionUtils.isNotEmpty(addDeliveries)) {
                deliveryOrderItemService.saveBatch(addDeliveries);
            }
        }
        orderItemMapper.updateByDeliveries(selectOrderItems);
        //判断是否发货完成
        List<OrderItem> orderItems = null;
        if (Objects.isNull(order.getRefundStatus())) {
            orderItems = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderNumber, orderNumber));
        } else {
            orderItems = orderItemMapper.getListByOrderNumber(orderNumber);
        }
        // 有多个商品的订单， 有退款记录的，并且有退款成功的单个商品，
        // 其余的商品都是发货完成的订单，改成发货状态
        // 在退款处理的时候将状态改为0即可
        for (OrderItem orderItem : orderItems) {
            if (orderItem.getStatus() != 0) {
                isDelivery = false;
            }
        }
        //修改为发货状态
        if (isDelivery) {
            Date date = new Date();
            order.setHbOrderStatus(OrderStatus.CONSIGNMENT.value());
            order.setUpdateTime(date);
            order.setDvyTime(date);
            //判断是无需物流还是快递发货
            order.setDvyType(deliveryOrderParam.getDeliveryType());
            // 如果是无需快递，则判断该订单是否包含有物流的项，若有物流则配送类型为快递配送，没有物流则不变
            if (Objects.equals(order.getDvyType(), 3)) {
                List<DeliveryOrder> deliveryOrders = list(new LambdaQueryWrapper<DeliveryOrder>().eq(DeliveryOrder::getOrderNumber, orderNumber));
                if (!CollectionUtils.isEmpty(deliveryOrders)) {
                    order.setDvyType(1);
                }
            }
            orderService.updateById(order);
        }
    }

    /**
     * 修改物流信息
     *
     * @param deliveryOrders 物流修改的信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateOrderDeliveries(List<DeliveryOrder> deliveryOrders) {
//        List<DeliveryOrder> addDeliveryOrders = new ArrayList<>();
//        for (DeliveryOrder deliveryOrder : deliveryOrders) {
//            //需要新增的物流信息
//            DeliveryOrder addDeliveryOrder = mapperFacade.map(deliveryOrder, DeliveryOrder.class);
//            addDeliveryOrder.setCreateTime(new Date());
//            addDeliveryOrder.setStatus(1);
//            addDeliveryOrders.add(addDeliveryOrder);
//            //修改之前的状态为删除，恢复之前的物流信息
//            deliveryOrder.setDvyId(null);
//            deliveryOrder.setDvyFlowId(null);
//            deliveryOrder.setDeleteTime(new Date());
//            deliveryOrder.setStatus(-1);
//        }
        updateBatchById(deliveryOrders);
//        saveBatch(addDeliveryOrders);
    }

    @Override
    public List<DeliveryOrder> getAndDeliveryItemInfo(String orderNumber) {
        return deliveryOrderMapper.getAndDeliveryItemInfo(orderNumber);
    }

    @Override
    public List<DeliveryOrder> listDetailDelivery(String orderNumber) {
        return deliveryOrderMapper.listDetailDelivery(orderNumber);
    }

    /**
     * 校验可发货数量并返回总数
     *
     * @param selectOrderItems 选择发货的订单项
     */
    private int checkDelivery(List<OrderItem> selectOrderItems) {
//        //查询已发货数量
//        List<DeliveryOrderItem> deliveryOrderItemList = deliveryOrderItemService.listItemNums(selectOrderItems);
//        //判断可发货数量
//        if(CollectionUtils.isNotEmpty(deliveryOrderItemList)){
//            Map<Long, Integer> deliveryMap = deliveryOrderItemList.stream().collect(
//                    Collectors.toMap(DeliveryOrderItem::getOrderItemId, DeliveryOrderItem::getProdCount));
//            for (OrderItem selectOrderItem : selectOrderItems) {
//                if(!deliveryMap.containsKey(selectOrderItem.getOrderItemId())){
//                    continue;
//                }
//                Integer prodCount = deliveryMap.get(selectOrderItem.getOrderItemId());
//                if(prodCount > selectOrderItem.getChangeNum()){
//                    throw new GlobalException("部分订单可发货数量不足！");
//                }
//            }
//        }
        //获取发货总数
        int prodNumSum = 0;
        for (OrderItem selectOrderItem : selectOrderItems) {
            prodNumSum += selectOrderItem.getChangeNum();
        }
        return prodNumSum;
    }
}
