package com.ycwl.basic.utils;

import com.ycwl.basic.model.pc.notify.entity.UserNotificationAuthorizationEntity;
import com.ycwl.basic.service.UserNotificationAuthorizationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 通知授权工具类
 * 提供系统内部调用的授权检查和消费功能
 * 
 * @Author: System
 * @Date: 2024/12/28
 */
@Component
@Slf4j
public class NotificationAuthUtils {
    
    @Autowired
    private UserNotificationAuthorizationService userNotificationAuthorizationService;
    
    /**
     * 检查用户是否对指定模板有授权
     * 
     * @param memberId 用户ID
     * @param templateId 模板ID
     * @param scenicId 景区ID
     * @return 是否有授权
     */
    public boolean hasAuthorization(Long memberId, String templateId, Long scenicId) {
        try {
            Integer remainingCount = userNotificationAuthorizationService.getRemainingCount(memberId, templateId, scenicId);
            return remainingCount != null && remainingCount > 0;
        } catch (Exception e) {
            log.error("检查用户授权失败: memberId={}, templateId={}, scenicId={}", memberId, templateId, scenicId, e);
            return false;
        }
    }
    
    /**
     * 获取用户剩余授权次数
     * 
     * @param memberId 用户ID
     * @param templateId 模板ID
     * @param scenicId 景区ID
     * @return 剩余授权次数，0表示没有剩余
     */
    public int getRemainingCount(Long memberId, String templateId, Long scenicId) {
        try {
            Integer remainingCount = userNotificationAuthorizationService.getRemainingCount(memberId, templateId, scenicId);
            return remainingCount != null ? remainingCount : 0;
        } catch (Exception e) {
            log.error("获取剩余授权次数失败: memberId={}, templateId={}, scenicId={}", memberId, templateId, scenicId, e);
            return 0;
        }
    }
    
    /**
     * 消费一次授权
     * 在发送通知前调用此方法消费授权
     * 
     * @param memberId 用户ID
     * @param templateId 模板ID
     * @param scenicId 景区ID
     * @return 是否消费成功
     */
    public boolean consumeAuthorization(Long memberId, String templateId, Long scenicId) {
        try {
            boolean result = userNotificationAuthorizationService.consumeAuthorization(memberId, templateId, scenicId);
            if (result) {
                log.info("成功消费授权: memberId={}, templateId={}, scenicId={}", memberId, templateId, scenicId);
            } else {
                log.warn("消费授权失败: memberId={}, templateId={}, scenicId={}", memberId, templateId, scenicId);
            }
            return result;
        } catch (Exception e) {
            log.error("消费授权异常: memberId={}, templateId={}, scenicId={}", memberId, templateId, scenicId, e);
            return false;
        }
    }
    
    /**
     * 检查并消费授权（原子操作）
     * 先检查是否有授权，如果有则直接消费
     * 
     * @param memberId 用户ID
     * @param templateId 模板ID
     * @param scenicId 景区ID
     * @return 是否检查并消费成功
     */
    public boolean checkAndConsumeAuthorization(Long memberId, String templateId, Long scenicId) {
        try {
            // 先检查剩余次数
            Integer remainingCount = userNotificationAuthorizationService.getRemainingCount(memberId, templateId, scenicId);
            if (remainingCount == null || remainingCount <= 0) {
                log.debug("用户剩余授权次数不足: memberId={}, templateId={}, scenicId={}, remainingCount={}", 
                        memberId, templateId, scenicId, remainingCount);
                return false;
            }
            
            // 尝试消费
            return consumeAuthorization(memberId, templateId, scenicId);
        } catch (Exception e) {
            log.error("检查并消费授权异常: memberId={}, templateId={}, scenicId={}", memberId, templateId, scenicId, e);
            return false;
        }
    }
    
    /**
     * 记录用户授权
     * 用户主动同意授权时调用
     * 
     * @param memberId 用户ID
     * @param templateId 模板ID
     * @param scenicId 景区ID
     * @return 授权记录
     */
    public UserNotificationAuthorizationEntity recordAuthorization(Long memberId, String templateId, Long scenicId) {
        try {
            return userNotificationAuthorizationService.recordAuthorization(memberId, templateId, scenicId);
        } catch (Exception e) {
            log.error("记录用户授权失败: memberId={}, templateId={}, scenicId={}", memberId, templateId, scenicId, e);
            throw new RuntimeException("记录用户授权失败", e);
        }
    }
    
    /**
     * 批量记录用户授权
     * 用户主动同意多个授权时调用
     * 
     * @param memberId 用户ID
     * @param templateIds 模板ID列表
     * @param scenicId 景区ID
     * @return 批量授权记录结果
     */
    public List<UserNotificationAuthorizationService.AuthorizationRecord> batchRecordAuthorization(
            Long memberId, List<String> templateIds, Long scenicId) {
        try {
            return userNotificationAuthorizationService.batchRecordAuthorization(memberId, templateIds, scenicId);
        } catch (Exception e) {
            log.error("批量记录用户授权失败: memberId={}, templateIds={}, scenicId={}", memberId, templateIds, scenicId, e);
            throw new RuntimeException("批量记录用户授权失败", e);
        }
    }
    
    /**
     * 获取用户授权详情
     * 
     * @param memberId 用户ID
     * @param templateId 模板ID
     * @param scenicId 景区ID
     * @return 授权记录，如果没有授权返回null
     */
    public UserNotificationAuthorizationEntity getAuthorizationDetail(Long memberId, String templateId, Long scenicId) {
        try {
            return userNotificationAuthorizationService.checkAuthorization(memberId, templateId, scenicId);
        } catch (Exception e) {
            log.error("获取用户授权详情失败: memberId={}, templateId={}, scenicId={}", memberId, templateId, scenicId, e);
            return null;
        }
    }
}