package com.gxwebsoft.common.system.controller;

import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.TenantSubscription;
import com.gxwebsoft.common.system.entity.TenantSubscriptionOrder;
import com.gxwebsoft.common.system.service.TenantSubscriptionOrderService;
import com.gxwebsoft.common.system.service.TenantSubscriptionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

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

/**
 * 租户订阅控制器
 *
 * @author WebSoft
 * @since 2025-12-12
 */
@Tag(name = "租户订阅管理")
@RestController
@RequestMapping("/api/system/subscription")
public class TenantSubscriptionController extends BaseController {

    @Resource
    private TenantSubscriptionService tenantSubscriptionService;

    @Resource
    private TenantSubscriptionOrderService tenantSubscriptionOrderService;

    @Operation(summary = "查询当前租户订阅信息")
    @GetMapping("/current")
    public ApiResult<TenantSubscription> getCurrentSubscription() {
        Integer tenantId = getTenantId();
        if (tenantId == null) {
            return fail("租户ID不存在", null);
        }
        TenantSubscription subscription = tenantSubscriptionService.getByTenantId(tenantId);
        return success(subscription);
    }

    @Operation(summary = "检查订阅是否有效")
    @GetMapping("/check")
    public ApiResult<Map<String, Object>> checkSubscription() {
        Integer tenantId = getTenantId();
        if (tenantId == null) {
            return fail("租户ID不存在", null);
        }

        boolean isValid = tenantSubscriptionService.isSubscriptionValid(tenantId);
        boolean isExpired = tenantSubscriptionService.isSubscriptionExpired(tenantId);

        Map<String, Object> result = new HashMap<>();
        result.put("isValid", isValid);
        result.put("isExpired", isExpired);

        return success(result);
    }

    @Operation(summary = "查询订阅激活状态")
    @GetMapping("/active")
    public ApiResult<Map<String, Object>> getActiveStatus() {
        Integer tenantId = getTenantId();
        if (tenantId == null) {
            return fail("租户ID不存在", null);
        }

        TenantSubscription subscription = tenantSubscriptionService.getByTenantId(tenantId);
        Map<String, Object> result = new HashMap<>();

        if (subscription == null) {
            result.put("active", false);
            result.put("message", "未订阅任何套餐");
        } else {
            boolean isActive = subscription.getStatus() == 1 && subscription.getIsExpired() == 0;
            result.put("active", isActive);
            result.put("version", subscription.getVersion());
            result.put("packageId", subscription.getPackageId());
            result.put("endTime", subscription.getEndTime());
            result.put("isTrial", subscription.getIsTrial());
        }

        return success(result);
    }

    @Operation(summary = "创建试用订单")
    @PostMapping("/trial")
    public ApiResult<TenantSubscriptionOrder> createTrialOrder() {
        Integer tenantId = getTenantId();
        Integer userId = getLoginUserId();

        if (tenantId == null || userId == null) {
            return fail("参数错误", null);
        }

        TenantSubscriptionOrder order = tenantSubscriptionOrderService.createTrialOrder(tenantId, userId);
        return success("试用开通成功", order);
    }

    @Operation(summary = "创建订阅订单")
    @PostMapping("/order")
    public ApiResult<TenantSubscriptionOrder> createOrder(@RequestParam Integer packageId,
                                                          @RequestParam Integer payType) {
        Integer tenantId = getTenantId();
        Integer userId = getLoginUserId();

        if (tenantId == null || userId == null) {
            return fail("参数错误", null);
        }

        TenantSubscriptionOrder order = tenantSubscriptionOrderService.createOrder(packageId, payType, tenantId, userId);
        return success("订单创建成功", order);
    }

    @Operation(summary = "查询订单列表")
    @GetMapping("/orders")
    public ApiResult<PageResult<TenantSubscriptionOrder>> listOrders(@RequestParam(defaultValue = "1") Integer page,
                                                                      @RequestParam(defaultValue = "10") Integer limit) {
        Integer tenantId = getTenantId();
        if (tenantId == null) {
            return fail("租户ID不存在", null);
        }

        PageResult<TenantSubscriptionOrder> result = tenantSubscriptionOrderService.pageByTenant(tenantId, page, limit);
        return success(result);
    }

    @Operation(summary = "根据订单号查询订单")
    @GetMapping("/order/{orderNo}")
    public ApiResult<TenantSubscriptionOrder> getOrderByNo(@PathVariable String orderNo) {
        TenantSubscriptionOrder order = tenantSubscriptionOrderService.getByOrderNo(orderNo);
        if (order == null) {
            return fail("订单不存在", null);
        }
        return success(order);
    }

    @Operation(summary = "取消订单")
    @PostMapping("/order/cancel")
    public ApiResult<?> cancelOrder(@RequestParam String orderNo,
                                    @RequestParam(required = false) String cancelReason) {
        boolean success = tenantSubscriptionOrderService.cancelOrder(orderNo, cancelReason);
        if (success) {
            return success("订单已取消");
        }
        return fail("取消失败", null);
    }

    @Operation(summary = "设置自动续费")
    @PostMapping("/auto-renewal")
    public ApiResult<?> setAutoRenewal(@RequestParam Integer autoRenewal,
                                       @RequestParam(required = false) Integer renewalPackageId) {
        Integer tenantId = getTenantId();
        if (tenantId == null) {
            return fail("租户ID不存在", null);
        }

        boolean success = tenantSubscriptionService.setAutoRenewal(tenantId, autoRenewal, renewalPackageId);
        if (success) {
            return success(autoRenewal == 1 ? "自动续费已开启" : "自动续费已关闭");
        }
        return fail("设置失败", null);
    }

    @Operation(summary = "升级套餐")
    @PostMapping("/upgrade")
    public ApiResult<?> upgradeSubscription(@RequestParam Integer newPackageId) {
        Integer tenantId = getTenantId();
        if (tenantId == null) {
            return fail("租户ID不存在", null);
        }

        boolean success = tenantSubscriptionService.upgradeSubscription(tenantId, newPackageId);
        if (success) {
            return success("升级成功");
        }
        return fail("升级失败", null);
    }
}
