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

import com.tmerclub.cloud.api.delivery.vo.StationVO;
import com.tmerclub.cloud.api.feign.SearchOrderFeignClient;
import com.tmerclub.cloud.api.seckill.feign.SeckillFeignClient;
import com.tmerclub.cloud.api.vo.EsPageVO;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.order.dto.OrderSearchDTO;
import com.tmerclub.cloud.common.order.vo.EsOrderVO;
import com.tmerclub.cloud.common.order.vo.OrderSelfStationVO;
import com.tmerclub.cloud.common.order.vo.ShopCartOrderMergerVO;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.security.AuthUserContext;
import com.tmerclub.cloud.delivery.manager.DeliveryManager;
import com.tmerclub.cloud.order.dto.OrderStationWriteOffDTO;
import com.tmerclub.cloud.order.service.OrderSelfStationService;
import com.tmerclub.cloud.order.service.OrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
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.*;

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

/**
 * @author Lanhai
 */
@RestController("appMyStationController")
@RequestMapping("/my_station_order")
@Tag(name = "用户自提订单接口")
public class MyStationOrderController {

    private final Logger LOGGER = LoggerFactory.getLogger(MyStationOrderController.class);

    @Autowired
    private DeliveryManager deliveryManager;

    @DubboReference
    private SearchOrderFeignClient searchOrderFeignClient;

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderSelfStationService orderSelfStationService;
    @Autowired
    private SeckillFeignClient seckillFeignClient;

    @GetMapping("/station_detail")
    @Operation(summary = "订单详情自提信息", description = "根据订单号获取订单详情自提信息")
    @Parameter(name = "orderId", description = "订单号", required = true)
    public ServerResponseEntity<OrderSelfStationVO> orderDetail(@RequestParam("orderId") Long orderId,
                                                                @RequestParam(value = "lat", required = false) Double lat,
                                                                @RequestParam(value = "lng", required = false) Double lng) {
        Long userId = AuthUserContext.get().getUserId();
        // 查询一下redis有没有数据,因为秒杀订单还存在redis
        ServerResponseEntity<ShopCartOrderMergerVO> seckillOrderByRedisResp = seckillFeignClient.getSeckillOrderByRedis(orderId, userId);
        if (!seckillOrderByRedisResp.isSuccess()) {
            throw new LuckException(seckillOrderByRedisResp.getMsg());
        }
        OrderSelfStationVO orderSelfStation = null;
        if(Objects.nonNull(seckillOrderByRedisResp.getData())){
            orderSelfStation = seckillOrderByRedisResp.getData().getOrderSelfStation();
        }
        OrderSelfStationVO orderSelfStationVO = orderSelfStationService.getStationByOrderId(orderSelfStation,orderId);
        if (lat != null && lng != null) {
            LOGGER.info("根据经纬度计算实时距离，lat:{},lng:{}", lat, lng);
            Double distance = orderSelfStationService.setStationDistance(orderSelfStationVO.getStationId(), lat, lng);
            orderSelfStationVO.setDistance(distance);
        }
        return ServerResponseEntity.success(orderSelfStationVO);
    }

    @GetMapping("/get_order_by_station_id")
    @Operation(summary = "用户扫自提点码", description = "用户扫自提点码获取自提订单列表")
    @Parameter(name = "stationId", description = "自提点id", required = true)
    public ServerResponseEntity<EsPageVO<EsOrderVO>> getOrderListByStationId(OrderSearchDTO orderSearchDTO) {
        Long userId = AuthUserContext.get().getUserId();
        StationVO stationVO = deliveryManager.getStation(orderSearchDTO.getStationId());
        if (Objects.isNull(stationVO)) {
            throw new LuckException("该自提点不存在");
        }
        orderSearchDTO.setUserId(userId);
        orderSearchDTO.setWaitPurchase(0);
        orderSearchDTO.setOrderMold(1);
        orderSearchDTO.setShopId(stationVO.getShopId());
        EsPageVO<EsOrderVO> page = searchOrderFeignClient.pageOrder(orderSearchDTO).getData();
        if (page.getList() != null) {
            List<OrderSelfStationVO> orderSelfStationVOList = orderSelfStationService.getOrderSelfStationByStationIdOrShopId(userId, orderSearchDTO.getStationId(), null);
            LOGGER.info("根据订单id获取自提信息，orderSelfStationVOList:{}", orderSelfStationVOList);
            Map<Long, OrderSelfStationVO> orderSelfStationMap = orderSelfStationVOList.stream().collect(Collectors.toMap(OrderSelfStationVO::getOrderId, (k) -> k));
            page.getList().forEach(s -> s.setOrderSelfStationVO(orderSelfStationMap.get(s.getOrderId())));
        }
        return ServerResponseEntity.success(page);
    }

    @GetMapping("/get_order_by_shop_id")
    @Operation(summary = "用户扫商家码", description = "用户扫商家码获取自提订单列表")
    @Parameter(name = "shopId", description = "店铺id", required = true)
    public ServerResponseEntity<EsPageVO<EsOrderVO>> getOrderListByShopId(OrderSearchDTO orderSearchDTO) {
        Long userId = AuthUserContext.get().getUserId();
        orderSearchDTO.setUserId(userId);
        orderSearchDTO.setWaitPurchase(0);
        EsPageVO<EsOrderVO> page = searchOrderFeignClient.pageOrder(orderSearchDTO).getData();
        List<OrderSelfStationVO> orderSelfStationVOList = orderSelfStationService.getOrderSelfStationByStationIdOrShopId(userId, null, orderSearchDTO.getShopId());
        Map<Long, OrderSelfStationVO> orderSelfStationMap = orderSelfStationVOList.stream().collect(Collectors.toMap(OrderSelfStationVO::getOrderId, (k) -> k));
        page.getList().forEach(s -> s.setOrderSelfStationVO(orderSelfStationMap.get(s.getOrderId())));
        return ServerResponseEntity.success(page);
    }

    @PutMapping("/orderStationByOrderId")
    @Operation(summary = "用户提货操作", description = "用户提货操作")
    public ServerResponseEntity<Boolean> orderStationByOrderId(@RequestBody OrderStationWriteOffDTO orderStationWriteOffDTO) {
        orderService.orderStationByOrderId(orderStationWriteOffDTO.getOrderIds(), AuthUserContext.get().getUserId(), orderStationWriteOffDTO.getStationId());
        return ServerResponseEntity.success(Boolean.TRUE);
    }

}
