
package com.tmerclub.cloud.order.controller.platform;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import com.tmerclub.cloud.api.multishop.feign.ShopDetailFeignClient;
import com.tmerclub.cloud.api.multishop.vo.ShopDetailVO;
import com.tmerclub.cloud.api.order.constant.OrderStatus;
import com.tmerclub.cloud.api.supplier.feign.SupplierDetailFeignClient;
import com.tmerclub.cloud.api.supplier.vo.SupplierApiDetailVO;
import com.tmerclub.cloud.api.user.feign.UserFeignClient;
import com.tmerclub.cloud.api.user.vo.UserApiVO;
import com.tmerclub.cloud.api.vo.EsPageVO;
import com.tmerclub.cloud.common.database.dto.PageDTO;
import com.tmerclub.cloud.common.order.constant.DeliveryType;
import com.tmerclub.cloud.common.order.constant.OrderActivityType;
import com.tmerclub.cloud.common.order.dto.OrderSearchDTO;
import com.tmerclub.cloud.common.order.vo.*;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.util.BeanUtil;
import com.tmerclub.cloud.order.constant.Constant;
import com.tmerclub.cloud.order.model.Order;
import com.tmerclub.cloud.order.model.OrderAddr;
import com.tmerclub.cloud.order.service.OrderAddrService;
import com.tmerclub.cloud.order.service.OrderExcelService;
import com.tmerclub.cloud.order.service.OrderSelfStationService;
import com.tmerclub.cloud.order.service.OrderService;
import io.swagger.v3.oas.annotations.Operation;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 平台订单管理
 *
 * @author: cl
 * @date: 2021-05-06 16:15:15
 */
@RestController("platformOrderController")
@RequestMapping("/p/order")
public class OrderController {
    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderExcelService orderExcelService;
    @Autowired
    private OrderAddrService orderAddrService;
    @DubboReference
    private UserFeignClient userFeignClient;
    @Autowired
    private OrderSelfStationService orderSelfStationService;
    @DubboReference
    private SupplierDetailFeignClient supplierDetailFeignClient;
    @DubboReference
    private ShopDetailFeignClient shopDetailFeignClient;

    /**
     * 分页获取
     */
    @GetMapping("/page")
    public ServerResponseEntity<EsPageVO<EsOrderVO>> page(OrderSearchDTO orderSearchDTO) {
        if (Objects.equals(orderSearchDTO.getStatus(), OrderStatus.PAYED.value())) {
            orderSearchDTO.setWaitPurchase(0);
        }
        if (Objects.equals(orderSearchDTO.getStatus(), Constant.WAIT_PURCHASES_STATUS)) {
            orderSearchDTO.setStatus(OrderStatus.PAYED.value());
            orderSearchDTO.setWaitPurchase(1);
        }
        // 判断处理供应商名称和店铺名称,防止因改名而导致的数据错误
        Map<Long, String> shopNameMap = orderService.checkShopName(orderSearchDTO);
        Map<Long, String> supplierNameMap = orderService.checkSupplierName(orderSearchDTO);
        EsPageVO<EsOrderVO> orderPage = orderService.orderPage(orderSearchDTO);
        for (EsOrderVO esOrderVO : orderPage.getList()) {
            if (StrUtil.isNotBlank(esOrderVO.getMobile())) {
                esOrderVO.setMobile(PhoneUtil.hideBetween(esOrderVO.getMobile()).toString());
            }
        }
        // 数据准备
        List<Long> supplierIds = new ArrayList<>(Constant.INITIAL_CAPACITY);
        List<Long> shopIds = new ArrayList<>(Constant.INITIAL_CAPACITY);
        List<Long> userIds = new ArrayList<>(Constant.INITIAL_CAPACITY);
        for (EsOrderVO orderVO : orderPage.getList()) {
            userIds.add(orderVO.getUserId());
            supplierIds.add(orderVO.getSupplierId());
            shopIds.add(orderVO.getShopId());
        }
        List<UserApiVO> userList = userFeignClient.getUserByUserIds(userIds).getData();
        Map<Long, String> userMap = userList.stream().collect(Collectors.toMap(UserApiVO::getUserId, UserApiVO::getNickName));
        if (CollUtil.isEmpty(supplierNameMap) && CollUtil.isNotEmpty(supplierIds)) {
            logger.info("补充供应商订单消息");
            List<SupplierApiDetailVO> supplierList = supplierDetailFeignClient.listBySupplierIds(supplierIds).getData();
            supplierNameMap.putAll(supplierList.stream().collect(Collectors.toMap(SupplierApiDetailVO::getSupplierId, SupplierApiDetailVO::getSupplierName)));
        }
        if (CollUtil.isEmpty(shopNameMap)) {
            logger.info("补充店铺订单消息");
            List<ShopDetailVO> shopList = shopDetailFeignClient.listByShopIds(shopIds).getData();
            shopNameMap.putAll(shopList.stream().collect(Collectors.toMap(ShopDetailVO::getShopId, ShopDetailVO::getShopName)));
        }
        for (EsOrderVO orderVO : orderPage.getList()) {
            orderVO.setShopName(null == shopNameMap.get(orderVO.getShopId()) ? null : shopNameMap.get(orderVO.getShopId()));
            orderVO.setSupplierName(null == supplierNameMap.get(orderVO.getSupplierId()) ? null : supplierNameMap.get(orderVO.getSupplierId()));
            orderVO.setUserName(null == userMap.get(orderVO.getUserId()) ? "*用户已注销*" : userMap.get(orderVO.getUserId()));
            //赠品处理
            Map<Long, List<EsOrderItemVO>> map = orderVO.getOrderItems().stream().filter(s -> Objects.equals(s.getActivityType(), OrderActivityType.GIVEAWAY.value()))
                    .collect(Collectors.groupingBy(EsOrderItemVO::getActivityId));
            //组合处理
            Map<Long, List<EsOrderItemVO>> comboMap = orderVO.getOrderItems().stream().filter(s -> Objects.equals(s.getActivityType(), OrderActivityType.COMBO_PROD.value()))
                    .collect(Collectors.groupingBy(EsOrderItemVO::getActivityId));
            // 如果没有赠品，就不需要处理
            if (MapUtil.isEmpty(map) && MapUtil.isEmpty(comboMap)) {
                continue;
            }
            // 将赠品放到对应的主订单项中
            Iterator<EsOrderItemVO> iterator = orderVO.getOrderItems().iterator();
            while (iterator.hasNext()) {
                EsOrderItemVO myOrderItemDto = iterator.next();
                // 移除赠品的订单项，进入下一个循环
                if (Objects.equals(myOrderItemDto.getActivityType(), OrderActivityType.GIVEAWAY.value()) || Objects.equals(myOrderItemDto.getActivityType(), OrderActivityType.COMBO_PROD.value())) {
                    iterator.remove();
                    continue;
                }
                // 主订单项插入赠品订单项
                if (map.containsKey(myOrderItemDto.getOrderItemId())) {
                    myOrderItemDto.setGiveawayList(map.get(myOrderItemDto.getOrderItemId()));
                }
                // 主订单项插入组合订单项
                if (comboMap.containsKey(myOrderItemDto.getOrderItemId())) {
                    myOrderItemDto.setComboList(comboMap.get(myOrderItemDto.getOrderItemId()));
                }
            }
        }
        return ServerResponseEntity.success(orderPage);
    }

    /**
     * 获取信息
     */
    @GetMapping("/orderInfo/{orderId}")
    public ServerResponseEntity<OrderVO> info(@PathVariable("orderId") Long orderId) {
        // 订单和订单项
        Order order = orderService.getOrderAndOrderItemData(orderId, null);
        OrderVO orderVO = BeanUtil.map(order, OrderVO.class);
        //如果是自提订单就没有收货地址
        if (!Objects.equals(orderVO.getDeliveryType(), DeliveryType.STATION.value())) {
            // 详情用户收货地址
            OrderAddr orderAddr = orderAddrService.getById(order.getOrderAddrId());
            if (Objects.nonNull(orderAddr)) {
                orderAddr.setMobile(PhoneUtil.hideBetween(orderAddr.getMobile()).toString());
            }
            orderVO.setOrderAddr(BeanUtil.map(orderAddr, OrderAddrVO.class));
        }
        // 处理下赠品
        // 获取赠品map
        Map<Long, List<OrderItemVO>> giveawayMap = orderVO.getOrderItems().stream().filter(item -> Objects.equals(item.getActivityType(), OrderActivityType.GIVEAWAY.value()))
                .collect(Collectors.groupingBy(OrderItemVO::getActivityId));
        // 获取组合map
        Map<Long, List<OrderItemVO>> comboMap = orderVO.getOrderItems().stream().filter(item -> Objects.equals(item.getActivityType(), OrderActivityType.COMBO_PROD.value()))
                .collect(Collectors.groupingBy(OrderItemVO::getActivityId));
        List<OrderItemVO> orderItemDbList = new ArrayList<>(Constant.INITIAL_CAPACITY);
        for (OrderItemVO orderItem : orderVO.getOrderItems()) {
            // 赠品订单项不需要进行处理
            if (Objects.equals(orderItem.getActivityType(), OrderActivityType.GIVEAWAY.value()) || Objects.equals(orderItem.getActivityType(), OrderActivityType.COMBO_PROD.value())) {
                continue;
            }
            // 放入赠品
            if (giveawayMap.containsKey(orderItem.getOrderItemId())) {
                orderItem.setGiveawayList(giveawayMap.get(orderItem.getOrderItemId()));
            }
            // 放入组合
            if (comboMap.containsKey(orderItem.getOrderItemId())) {
                orderItem.setComboItemList(comboMap.get(orderItem.getOrderItemId()));
            }
            orderItemDbList.add(orderItem);
        }
        orderVO.setOrderItems(orderItemDbList);
        // 补充自提点信息
        if (order.getDeliveryType() != null
                && DeliveryType.STATION.value().equals(order.getDeliveryType())) {
            logger.info("自提订单，补充自提点信息");
            OrderSelfStationVO stationVO = orderSelfStationService.getStationByOrderId(null, orderId);
            orderVO.setOrderSelfStationVO(stationVO);
        }
        orderVO.setOrderItems(orderItemDbList);
        return ServerResponseEntity.success(orderVO);
    }


    @GetMapping("/get_order_by_userId")
    @Operation(summary = "分页获取某个用户的订单数据", description = "分页获取某个用户的订单数据")
    public ServerResponseEntity<EsPageVO<EsOrderVO>> getOrderByUserId(PageDTO pageDTO, String userId) {
        EsPageVO<EsOrderVO> pages = orderService.pageByUserId(pageDTO, userId);
        return ServerResponseEntity.success(pages);
    }
}
