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

import cn.hutool.core.map.MapUtil;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.order.constant.OrderActivityType;
import com.tmerclub.cloud.common.order.dto.OrderInvoiceDTO;
import com.tmerclub.cloud.common.order.vo.EsOrderItemVO;
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.constant.InvoiceHeaderType;
import com.tmerclub.cloud.order.constant.OrderInvoiceState;
import com.tmerclub.cloud.order.model.Order;
import com.tmerclub.cloud.order.model.OrderInvoice;
import com.tmerclub.cloud.order.service.OrderInvoiceService;
import com.tmerclub.cloud.order.service.OrderService;
import com.tmerclub.cloud.order.vo.MyOrderItemVO;
import com.tmerclub.cloud.order.vo.OrderInvoiceVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/**
 * @author Pineapple
 * @date 2021/8/2 8:59
 */
@RestController("appOrderInvoiceController")
@RequestMapping("/order_invoice")
@Tag(name = "用户端订单发票")
public class OrderInvoiceController {

    private final Logger LOGGER = LoggerFactory.getLogger(OrderInvoiceController.class);
    @Autowired
    private OrderInvoiceService orderInvoiceService;
    @Autowired
    private OrderService orderService;


    @GetMapping
    @Operation(summary = "获取发票信息", description = "根据orderInvoiceId获取")
    public ServerResponseEntity<OrderInvoiceVO> getByOrderInvoiceId(@RequestParam Long orderInvoiceId) {
        OrderInvoiceVO orderInvoice = orderInvoiceService.getById(orderInvoiceId);
        if (Objects.nonNull(orderInvoice.getUserId()) && !Objects.equals(orderInvoice.getUserId(), AuthUserContext.get().getUserId())) {
            LOGGER.error("无法查看非当前用户的发票信息");
            //非当前用户的发票信息
            throw new LuckException("无法查看非当前用户的发票信息");
        }
        Map<Long, List<MyOrderItemVO>> comboMap = orderInvoice.getOrderItemVOList().stream()
                .filter(order -> Objects.equals(order.getActivityType(), OrderActivityType.COMBO_PROD.value()))
                .collect(Collectors.groupingBy(MyOrderItemVO::getActivityId));
        if (MapUtil.isEmpty(comboMap)) {
            return ServerResponseEntity.success(orderInvoice);
        }
        Iterator<MyOrderItemVO> iterator = orderInvoice.getOrderItemVOList().iterator();
        while (iterator.hasNext()) {
            MyOrderItemVO orderItem = iterator.next();
            if (Objects.equals(orderItem.getActivityType(), OrderActivityType.COMBO_PROD.value())) {
                iterator.remove();
            }
            orderItem.setComboList(comboMap.get(orderItem.getOrderItemId()));
        }
        return ServerResponseEntity.success(orderInvoice);
    }

    @PostMapping
    @Operation(summary = "申请开票", description = "保存申请信息")
    public ServerResponseEntity<Void> save(@Valid @RequestBody OrderInvoiceDTO orderInvoiceDTO) {
        if (Objects.isNull(orderInvoiceDTO.getShopId())) {
            LOGGER.error("店铺id不能为空");
            throw new LuckException("店铺id不能为空");
        }
        Order order = orderService.getByOrderId(orderInvoiceDTO.getOrderId());
        if (Objects.isNull(order)) {
            throw new LuckException("订单不存在");
        }
        Long orderId = orderInvoiceService.getByOrderId(orderInvoiceDTO.getOrderId(), orderInvoiceDTO.getShopId(), null);
        if (Objects.nonNull(orderId)) {
            LOGGER.error("该订单已经申请发票，请勿重复申请！");
            throw new LuckException("该订单已经申请发票，请勿重复申请！");
        }
        OrderInvoice orderInvoice = BeanUtil.map(orderInvoiceDTO, OrderInvoice.class);
        orderInvoice.setShopId(orderInvoiceDTO.getShopId());
        if (Objects.equals(InvoiceHeaderType.PERSONAL.value(), orderInvoice.getHeaderType())) {
            LOGGER.error("个人发票不需要填写税号");
            orderInvoice.setInvoiceTaxNumber(null);
        }
        orderInvoice.setSupplierId(Objects.isNull(order.getSupplierId()) ? 0L : order.getSupplierId());
        orderInvoice.setInvoiceState(OrderInvoiceState.APPLICATION.value());
        orderInvoice.setApplicationTime(new Date());
        orderInvoiceService.save(AuthUserContext.get().getUserId(), orderInvoice);
        return ServerResponseEntity.success();
    }

    @PutMapping
    @Operation(summary = "申请换开", description = "更新发票信息")
    public ServerResponseEntity<Void> update(@Valid @RequestBody OrderInvoiceDTO orderInvoiceDTO) {
        OrderInvoice orderInvoice = BeanUtil.map(orderInvoiceDTO, OrderInvoice.class);
        orderInvoice.setInvoiceState(OrderInvoiceState.APPLICATION.value());
        orderInvoice.setApplicationTime(new Date());
        if (Objects.equals(InvoiceHeaderType.PERSONAL.value(), orderInvoice.getHeaderType())) {
            LOGGER.error("个人发票不需要填写税号");
            orderInvoice.setInvoiceTaxNumber(null);
        }
        orderInvoiceService.update(orderInvoice);
        return ServerResponseEntity.success();
    }
}
