package com.erp.tenant.controller;

import com.erp.common.core.model.ApiResponse;
import com.erp.tenant.dto.*;
import com.erp.tenant.service.TenantService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import com.erp.common.core.model.PageResponse;
import java.util.Map;

/**
 * 租户管理控制器（超级管理员使用）
 */
@Slf4j
@RestController
@RequestMapping("/api/admin/tenants")
@RequiredArgsConstructor
public class TenantAdminController {
    
    private final TenantService tenantService;
    
    // ==================== 租户管理 ====================
    
    /**
     * 获取租户列表
     */
    @GetMapping
    public ApiResponse<PageResponse<TenantListResponse>> listTenants(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Boolean expired,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "15") Integer pageSize) {
        
        return ApiResponse.success(tenantService.listTenants(keyword, status, expired, page, pageSize));
    }
    
    /**
     * 获取租户详情
     */
    @GetMapping("/{id}")
    public ApiResponse<TenantDetailResponse> getTenantById(@PathVariable Long id) {
        return ApiResponse.success(tenantService.getTenantById(id));
    }
    
    /**
     * 根据编码获取租户
     */
    @GetMapping("/code/{code}")
    public ApiResponse<TenantDetailResponse> getTenantByCode(@PathVariable String code) {
        return ApiResponse.success(tenantService.getTenantByCode(code));
    }
    
    /**
     * 创建租户
     */
    @PostMapping
    public ApiResponse<TenantDetailResponse> createTenant(@Valid @RequestBody CreateTenantRequest request) {
        return ApiResponse.success("创建成功", tenantService.createTenant(request));
    }
    
    /**
     * 更新租户
     */
    @PutMapping("/{id}")
    public ApiResponse<TenantDetailResponse> updateTenant(
            @PathVariable Long id,
            @Valid @RequestBody UpdateTenantRequest request) {
        return ApiResponse.success("更新成功", tenantService.updateTenant(id, request));
    }
    
    /**
     * 删除租户
     */
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteTenant(@PathVariable Long id) {
        tenantService.deleteTenant(id);
        return ApiResponse.success("删除成功", null);
    }
    
    /**
     * 切换租户状态
     */
    @PostMapping("/{id}/toggle-status")
    public ApiResponse<Map<String, Object>> toggleStatus(@PathVariable Long id) {
        TenantService.TenantStatusVO statusVO = tenantService.toggleStatus(id);
        return ApiResponse.success(statusVO.getStatusLabel(), Map.of(
                "id", statusVO.getId(),
                "status", statusVO.getStatus(),
                "statusLabel", statusVO.getStatusLabel()
        ));
    }
    
    /**
     * 暂停租户
     */
    @PostMapping("/{id}/suspend")
    public ApiResponse<Void> suspendTenant(@PathVariable Long id) {
        tenantService.suspendTenant(id);
        return ApiResponse.success("已暂停", null);
    }
    
    /**
     * 恢复租户
     */
    @PostMapping("/{id}/activate")
    public ApiResponse<Void> activateTenant(@PathVariable Long id) {
        tenantService.activateTenant(id);
        return ApiResponse.success("已恢复", null);
    }
    
    /**
     * 批量更新租户状态
     */
    @PostMapping("/batch-status")
    public ApiResponse<Void> batchUpdateStatus(
            @RequestBody Map<String, Object> request) {
        @SuppressWarnings("unchecked")
        List<Long> ids = (List<Long>) request.get("ids");
        Integer status = (Integer) request.get("status");
        tenantService.batchUpdateStatus(ids, status);
        return ApiResponse.success("批量更新成功", null);
    }
    
    /**
     * 获取系统概览
     */
    @GetMapping("/overview")
    public ApiResponse<TenantService.SystemOverview> getSystemOverview() {
        return ApiResponse.success(tenantService.getSystemOverview());
    }
    
    // ==================== 套餐管理 ====================
    
    /**
     * 获取套餐列表
     */
    @GetMapping("/packages")
    public ApiResponse<PageResponse<PackageResponse>> listPackages(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "15") Integer pageSize) {
        return ApiResponse.success(tenantService.listPackages(page, pageSize));
    }
    
    /**
     * 获取启用的套餐列表
     */
    @GetMapping("/packages/active")
    public ApiResponse<List<PackageResponse>> listActivePackages() {
        return ApiResponse.success(tenantService.listActivePackages());
    }
    
    /**
     * 获取套餐详情
     */
    @GetMapping("/packages/{id}")
    public ApiResponse<PackageResponse> getPackageById(@PathVariable Long id) {
        return ApiResponse.success(tenantService.getPackageById(id));
    }
    
    /**
     * 创建套餐
     */
    @PostMapping("/packages")
    public ApiResponse<PackageResponse> createPackage(@Valid @RequestBody CreatePackageRequest request) {
        return ApiResponse.success("创建成功", tenantService.createPackage(request));
    }
    
    /**
     * 更新套餐
     */
    @PutMapping("/packages/{id}")
    public ApiResponse<PackageResponse> updatePackage(
            @PathVariable Long id,
            @Valid @RequestBody CreatePackageRequest request) {
        return ApiResponse.success("更新成功", tenantService.updatePackage(id, request));
    }
    
    /**
     * 删除套餐
     */
    @DeleteMapping("/packages/{id}")
    public ApiResponse<Void> deletePackage(@PathVariable Long id) {
        tenantService.deletePackage(id);
        return ApiResponse.success("删除成功", null);
    }
    
    /**
     * 设置默认套餐
     */
    @PostMapping("/packages/{id}/set-default")
    public ApiResponse<Void> setDefaultPackage(@PathVariable Long id) {
        tenantService.setDefaultPackage(id);
        return ApiResponse.success("设置成功", null);
    }
    
    /**
     * 切换套餐状态
     */
    @PostMapping("/packages/{id}/toggle-status")
    public ApiResponse<Map<String, Object>> togglePackageStatus(@PathVariable Long id) {
        Integer newStatus = tenantService.togglePackageStatus(id);
        return ApiResponse.success("切换成功", Map.of("status", newStatus));
    }

    // ==================== 总控审核接口 ====================

    /**
     * 获取待审核租户列表
     * 状态 STATUS_PENDING_REVIEW = 2 的租户需要审核
     */
    @GetMapping("/pending-review")
    public ApiResponse<PageResponse<TenantListResponse>> listPendingReviewTenants(
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "15") Integer pageSize) {
        return ApiResponse.success(tenantService.listTenants(keyword, 2, null, page, pageSize));
    }

    /**
     * 审核通过租户（初始化套餐、激活租户）
     * 
     * 操作：
     * 1. 将租户状态更新为正常（STATUS_ACTIVE）
     * 2. 初始化租户套餐配置到Redis/Nacos
     * 3. 发送审核通过通知
     */
    @PostMapping("/{id}/approve")
    public ApiResponse<Map<String, Object>> approveTenant(@PathVariable Long id) {
        Map<String, Object> result = tenantService.approveTenant(id);
        return ApiResponse.success("审核通过", result);
    }

    /**
     * 审核拒绝租户
     * 
     * 操作：
     * 1. 将租户状态更新为已拒绝
     * 2. 发送审核拒绝通知
     */
    @PostMapping("/{id}/reject")
    public ApiResponse<Void> rejectTenant(
            @PathVariable Long id,
            @RequestBody(required = false) Map<String, String> body) {
        String reason = body != null ? body.get("reason") : "未说明原因";
        tenantService.rejectTenant(id, reason);
        return ApiResponse.success("已拒绝", null);
    }

    // ==================== 套餐变更推送到Nacos接口 ====================

    /**
     * 手动触发套餐配置推送到Nacos
     */
    @PostMapping("/packages/{id}/push-nacos")
    public ApiResponse<Void> pushPackageToNacos(@PathVariable Long id) {
        tenantService.pushPackageToNacos(id);
        return ApiResponse.success("推送成功", null);
    }
}
