package com.ycwl.basic.controller.mobile.notify;

import com.ycwl.basic.model.mobile.notify.req.NotificationAuthRecordReq;
import com.ycwl.basic.model.mobile.notify.resp.NotificationAuthRecordResp;
import com.ycwl.basic.model.mobile.notify.resp.ScenicTemplateAuthResp;
import com.ycwl.basic.service.UserNotificationAuthorizationService;
import com.ycwl.basic.utils.ApiResponse;
import com.ycwl.basic.utils.JwtTokenUtil;
import com.ycwl.basic.repository.ScenicRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户通知授权记录Controller (移动端API)
 * 只提供用户主动授权记录功能，支持批量授权，其他检查和消费功能由系统内部调用
 * 
 * @Author: System
 * @Date: 2024/12/28
 */
@RestController
@RequestMapping("/api/mobile/notify/auth")
@Slf4j
public class UserNotificationAuthController {
    
    @Autowired
    private UserNotificationAuthorizationService userNotificationAuthorizationService;

    @Autowired
    private ScenicRepository scenicRepository;
    
    /**
     * 记录用户通知授权 - 支持批量授权
     * 用户主动同意通知授权时调用
     */
    @PostMapping("/record")
    public ApiResponse<NotificationAuthRecordResp> recordAuthorization(
            @RequestBody NotificationAuthRecordReq req) {
        log.debug("记录用户通知授权: templateIds={}, scenicId={}", req.getTemplateIds(), req.getScenicId());
        
        try {
            // 获取当前用户ID
            Long memberId = JwtTokenUtil.getWorker().getUserId();
            
            // 调用批量授权记录方法
            List<UserNotificationAuthorizationService.AuthorizationRecord> records = 
                    userNotificationAuthorizationService.batchRecordAuthorization(
                            memberId, req.getTemplateIds(), req.getScenicId());
            
            NotificationAuthRecordResp resp = new NotificationAuthRecordResp();
            
            // 转换响应数据
            List<NotificationAuthRecordResp.AuthorizationRecord> successRecords = new ArrayList<>();
            List<String> failedTemplateIds = new ArrayList<>();
            List<String> failureReasons = new ArrayList<>();
            
            for (UserNotificationAuthorizationService.AuthorizationRecord record : records) {
                if (record.isSuccess()) {
                    NotificationAuthRecordResp.AuthorizationRecord successRecord = 
                            new NotificationAuthRecordResp.AuthorizationRecord();
                    successRecord.setId(record.getId());
                    successRecord.setTemplateId(record.getTemplateId());
                    successRecord.setScenicId(record.getScenicId());
                    successRecord.setAuthorizationCount(record.getAuthorizationCount());
                    successRecord.setConsumedCount(record.getConsumedCount());
                    successRecord.setRemainingCount(record.getRemainingCount());
                    successRecord.setLastAuthorizedTime(record.getLastAuthorizedTime());
                    successRecord.setLastConsumedTime(record.getLastConsumedTime());
                    successRecord.setStatus(record.getStatus());
                    successRecord.setCreateTime(record.getCreateTime());
                    successRecords.add(successRecord);
                } else {
                    failedTemplateIds.add(record.getTemplateId());
                    failureReasons.add(record.getFailureReason());
                }
            }
            
            resp.setAllSuccess(CollectionUtils.isEmpty(failedTemplateIds));
            resp.setSuccessRecords(successRecords);
            resp.setFailedTemplateIds(failedTemplateIds);
            resp.setFailureReasons(failureReasons);
            
            return ApiResponse.success(resp);
        } catch (Exception e) {
            log.error("记录用户通知授权失败", e);
            return ApiResponse.fail("记录授权失败: " + e.getMessage());
        }
    }

    /**
     * 获取景区通知模板ID及用户授权余额
     * 复制AppWxNotifyController中的逻辑，并额外返回用户对应的授权余额
     */
    @GetMapping("/{scenicId}/templates")
    public ApiResponse<ScenicTemplateAuthResp> getScenicTemplatesWithAuth(@PathVariable("scenicId") Long scenicId) {
        log.debug("获取景区通知模板ID及用户授权余额: scenicId={}", scenicId);

        try {
            // 获取当前用户ID
            Long memberId = JwtTokenUtil.getWorker().getUserId();

            // 获取景区的所有模板ID（复制自AppWxNotifyController的逻辑）
            List<String> templateIds = new ArrayList<>() {{
                String videoGeneratedTemplateId = scenicRepository.getVideoGeneratedTemplateId(scenicId);
                if (StringUtils.isNotBlank(videoGeneratedTemplateId)) {
                    add(videoGeneratedTemplateId);
                }
                String videoDownloadTemplateId = scenicRepository.getVideoDownloadTemplateId(scenicId);
                if (StringUtils.isNotBlank(videoDownloadTemplateId)) {
                    add(videoDownloadTemplateId);
                }
                String videoPreExpireTemplateId = scenicRepository.getVideoPreExpireTemplateId(scenicId);
                if (StringUtils.isNotBlank(videoPreExpireTemplateId)) {
                    add(videoPreExpireTemplateId);
                }
            }};

            // 构建响应对象
            ScenicTemplateAuthResp resp = new ScenicTemplateAuthResp();
            resp.setScenicId(scenicId);

            // 查询每个模板的授权余额信息
            List<ScenicTemplateAuthResp.TemplateAuthInfo> templateAuthInfos = new ArrayList<>();
            for (String templateId : templateIds) {
                ScenicTemplateAuthResp.TemplateAuthInfo templateAuthInfo =
                        new ScenicTemplateAuthResp.TemplateAuthInfo();
                templateAuthInfo.setTemplateId(templateId);
                
                if (templateId.equals(scenicRepository.getVideoGeneratedTemplateId(scenicId))) {
                    templateAuthInfo.setTitle("视频生成通知");
                    templateAuthInfo.setDescription("当视频生成完成时，我们将提醒您");
                } else if (templateId.equals(scenicRepository.getVideoDownloadTemplateId(scenicId))) {
                    templateAuthInfo.setTitle("视频下载通知");
                    templateAuthInfo.setDescription("当您的视频未购买时，我们将提醒您");
                } else if (templateId.equals(scenicRepository.getVideoPreExpireTemplateId(scenicId))) {
                    templateAuthInfo.setTitle("视频即将过期通知");
                    templateAuthInfo.setDescription("当您的视频即将过期时，我们将提醒您及时下载");
                } else {
                    templateAuthInfo.setTitle("未知模板类型");
                    templateAuthInfo.setDescription("未知的模板类型");
                }

                // 获取授权详情
                try {
                    com.ycwl.basic.model.pc.notify.entity.UserNotificationAuthorizationEntity authEntity =
                            userNotificationAuthorizationService.checkAuthorization(memberId, templateId, scenicId);

                    if (authEntity != null) {
                        templateAuthInfo.setAuthorizationCount(authEntity.getAuthorizationCount());
                        templateAuthInfo.setConsumedCount(authEntity.getConsumedCount());
                        templateAuthInfo.setRemainingCount(authEntity.getRemainingCount());
                        templateAuthInfo.setHasAuthorization(authEntity.getRemainingCount() != null && authEntity.getRemainingCount() > 0);
                    } else {
                        // 没有授权记录
                        templateAuthInfo.setAuthorizationCount(0);
                        templateAuthInfo.setConsumedCount(0);
                        templateAuthInfo.setRemainingCount(0);
                        templateAuthInfo.setHasAuthorization(false);
                    }
                } catch (Exception e) {
                    log.warn("获取模板授权信息失败: templateId={}, scenicId={}, memberId={}, error={}",
                            templateId, scenicId, memberId, e.getMessage());

                    // 获取失败时设置为无授权
                    templateAuthInfo.setAuthorizationCount(0);
                    templateAuthInfo.setConsumedCount(0);
                    templateAuthInfo.setRemainingCount(0);
                    templateAuthInfo.setHasAuthorization(false);
                }

                templateAuthInfos.add(templateAuthInfo);
            }

            resp.setTemplates(templateAuthInfos);

            log.debug("成功获取景区通知模板ID及用户授权余额: scenicId={}, templateCount={}, memberId={}",
                    scenicId, templateIds.size(), memberId);

            return ApiResponse.success(resp);
        } catch (Exception e) {
            log.error("获取景区通知模板ID及用户授权余额失败: scenicId={}", scenicId, e);
            return ApiResponse.fail("获取授权信息失败: " + e.getMessage());
        }
    }
}