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

import cn.hutool.core.collection.CollectionUtil;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.order.dto.OrderVirtualInfoDTO;
import com.tmerclub.cloud.common.order.vo.OrderVO;
import com.tmerclub.cloud.common.order.vo.OrderVirtualInfoVO;
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.order.model.Order;
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.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
/**
 * @author lanhai
 */
@RestController("multishopOrderVirtualInfoController")
@RequestMapping("/m/order_virtual_info")
@Tag(name = "multishop-虚拟订单接口")
public class OrderVirtualInfoController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderVirtualInfoService orderVirtualInfoService;

    @GetMapping("/orderInfo/{orderId}")
    @Operation(summary = "根据订单号获取虚拟订单信息", description = "根据订单号获取订单信息")
    public ServerResponseEntity<OrderVO> info(@PathVariable("orderId") Long orderId) {
        Long shopId = AuthUserContext.get().getTenantId();
        Order order = orderService.getOrderAndOrderItemData(orderId, shopId);
        OrderVO orderVO = BeanUtil.map(order, OrderVO.class);
        if (Objects.equals(order.getOrderMold(), 1)) {
            List<OrderVirtualInfoVO> orderVirtualInfos = orderVirtualInfoService.getByOrderIdAndStationId(orderId, null);
            if (CollectionUtil.isNotEmpty(orderVirtualInfos)) {
                orderVO.setOrderVirtualInfoList(orderVirtualInfos);
            }
        }
        return ServerResponseEntity.success(orderVO);
    }

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