/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.delivery.multishop.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.model.Delivery;
import com.yami.shop.bean.model.Order;
import com.yami.shop.bean.model.OrderItem;
import com.yami.shop.bean.model.UserAddrOrder;
import com.yami.shop.common.exception.GlobalException;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.delivery.comment.api.paotui.PaoTuiApi;
import com.yami.shop.delivery.comment.api.paotui.model.request.OrderDetailRequest;
import com.yami.shop.delivery.comment.api.paotui.model.response.OrderStatusResponse;
import com.yami.shop.delivery.comment.model.DeliveryOrder;
import com.yami.shop.delivery.comment.param.DeliveryOrderItemParam;
import com.yami.shop.delivery.comment.param.DvyOrderParam;
import com.yami.shop.delivery.comment.param.OrderParam;
import com.yami.shop.delivery.comment.service.DeliveryOrderService;
import com.yami.shop.security.multishop.util.SecurityUtils;
import com.yami.shop.service.DeliveryService;
import com.yami.shop.service.OrderItemService;
import com.yami.shop.service.OrderService;
import com.yami.shop.service.UserAddrOrderService;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 多商户订单配送信息管理实现
 *
 * @author lhd
 * @version 1.0.0
 * @since 2020-05-15
 */
@Controller
@AllArgsConstructor
@RequestMapping("/order/delivery")
public class OrderDeliveryController {

    private final OrderItemService orderItemService;

    private final UserAddrOrderService userAddrOrderService;

    private final OrderService orderService;

    private final DeliveryOrderService deliveryOrderService;

    private final DeliveryService deliveryService;

    private final MapperFacade mapperFacade;

    @Autowired
    private PaoTuiApi paoTuiApi;

    /**
     * 订单项待发货数量查询
     */
    @GetMapping("/getOrderItemUnDelivery/{orderNumber}")
    public ResponseEntity<Order> getOrderItemUnDelivery(@PathVariable("orderNumber") String orderNumber) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        Order order = orderService.getOrderByOrderNumberAndShopId(orderNumber, shopId, true);
        UserAddrOrder userAddrOrder = userAddrOrderService.getById(order.getAddrOrderId());
        order.setUserAddrOrder(userAddrOrder);
        List<OrderItem> orderItems = orderItemService.list(new LambdaQueryWrapper<OrderItem>()
                .eq(OrderItem::getOrderNumber, orderNumber).eq(OrderItem::getShopId, shopId));
        if (CollectionUtils.isEmpty(orderItems)) {
            throw new GlobalException("订单不存在！");
        }
        Map<Long, Integer> orderItemMap = null;
        if (Objects.nonNull(order.getRefundStatus())) {
            orderItemMap = orderService.getOrderItemMap(order.getOrderId());
        }
        //查询已发货数量
        for (OrderItem orderItem : orderItems) {
            //根据状态查询可发货数量
            orderItem.setChangeNum(orderItem.getStatus() == -1 ? orderItem.getProdCount() : orderItem.getStatus());
            orderItem.setProdCount(orderItem.getChangeNum());
            if (Objects.nonNull(orderItemMap) && Objects.nonNull(orderItemMap.get(orderItem.getOrderItemId()))) {
                orderItem.setReturnMoneySts(orderItemMap.get(orderItem.getOrderItemId()));
            } else if (Objects.nonNull(orderItemMap) && Objects.nonNull(orderItemMap.get(0L))) {
                orderItem.setReturnMoneySts(orderItemMap.get(0L));
            }
        }
        order.setOrderItems(orderItems);
        return ResponseEntity.ok(order);
    }


    /**
     * 订单项分包裹发货
     */
    @PutMapping("/orderItemsDelivery")
    public ResponseEntity<Void> orderItemsDelivery(@RequestBody DeliveryOrderItemParam deliveryOrderParam) {
        deliveryOrderService.saveDeliveriesInfo(deliveryOrderParam);
        return ResponseEntity.ok().build();
    }

    /**
     * 查询订单物流包裹信息
     */
    @PutMapping("/getOrderDeliveries/{orderNumber}")
    public ResponseEntity<List<DeliveryOrder>> getOrderDeliveries(@PathVariable("orderNumber") String orderNumber) {
        List<DeliveryOrder> deliveryOrders = deliveryOrderService.listDetailDelivery(orderNumber);
        return ResponseEntity.ok(deliveryOrders);
    }


    /**
     * 修改订单物流包裹信息
     */
    @PutMapping("/updateOrderDeliveries")
    public ResponseEntity<Void> updateOrderDeliveries(@RequestBody DvyOrderParam dvyOrderParam) {
        List<DeliveryOrder> deliveryOrders = dvyOrderParam.getDeliveryOrders();
        deliveryOrderService.updateOrderDeliveries(deliveryOrders);
        return ResponseEntity.ok().build();
    }


    /**
     * 获取信息
     */
    @GetMapping("/orderInfo/{orderNumber}")
    public ResponseEntity<OrderParam> info(@PathVariable("orderNumber") String orderNumber) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        Order order = orderService.getOrderDetailByOrderNumberAndShopId(orderNumber, shopId);
//        List<OrderItem> orderItems = orderItemService.getOrderItemsByOrderNumber(orderNumber);
//        UserAddrOrder userAddrOrder = userAddrOrderService.getById(order.getAddrOrderId());
//        order.setOrderItems(orderItems);
//        order.setUserAddrOrder(userAddrOrder);
        OrderParam orderParam = mapperFacade.map(order, OrderParam.class);
        orderParam.setScore(orderParam.getOrderItems().stream().mapToInt(OrderItem::getUseScore).sum());
        //查询包裹信息
        List<DeliveryOrder> deliveryOrders = deliveryOrderService.getAndDeliveryItemInfo(orderNumber);
        // 查询物流详情信息
        // 物流公司名称、官网、订单号、物流详情信息
        try {
            for (DeliveryOrder deliveryOrder : deliveryOrders) {
                // 查询交易单
                Delivery delivery = deliveryService.getById(deliveryOrder.getDvyId());
                // 解析的物流详情明细

                // 解析的物流详情明细
                OrderDetailRequest orderDetailRequest = new OrderDetailRequest();
                orderDetailRequest.setOrder_id(deliveryOrder.getDvyFlowId());
                OrderStatusResponse orderStatusResponse = paoTuiApi.deliveryRoute(orderDetailRequest);
                deliveryOrder.setDeliveryDto(orderStatusResponse);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new GlobalException("查询出错");
        }
        UserAddrOrder userAddrOrder = userAddrOrderService.selectByAddrOrderId(order.getAddrOrderId());
        orderParam.setUserAddrOrder(userAddrOrder);
        orderParam.setDeliveryExpresses(deliveryOrders);
        return ResponseEntity.ok(orderParam);
    }

}
