package com.gxwebsoft.shop.controller;

import cn.hutool.core.util.ObjectUtil;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.shop.dto.RefundedOrderGltRepairRequest;
import com.gxwebsoft.shop.service.ShopOrderGltRepairService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 历史订单修复：用于对“已退款的旧订单”补偿撤销水票相关数据。
 */
@Tag(name = "订单修复")
@RestController
@RequestMapping("/api/shop/shop-order/repair")
public class ShopOrderGltRepairController extends BaseController {

    @Resource
    private ShopOrderGltRepairService shopOrderGltRepairService;

    @PreAuthorize("hasAuthority('shop:shopOrder:manage')")
    @Operation(summary = "修复：已退款旧订单补偿撤销水票/释放计划/送水单（支持dryRun预览）")
    @PostMapping("/revoke-glt-after-refund")
    public ApiResult<?> revokeGltAfterRefund(@RequestBody RefundedOrderGltRepairRequest req) {
        if (req == null) {
            return fail("请求体不能为空");
        }

        Integer tenantId = ObjectUtil.defaultIfNull(req.getTenantId(), getTenantId());
        if (tenantId == null) {
            return fail("tenantId不能为空");
        }

        boolean dryRun = req.getDryRun() == null || req.getDryRun();

        // 防误操作：既未指定订单，也未指定时间窗口时，只允许 dryRun
        boolean noTargets = (req.getOrderIds() == null || req.getOrderIds().isEmpty())
            && (req.getOrderNos() == null || req.getOrderNos().isEmpty())
            && req.getRefundTimeStart() == null
            && req.getRefundTimeEnd() == null;
        if (noTargets && !dryRun) {
            return fail("请指定 orderIds/orderNos 或 refundTimeStart/refundTimeEnd；否则仅允许 dryRun=true 预览");
        }

        ShopOrderGltRepairService.RepairResult r = shopOrderGltRepairService.revokeTicketsForRefundedOrders(
            tenantId,
            req.getOrderIds(),
            req.getOrderNos(),
            req.getRefundTimeStart(),
            req.getRefundTimeEnd(),
            req.getBatchSize(),
            dryRun
        );

        Map<String, Object> data = new HashMap<>();
        data.put("tenantId", tenantId);
        data.put("dryRun", r.dryRun());
        data.put("scannedOrders", r.scannedOrders());
        data.put("ordersWithTicketsRevoked", r.ordersWithTicketsRevoked());
        data.put("revokedTicketCount", r.revokedTicketCount());
        data.put("processedOrderIds", r.processedOrderIds());
        return success(data);
    }
}

