package com.erp.tenant.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.common.core.exception.BusinessException;
import com.erp.tenant.dto.*;
import com.erp.tenant.entity.Package;
import com.erp.tenant.entity.Tenant;
import com.erp.tenant.entity.TenantStats;
import com.erp.tenant.feign.NotificationFeignClient;
import com.erp.tenant.repository.PackageRepository;
import com.erp.tenant.repository.TenantRepository;
import com.erp.tenant.service.TenantService;
import com.erp.tenant.service.nacos.NacosConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.erp.common.core.model.PageResponse;

/**
 * 租户服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TenantServiceImpl implements TenantService {
    
    private final TenantRepository tenantRepository;
    private final PackageRepository packageRepository;
    
    @Lazy
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Lazy
    @Autowired
    private NotificationFeignClient notificationClient;

    @Lazy
    @Autowired
    private NacosConfigService nacosConfigService;
    
    // ==================== 租户管理 ====================
    
    @Override
    public PageResponse<TenantListResponse> listTenants(String keyword, Integer status, Boolean expired, Integer page, Integer pageSize) {
        Page<Tenant> pageParam = new Page<>(page, pageSize);
        IPage<Tenant> pageResult = tenantRepository.findPage(pageParam, keyword, status);
        
        // 转换为响应DTO
        List<TenantListResponse> list = pageResult.getRecords().stream()
                .map(this::convertTenantToListResponse)
                .collect(Collectors.toList());
        
        return PageResponse.of(list, pageResult.getTotal(), (int) pageResult.getCurrent(), (int) pageResult.getSize());
    }
    
    @Override
    public TenantDetailResponse getTenantById(Long id) {
        Tenant tenant = tenantRepository.findDetailById(id);
        if (tenant == null) {
            throw new BusinessException(404, "租户不存在");
        }
        
        TenantStats stats = getTenantStats(id);
        return TenantDetailResponse.fromEntity(tenant, stats);
    }
    
    @Override
    public TenantDetailResponse getTenantByCode(String code) {
        Tenant tenant = tenantRepository.findByCode(code);
        if (tenant == null) {
            throw new BusinessException(404, "租户不存在");
        }
        
        // 加载套餐信息
        if (tenant.getPackageId() != null) {
            tenant.setPkg(packageRepository.selectById(tenant.getPackageId()));
        }
        
        TenantStats stats = getTenantStats(tenant.getId());
        return TenantDetailResponse.fromEntity(tenant, stats);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public TenantDetailResponse createTenant(CreateTenantRequest request) {
        // 检查编码唯一性
        if (tenantRepository.existsByCode(request.getCode())) {
            throw new BusinessException(400, "租户编码已存在");
        }
        
        // 检查套餐是否存在
        Package pkg = packageRepository.selectById(request.getPackageId());
        if (pkg == null || !pkg.isActive()) {
            throw new BusinessException(400, "套餐不存在或未启用");
        }
        
        // 创建租户
        Tenant tenant = Tenant.builder()
                .name(request.getName())
                .code(request.getCode())
                .domain(request.getDomain())
                .packageId(request.getPackageId())
                .adminEmail(request.getAdminEmail())
                .adminPhone(request.getAdminPhone())
                .expireTime(request.getExpireTime())
                .remark(request.getRemark())
                .status(Tenant.STATUS_ACTIVE)
                .build();
        
        tenantRepository.insert(tenant);
        
        // 创建租户管理员用户（调用用户服务）
        // Long adminUserId = createTenantAdmin(tenant);
        // tenant.setAdminUserId(adminUserId);
        // tenantRepository.updateById(tenant);
        
        // 加载套餐信息
        tenant.setPkg(pkg);

        // ===== 发送通知 =====
        sendTenantCreatedNotification(tenant, pkg);

        log.info("创建租户成功: id={}, code={}", tenant.getId(), tenant.getCode());

        return TenantDetailResponse.fromEntity(tenant, null);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public TenantDetailResponse updateTenant(Long id, UpdateTenantRequest request) {
        Tenant tenant = tenantRepository.selectById(id);
        if (tenant == null) {
            throw new BusinessException(404, "租户不存在");
        }
        
        // 检查套餐
        if (request.getPackageId() != null) {
            Package pkg = packageRepository.selectById(request.getPackageId());
            if (pkg == null || !pkg.isActive()) {
                throw new BusinessException(400, "套餐不存在或未启用");
            }
            tenant.setPackageId(request.getPackageId());
            tenant.setPkg(pkg);
        }
        
        // 更新字段
        if (request.getName() != null) {
            tenant.setName(request.getName());
        }
        if (request.getDomain() != null) {
            tenant.setDomain(request.getDomain());
        }
        if (request.getAdminEmail() != null) {
            tenant.setAdminEmail(request.getAdminEmail());
        }
        if (request.getAdminPhone() != null) {
            tenant.setAdminPhone(request.getAdminPhone());
        }
        if (request.getExpireTime() != null) {
            tenant.setExpireTime(request.getExpireTime());
        }
        if (request.getRemark() != null) {
            tenant.setRemark(request.getRemark());
        }
        
        tenantRepository.updateById(tenant);
        
        log.info("更新租户成功: id={}", id);
        
        TenantStats stats = getTenantStats(id);
        return TenantDetailResponse.fromEntity(tenant, stats);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteTenant(Long id) {
        Tenant tenant = tenantRepository.selectById(id);
        if (tenant == null) {
            throw new BusinessException(404, "租户不存在");
        }
        
        // 检查是否可以删除
        if (!canDelete(id)) {
            throw new BusinessException(400, "该租户下有数据，无法删除");
        }
        
        // 删除租户用户
        // userService.deleteByTenantId(tenant.getId());
        
        // 删除租户（软删除）
        tenantRepository.deleteById(id);
        
        log.info("删除租户成功: id={}", id);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public TenantStatusVO toggleStatus(Long id) {
        Tenant tenant = tenantRepository.selectById(id);
        if (tenant == null) {
            throw new BusinessException(404, "租户不存在");
        }
        
        int newStatus = tenant.isActive() ? Tenant.STATUS_INACTIVE : Tenant.STATUS_ACTIVE;
        tenant.setStatus(newStatus);
        tenantRepository.updateById(tenant);
        
        log.info("切换租户状态: id={}, newStatus={}", id, newStatus);
        
        return new TenantStatusVO(tenant.getId(), tenant.getStatus(), tenant.getStatusLabel());
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void suspendTenant(Long id) {
        Tenant tenant = tenantRepository.selectById(id);
        if (tenant == null) {
            throw new BusinessException(404, "租户不存在");
        }
        
        tenant.setStatus(Tenant.STATUS_SUSPENDED);
        tenantRepository.updateById(tenant);
        
        log.info("暂停租户: id={}", id);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void activateTenant(Long id) {
        Tenant tenant = tenantRepository.selectById(id);
        if (tenant == null) {
            throw new BusinessException(404, "租户不存在");
        }
        
        tenant.setStatus(Tenant.STATUS_ACTIVE);
        tenantRepository.updateById(tenant);
        
        log.info("恢复租户: id={}", id);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchUpdateStatus(List<Long> ids, Integer status) {
        if (ids == null || ids.isEmpty()) {
            return;
        }
        
        tenantRepository.batchUpdateStatus(ids, status);
        
        log.info("批量更新租户状态: count={}, status={}", ids.size(), status);
    }
    
    // ==================== 套餐管理 ====================
    
    @Override
    public PageResponse<PackageResponse> listPackages(Integer page, Integer pageSize) {
        Page<Package> pageParam = new Page<>(page, pageSize);
        IPage<Package> pageResult = packageRepository.findPage(pageParam);
        
        List<PackageResponse> list = pageResult.getRecords().stream()
                .map(PackageResponse::fromEntity)
                .collect(Collectors.toList());
        
        return PageResponse.of(list, pageResult.getTotal(), (int) pageResult.getCurrent(), (int) pageResult.getSize());
    }
    
    @Override
    public PackageResponse getPackageById(Long id) {
        Package pkg = packageRepository.selectById(id);
        if (pkg == null) {
            throw new BusinessException(404, "套餐不存在");
        }
        return PackageResponse.fromEntity(pkg);
    }
    
    @Override
    public List<PackageResponse> listActivePackages() {
        return packageRepository.findActive().stream()
                .map(PackageResponse::fromEntity)
                .collect(Collectors.toList());
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PackageResponse createPackage(CreatePackageRequest request) {
        // 检查编码唯一性
        if (packageRepository.existsByCode(request.getCode())) {
            throw new BusinessException(400, "套餐编码已存在");
        }
        
        // 如果设置为默认，先清除其他默认
        if (Boolean.TRUE.equals(request.getIsDefault())) {
            packageRepository.clearDefaultFlag();
        }
        
        Package pkg = Package.builder()
                .name(request.getName())
                .code(request.getCode())
                .type(request.getType())
                .price(request.getPrice())
                .periodDays(request.getPeriodDays())
                .sort(request.getSort() != null ? request.getSort() : 0)
                .isDefault(request.getIsDefault() != null ? request.getIsDefault() : false)
                .trialDays(request.getTrialDays() != null ? request.getTrialDays() : 0)
                .status(request.getStatus())
                .features(request.getFeatures())
                .limits(request.getLimits())
                .remark(request.getRemark())
                .build();
        
        packageRepository.insert(pkg);
        
        log.info("创建套餐成功: id={}, code={}", pkg.getId(), pkg.getCode());
        
        return PackageResponse.fromEntity(pkg);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PackageResponse updatePackage(Long id, CreatePackageRequest request) {
        Package pkg = packageRepository.selectById(id);
        if (pkg == null) {
            throw new BusinessException(404, "套餐不存在");
        }
        
        // 检查编码唯一性
        if (packageRepository.existsByCodeExclude(request.getCode(), id)) {
            throw new BusinessException(400, "套餐编码已存在");
        }
        
        // 如果设置为默认，先清除其他默认
        if (Boolean.TRUE.equals(request.getIsDefault()) && !Boolean.TRUE.equals(pkg.getIsDefault())) {
            packageRepository.clearDefaultFlag();
        }
        
        pkg.setName(request.getName());
        pkg.setCode(request.getCode());
        pkg.setType(request.getType());
        pkg.setPrice(request.getPrice());
        pkg.setPeriodDays(request.getPeriodDays());
        pkg.setSort(request.getSort() != null ? request.getSort() : pkg.getSort());
        pkg.setIsDefault(request.getIsDefault());
        pkg.setTrialDays(request.getTrialDays());
        pkg.setStatus(request.getStatus());
        pkg.setFeatures(request.getFeatures());
        pkg.setLimits(request.getLimits());
        pkg.setRemark(request.getRemark());
        
        packageRepository.updateById(pkg);

        // ===== 推送套餐变更到Nacos =====
        pushPackageChangeToNacos(id, pkg);

        log.info("更新套餐成功: id={}", id);

        return PackageResponse.fromEntity(pkg);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePackage(Long id) {
        Package pkg = packageRepository.selectById(id);
        if (pkg == null) {
            throw new BusinessException(404, "套餐不存在");
        }
        
        // 检查是否有租户使用此套餐
        Long tenantCount = tenantRepository.countByPackageId(id);
        if (tenantCount > 0) {
            throw new BusinessException(400, "该套餐下有 " + tenantCount + " 个租户，无法删除");
        }
        
        packageRepository.deleteById(id);
        
        log.info("删除套餐成功: id={}", id);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setDefaultPackage(Long id) {
        Package pkg = packageRepository.selectById(id);
        if (pkg == null) {
            throw new BusinessException(404, "套餐不存在");
        }
        
        if (!pkg.isActive()) {
            throw new BusinessException(400, "只能将启用状态的套餐设为默认");
        }
        
        packageRepository.clearDefaultFlag();
        packageRepository.setDefault(id);
        
        log.info("设置默认套餐: id={}", id);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer togglePackageStatus(Long id) {
        Package pkg = packageRepository.selectById(id);
        if (pkg == null) {
            throw new BusinessException(404, "套餐不存在");
        }

        int newStatus = pkg.isActive() ? Package.STATUS_DISABLED : Package.STATUS_ENABLED;
        pkg.setStatus(newStatus);
        packageRepository.updateById(pkg);

        // ===== 推送套餐状态变更到Nacos =====
        pushPackageChangeToNacos(id, pkg);

        log.info("切换套餐状态: id={}, newStatus={}", id, newStatus);

        return newStatus;
    }
    
    // ==================== 租户统计 ====================
    
    @Override
    public TenantStats getTenantStats(Long tenantId) {
        // TODO: 调用其他服务获取统计数据
        // 这里暂时返回空数据，实际应调用 order-service, user-service 等
        
        return TenantStats.builder()
                .orders(0L)
                .users(0L)
                .goods(0L)
                .orderAmount(java.math.BigDecimal.ZERO)
                .monthlyOrders(0L)
                .monthlyUsers(0L)
                .activeUsers(0L)
                .build();
    }
    
    @Override
    public SystemOverview getSystemOverview() {
        LocalDateTime now = LocalDateTime.now();
        
        Long totalTenants = tenantRepository.selectCount(null);
        Long activeTenants = tenantRepository.countActive();
        Long expiredTenants = tenantRepository.countExpired(now);
        Long totalPackages = packageRepository.selectCount(null);
        Long activePackages = packageRepository.countActive();
        
        // 统计暂停的租户
        List<Tenant> suspendedTenants = tenantRepository.findByStatus(Tenant.STATUS_SUSPENDED);
        
        return SystemOverview.builder()
                .totalTenants(totalTenants)
                .activeTenants(activeTenants)
                .expiredTenants(expiredTenants)
                .suspendedTenants((long) suspendedTenants.size())
                .totalPackages(totalPackages)
                .activePackages(activePackages)
                .build();
    }
    
    // ==================== 辅助方法 ====================
    
    @Override
    public boolean existsByCode(String code) {
        return tenantRepository.existsByCode(code);
    }
    
    @Override
    public boolean canDelete(Long id) {
        // TODO: 检查是否有订单等数据
        return true;
    }
    
    @Override
    public boolean isValid(Long id) {
        Tenant tenant = tenantRepository.selectById(id);
        if (tenant == null) {
            return false;
        }
        return tenant.isActive() && !tenant.isExpired();
    }
    
    /**
     * 转换租户实体为列表响应DTO
     */
    private TenantListResponse convertTenantToListResponse(Tenant tenant) {
        // 加载套餐信息
        if (tenant.getPackageId() != null && tenant.getPkg() == null) {
            Package pkg = packageRepository.selectById(tenant.getPackageId());
            tenant.setPkg(pkg);
        }
        return TenantListResponse.fromEntity(tenant);
    }

    // ==================== 辅助方法：通知发送 ====================

    /**
     * 发送租户创建通知
     */
    private void sendTenantCreatedNotification(Tenant tenant, Package pkg) {
        try {
            // 1. 发送系统通知
            if (notificationClient != null) {
                NotificationFeignClient.SystemNoticeRequest sysRequest =
                    new NotificationFeignClient.SystemNoticeRequest(
                        tenant.getId(),
                        "租户创建成功",
                        "恭喜！您的租户 \"" + tenant.getName() + "\" 已成功创建。\n" +
                        "套餐：" + pkg.getName() + "\n" +
                        "到期时间：" + (tenant.getExpireTime() != null ? tenant.getExpireTime().toString() : "未设置"),
                        "tenant_register",
                        String.valueOf(tenant.getId())
                    );
                notificationClient.sendSystemNotice(sysRequest);
            }

            // 2. 发送邮件通知（如果配置了邮箱）
            if (tenant.getAdminEmail() != null && !tenant.getAdminEmail().isEmpty() && notificationClient != null) {
                NotificationFeignClient.NotificationRequest emailRequest =
                    new NotificationFeignClient.NotificationRequest(
                        "email",
                        tenant.getAdminEmail(),
                        "租户创建成功",
                        "您的租户 \"" + tenant.getName() + "\" 已成功创建。套餐：" + pkg.getName(),
                        tenant.getId(),
                        "tenant_register",
                        String.valueOf(tenant.getId())
                    );
                notificationClient.sendNotification(emailRequest);
            }

            // 3. 发送钉钉通知给管理员（如果有配置）
            if (notificationClient != null) {
                NotificationFeignClient.NotificationRequest dingTalkRequest =
                    new NotificationFeignClient.NotificationRequest(
                        "dingtalk",
                        null,
                        "【新租户注册】" + tenant.getName(),
                        "新租户注册：\n" +
                        "- 租户名：" + tenant.getName() + "\n" +
                        "- 编码：" + tenant.getCode() + "\n" +
                        "- 套餐：" + pkg.getName() + "\n" +
                        "- 管理员邮箱：" + tenant.getAdminEmail() + "\n" +
                        "- 到期时间：" + (tenant.getExpireTime() != null ? tenant.getExpireTime().toString() : "未设置"),
                        tenant.getId(),
                        "tenant_register",
                        String.valueOf(tenant.getId())
                    );
                notificationClient.sendNotification(dingTalkRequest);
            }

            log.info("租户创建通知已发送: tenantId={}", tenant.getId());
        } catch (Exception e) {
            // 通知失败不影响主流程
            log.warn("发送租户创建通知失败: tenantId={}, error={}", tenant.getId(), e.getMessage());
        }
    }

    // ==================== 辅助方法：Nacos配置推送 ====================

    /**
     * 将套餐变更推送到Nacos
     *
     * 推送内容：套餐ID、名称、功能列表、限制列表、状态
     * 订阅方：各微服务通过Nacos监听租户配置变化，动态更新本地缓存
     */
    private void pushPackageChangeToNacos(Long packageId, Package pkg) {
        try {
            if (nacosConfigService == null) {
                log.warn("NacosConfigService未初始化，跳过配置推送");
                return;
            }

            // 构建套餐配置JSON
            String configJson = buildPackageConfigYaml(packageId, pkg);

            // 推送到Nacos
            nacosConfigService.publishTenantPackageConfig(null, packageId, configJson);

            // 如果是默认套餐，发布到全局默认配置
            if (Boolean.TRUE.equals(pkg.getIsDefault())) {
                nacosConfigService.publishTenantPackageConfig(0L, packageId, configJson);
            }

            log.info("套餐变更已推送Nacos: packageId={}, isDefault={}", packageId, pkg.getIsDefault());
        } catch (Exception e) {
            log.error("推送套餐变更到Nacos失败: packageId={}, error={}", packageId, e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> approveTenant(Long id) {
        Tenant tenant = tenantRepository.selectById(id);
        if (tenant == null) {
            throw new BusinessException(404, "租户不存在");
        }

        if (tenant.getPackageId() == null) {
            throw new BusinessException(400, "租户未分配套餐，无法审核");
        }

        // 加载套餐
        Package pkg = packageRepository.selectById(tenant.getPackageId());
        if (pkg == null) {
            throw new BusinessException(400, "套餐不存在");
        }

        // 更新租户状态为正常
        tenant.setStatus(Tenant.STATUS_ACTIVE);
        tenantRepository.updateById(tenant);

        // 初始化套餐配置到Redis（供网关和各服务查询）
        String configKey = "tenant:package:" + tenant.getId();
        redisTemplate.opsForValue().set(configKey + ":info", pkg.getName());
        redisTemplate.opsForValue().set(configKey + ":features", pkg.getFeatures() != null ? pkg.getFeatures() : "{}");
        redisTemplate.opsForValue().set(configKey + ":limits", pkg.getLimits() != null ? pkg.getLimits() : "{}");

        // 推送到Nacos
        pushPackageChangeToNacos(tenant.getPackageId(), pkg);

        // 发送审核通过通知
        sendApprovalNotification(tenant, pkg, true, null);

        log.info("租户审核通过: id={}, code={}", tenant.getId(), tenant.getCode());

        return Map.of(
            "tenantId", tenant.getId(),
            "tenantCode", tenant.getCode(),
            "status", tenant.getStatus(),
            "packageId", pkg.getId(),
            "packageName", pkg.getName(),
            "features", pkg.getFeatures() != null ? pkg.getFeatures() : "{}",
            "limits", pkg.getLimits() != null ? pkg.getLimits() : "{}"
        );
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void rejectTenant(Long id, String reason) {
        Tenant tenant = tenantRepository.selectById(id);
        if (tenant == null) {
            throw new BusinessException(404, "租户不存在");
        }

        // 更新租户状态为禁用
        tenant.setStatus(Tenant.STATUS_INACTIVE);
        tenantRepository.updateById(tenant);

        // 加载套餐（用于通知）
        Package pkg = null;
        if (tenant.getPackageId() != null) {
            pkg = packageRepository.selectById(tenant.getPackageId());
        }

        // 发送审核拒绝通知
        sendApprovalNotification(tenant, pkg, false, reason);

        log.info("租户审核拒绝: id={}, reason={}", tenant.getId(), reason);
    }

    @Override
    public void pushPackageToNacos(Long packageId) {
        Package pkg = packageRepository.selectById(packageId);
        if (pkg == null) {
            throw new BusinessException(404, "套餐不存在");
        }

        pushPackageChangeToNacos(packageId, pkg);

        log.info("手动推送套餐配置到Nacos: packageId={}", packageId);
    }

    /**
     * 发送审核结果通知
     */
    private void sendApprovalNotification(Tenant tenant, Package pkg, boolean approved, String reason) {
        try {
            if (notificationClient == null) {
                return;
            }

            if (approved) {
                // 审核通过 - 通知租户管理员
                if (tenant.getAdminEmail() != null) {
                    notificationClient.sendNotification(
                        new NotificationFeignClient.NotificationRequest(
                            "email",
                            tenant.getAdminEmail(),
                            "租户审核通过",
                            "您的租户 \"" + tenant.getName() + "\" 已审核通过！\n套餐：" +
                            (pkg != null ? pkg.getName() : "未知") + "\n" +
                            "功能已开通，请登录系统开始使用。",
                            tenant.getId(),
                            "tenant_approve",
                            String.valueOf(tenant.getId())
                        )
                    );
                }
                notificationClient.sendSystemNotice(
                    new NotificationFeignClient.SystemNoticeRequest(
                        tenant.getId(),
                        "租户审核通过",
                        "您的租户已审核通过，套餐功能已开通。",
                        "tenant_approve",
                        String.valueOf(tenant.getId())
                    )
                );
            } else {
                // 审核拒绝 - 通知租户管理员
                if (tenant.getAdminEmail() != null) {
                    notificationClient.sendNotification(
                        new NotificationFeignClient.NotificationRequest(
                            "email",
                            tenant.getAdminEmail(),
                            "租户审核未通过",
                            "您的租户 \"" + tenant.getName() + "\" 审核未通过。\n" +
                            "拒绝原因：" + (reason != null ? reason : "未说明") + "\n" +
                            "请修改后重新提交。",
                            tenant.getId(),
                            "tenant_reject",
                            String.valueOf(tenant.getId())
                        )
                    );
                }
                notificationClient.sendSystemNotice(
                    new NotificationFeignClient.SystemNoticeRequest(
                        tenant.getId(),
                        "租户审核未通过",
                        "审核未通过，原因：" + (reason != null ? reason : "未说明"),
                        "tenant_reject",
                        String.valueOf(tenant.getId())
                    )
                );
            }
        } catch (Exception e) {
            log.warn("发送审核结果通知失败: tenantId={}, error={}", tenant.getId(), e.getMessage());
        }
    }

    /**
     * 构建套餐配置YAML内容
     */
    private String buildPackageConfigYaml(Long packageId, Package pkg) {
        StringBuilder sb = new StringBuilder();
        sb.append("# 套餐配置，由tenant-service自动生成\n");
        sb.append("# 更新时间: ").append(java.time.LocalDateTime.now()).append("\n");
        sb.append("package:\n");
        sb.append("  id: ").append(packageId).append("\n");
        sb.append("  code: \"").append(pkg.getCode() != null ? pkg.getCode() : "").append("\"\n");
        sb.append("  name: \"").append(pkg.getName() != null ? pkg.getName() : "").append("\"\n");
        sb.append("  type: ").append(pkg.getType() != null ? pkg.getType() : "month").append("\n");
        sb.append("  status: ").append(pkg.getStatus()).append("\n");
        sb.append("  price: ").append(pkg.getPrice() != null ? pkg.getPrice().toString() : "0").append("\n");
        sb.append("  period_days: ").append(pkg.getPeriodDays() != null ? pkg.getPeriodDays() : 30).append("\n");
        sb.append("  trial_days: ").append(pkg.getTrialDays() != null ? pkg.getTrialDays() : 0).append("\n");
        sb.append("  features: ").append(pkg.getFeatures() != null ? pkg.getFeatures() : "{}").append("\n");
        sb.append("  limits: ").append(pkg.getLimits() != null ? pkg.getLimits() : "{}").append("\n");
        sb.append("  updated_at: ").append(java.time.LocalDateTime.now().toString()).append("\n");
        return sb.toString();
    }
}
