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

import cn.hutool.core.map.MapUtil;
import com.tmerclub.cloud.api.delivery.dto.StationSalesDTO;
import com.tmerclub.cloud.api.delivery.vo.StationVO;
import com.tmerclub.cloud.api.feign.SearchOrderFeignClient;
import com.tmerclub.cloud.api.order.constant.OrderStatus;
import com.tmerclub.cloud.api.vo.EsPageVO;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.database.dto.PageDTO;
import com.tmerclub.cloud.common.database.vo.PageVO;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.order.constant.OrderActivityType;
import com.tmerclub.cloud.common.order.dto.OrderSearchDTO;
import com.tmerclub.cloud.common.order.dto.OrderVirtualInfoDTO;
import com.tmerclub.cloud.common.order.vo.EsOrderItemVO;
import com.tmerclub.cloud.common.order.vo.EsOrderVO;
import com.tmerclub.cloud.common.order.vo.OrderVO;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.security.AuthUserContext;
import com.tmerclub.cloud.common.util.BeanUtil;
import com.tmerclub.cloud.delivery.dto.OrderStationDTO;
import com.tmerclub.cloud.delivery.dto.StationDTO;
import com.tmerclub.cloud.delivery.model.Station;
import com.tmerclub.cloud.delivery.service.StationService;
import com.tmerclub.cloud.order.vo.StationDetailVO;
import com.tmerclub.cloud.order.model.Order;
import com.tmerclub.cloud.order.service.OrderSelfStationService;
import com.tmerclub.cloud.order.service.OrderService;
import com.tmerclub.cloud.order.service.OrderVirtualInfoService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/**
 * 自提点信息
 *
 * @author tmerclub
 * @date 2020-12-07 15:10:01
 */
@RestController("appStationController")
@RequestMapping("/station")
@Tag(name = "用户自提点信息")
public class StationController {

    @Autowired
    private StationService stationService;
    @Autowired
    private OrderSelfStationService orderSelfStationService;
    @Autowired
    private OrderVirtualInfoService orderVirtualInfoService;
    @Autowired
    private OrderService orderService;
    @DubboReference
    private SearchOrderFeignClient searchOrderFeignClient;

    @GetMapping("/page")
    @Operation(summary = "获取自提点信息列表", description = "分页获取自提点信息列表")
    public ServerResponseEntity<PageVO<StationVO>> page(@Valid PageDTO pageDTO) {
        PageVO<StationVO> stationPage = stationService.page(pageDTO);
        return ServerResponseEntity.success(stationPage);
    }

    @GetMapping
    @Operation(summary = "获取自提点信息", description = "根据stationId获取自提点信息")
    public ServerResponseEntity<StationVO> getInfo() {
        Long stationId = AuthUserContext.get().getTenantId();
        return ServerResponseEntity.success(stationService.getByStationId(stationId));
    }

    @PutMapping
    @Operation(summary = "更新自提点信息", description = "更新自提点信息")
    public ServerResponseEntity<Void> update(@Valid @RequestBody StationDTO stationDTO) {
        Station station = BeanUtil.map(stationDTO, Station.class);
        station.setStationId(AuthUserContext.get().getTenantId());
        station.setAccount(null);
        stationService.update(station);
        return ServerResponseEntity.success();
    }

    @DeleteMapping
    @Operation(summary = "删除自提点信息", description = "根据自提点信息id删除自提点信息")
    public ServerResponseEntity<Void> delete(@RequestParam Long stationId) {
        stationService.deleteById(stationId);
        return ServerResponseEntity.success();
    }

    @GetMapping("/getStationIndexInfo")
    @Operation(summary = "自提点首页数据", description = "获取自提点首页数据")
    public ServerResponseEntity<StationVO> getStationIndexInfo() {
        Long stationId = AuthUserContext.get().getTenantId();
        StationVO stationVO = stationService.getByStationId(stationId);
        List<StationSalesDTO> stationSalesRecord = stationService.getStationSalesRecord(stationVO.getShopId(), stationId);
        stationVO.setStationSalesDTOList(stationSalesRecord);
        return ServerResponseEntity.success(stationVO);
    }

    @PostMapping("/userStation")
    @Operation(summary = "获取距离用户近的自提点")
    public ServerResponseEntity<PageVO<StationDetailVO>> getStationList(@Valid @RequestBody OrderStationDTO orderStationDTO) {
        PageVO<StationDetailVO> stationParams = stationService.getStationList(orderStationDTO.getPageDTO(), orderStationDTO);
        return ServerResponseEntity.success(stationParams);
    }

    @GetMapping("/orderStatusList")
    @Operation(summary = "订单列表信息", description = "根据订单状态获取订单列表信息，状态为0时获取所有订单")
    @Parameters(@Parameter(name = "status", description = "订单状态 1:待付款 2:待发货 3:待收货 4:待评价 5:成功 6:失败"))
    public ServerResponseEntity<EsPageVO<EsOrderVO>> orderStatusList(OrderSearchDTO orderSearchDTO) {
        Long stationId = AuthUserContext.get().getTenantId();
        orderSearchDTO.setStationId(stationId);
        if (Objects.equals(orderSearchDTO.getStatus(), OrderStatus.PAYED.value())) {
            orderSearchDTO.setWaitPurchase(0);
        }
        EsPageVO<EsOrderVO> data = searchOrderFeignClient.pageOrder(orderSearchDTO).getData();
        for (EsOrderVO esOrderVO : data.getList()) {
            Map<Long, List<EsOrderItemVO>> comboMap = esOrderVO.getOrderItems().stream().filter(orderItemVO -> Objects.equals(orderItemVO.getActivityType(), OrderActivityType.COMBO_PROD.value()))
                    .collect(Collectors.groupingBy(EsOrderItemVO::getActivityId));
            if (MapUtil.isEmpty(comboMap)) {
                continue;
            }
            Iterator<EsOrderItemVO> iterator = esOrderVO.getOrderItems().iterator();
            while (iterator.hasNext()) {
                EsOrderItemVO orderItem = iterator.next();
                if (Objects.equals(orderItem.getActivityType(), OrderActivityType.COMBO_PROD.value())) {
                    iterator.remove();
                }
                orderItem.setComboList(comboMap.get(orderItem.getOrderItemId()));
            }
        }
        return ServerResponseEntity.success(data);
    }

    @GetMapping("/getCode")
    @Operation(summary = "自提点二维码信息", description = "自提点二维码信息")
    public ServerResponseEntity<String> getCode() {
        Long stationId = AuthUserContext.get().getTenantId();
        StationVO station = stationService.getStationInfoById(stationId);
        String code = station.getShopId() + "#station#" + stationId;
        return ServerResponseEntity.success(code);
    }

    @GetMapping("/getStationOrderByCode")
    @Operation(summary = "通过提货码获取自提订单或虚拟订单", description = "自提点输入提货码获取自提订单或虚拟订单")
    @Parameter(name = "code", description = "提货码", required = true)
    public ServerResponseEntity<OrderVO> getStationOrderByCode(@RequestParam("code") String code) {
        OrderVO orderVO = orderSelfStationService.getOrderByStationCode(AuthUserContext.get().getTenantId(), code);
        return ServerResponseEntity.success(orderVO);
    }


    @PutMapping("/orderStationByOrderId")
    @Operation(summary = "自提点提货", description = "自提点提货操作")
    @Parameter(name = "orderIds", description = "订单编号数组", required = true)
    public ServerResponseEntity<Boolean> orderStationByOrderId(@RequestBody String orderIds) {
        List<String> orderIdList = Arrays.asList(orderIds.split(","));
        List<Long> ids = new ArrayList<>(Constant.INITIAL_CAPACITY);
        orderIdList.forEach(s -> ids.add(Long.parseLong(s)));
        orderService.orderStationByOrderId(ids, null, AuthUserContext.get().getTenantId());
        return ServerResponseEntity.success(Boolean.TRUE);
    }

    @PutMapping("/orderWriteOffByOrderId")
    @Operation(summary = "虚拟商品订单核销操作", description = "虚拟商品订单核销操作")
    public ServerResponseEntity<Boolean> orderWriteOffByOrderId(@RequestBody OrderVirtualInfoDTO orderVirtualInfoDTO) {
        Long orderId = orderVirtualInfoDTO.getOrderId();
        Long stationId = AuthUserContext.get().getTenantId();
        if (Objects.isNull(orderId)) {
            // 订单不存在
            throw new LuckException("订单不存在");
        }
        Order order = orderService.getByOrderId(orderId);
        if (Objects.isNull(order) || order.getOrderMold() == 0) {
            // 订单不存在
            throw new LuckException("订单不存在");
        }
        orderVirtualInfoService.orderWriteOffByOrderId(orderVirtualInfoDTO, order, stationId);
        return ServerResponseEntity.success(Boolean.TRUE);
    }

}
