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

import com.ycwl.basic.model.mobile.notify.req.BatchRemainingCountReq;
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.model.pc.notify.entity.UserNotificationAuthorizationEntity;
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.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户通知授权记录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={}, requestId={}",
                req.getTemplateIds(), req.getScenicId(), req.getRequestId());
        
        try {
            // 获取当前用户ID
            Long memberId = JwtTokenUtil.getWorker().getUserId();
            
            // 调用批量授权记录方法
            List<UserNotificationAuthorizationService.AuthorizationRecord> records = 
                    userNotificationAuthorizationService.batchRecordAuthorization(
                            memberId, req.getTemplateIds(), req.getScenicId(), req.getRequestId());
            
            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());
        }
    }

    /**
     * 批量查询用户授权余额
     * 返回 Map<wechatTemplateId, remainingCount>
     */
    @PostMapping("/batch-remaining")
    public ApiResponse<Map<String, Integer>> batchGetRemainingCount(
            @RequestBody BatchRemainingCountReq req) {
        log.debug("批量查询用户授权余额: templateIds={}, scenicId={}",
                req.getTemplateIds(), req.getScenicId());

        try {
            Long memberId = JwtTokenUtil.getWorker().getUserId();
            if (memberId == null) {
                return ApiResponse.fail("用户未登录");
            }

            if (CollectionUtils.isEmpty(req.getTemplateIds())) {
                return ApiResponse.success(new HashMap<>());
            }

            Map<String, UserNotificationAuthorizationEntity> authMap =
                    userNotificationAuthorizationService.batchCheckAuthorization(
                            memberId, req.getTemplateIds(), req.getScenicId());

            // 转换为 templateId -> remainingCount
            Map<String, Integer> result = new HashMap<>();
            for (String templateId : req.getTemplateIds()) {
                UserNotificationAuthorizationEntity entity = authMap.get(templateId);
                int remaining = (entity != null && entity.getRemainingCount() != null)
                        ? entity.getRemainingCount() : 0;
                result.put(templateId, remaining);
            }

            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("批量查询用户授权余额失败", e);
            return ApiResponse.fail("查询失败: " + e.getMessage());
        }
    }
}
