package com.ruoyi.novel.service.impl;

import com.ruoyi.novel.domain.VoteRecord;
import com.ruoyi.novel.domain.VoteRequest;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

// VoteServiceImpl.java
@Service
public class VoteServiceImpl implements IVoteService {

    @Autowired
    private VoteRecordMapper voteRecordMapper;
    @Autowired
    private StoryOptionMapper storyOptionMapper;
    @Value("${deepseek.api.key}")
    private String deepSeekApiKey;

    @Value("${php.notify.url}")
    private String phpNotifyUrl;
    // 用户投票限流器 <userId, 计数器>
    private final Map<Long, AtomicInteger> userVoteCounters = new ConcurrentHashMap<>();
    private static final int DAILY_VOTE_LIMIT = 3;

    @Override
    public String processVote(VoteRequest request) {
        // 1. 检查当日投票次数
        AtomicInteger counter = userVoteCounters.computeIfAbsent(
                request.getUserId(),
                k -> new AtomicInteger(0)
        );

        if (counter.get() >= DAILY_VOTE_LIMIT) {
            throw new ServiceException("今日投票次数已达上限");
        }

        // 2. 记录投票
        VoteRecord record = new VoteRecord();
        record.setUserId(request.getUserId());
        record.setStoryId(request.getStoryId());
        record.setOptionId(request.getOptionId());
        record.setNotifyStatus(0); // 未通知状态
        voteRecordMapper.insert(record);

        // 3. 更新选项计数
        storyOptionMapper.incrementOptionVote(request.getOptionId());

        // 4. 异步生成内容
        this.generateStoryContent(record);

        counter.incrementAndGet();
        return "投票成功，剧情生成中...";
    }
    @Override
    @Async("voteTaskExecutor")
    public void generateStoryContent(VoteRecord record) {
        try {
            String content = callDeepSeekApi(record);
            record.setGeneratedContent(content);
            voteRecordMapper.updateById(record);

            // 通知PHP系统
            this.notifyPhpSystem(record);
        } catch (Exception e) {
            log.error("AI生成失败: {}", e.getMessage());
        }
    }
    private String callDeepSeekApi(VoteRecord record) {
        // 实现DeepSeek API调用
        // 返回生成的剧情内容
        return "生成的故事内容...";
    }

//    @Async
//    @Override
//    public void generateStoryContent(Long storyId, Long optionId) {
//        // 调用DeepSeek API
//        DeepSeekRequest request = new DeepSeekRequest(storyId, optionId);
//        String apiUrl = "https://api.deepseek.com/v1/story/generate";
//
//        RestTemplate restTemplate = new RestTemplate();
//        HttpHeaders headers = new HttpHeaders();
//        headers.setBearerAuth(deepSeekApiKey);
//
//        HttpEntity<DeepSeekRequest> entity = new HttpEntity<>(request, headers);
//        ResponseEntity<String> response = restTemplate.exchange(
//                apiUrl, HttpMethod.POST, entity, String.class);
//
//        if (response.getStatusCode() == HttpStatus.OK) {
//            return parseGeneratedContent(response.getBody());
//        }
//        throw new ServiceException("Failed to generate story content");
//    }

    @Async
    @Override
    public void notifyPhpSystem(VoteRequest request, String content) {
        // 组装通知数据
        Map<String, Object> payload = new HashMap<>();
        payload.put("userId", request.getUserId());
        payload.put("storyId", request.getStoryId());
        payload.put("optionId", request.getOptionId());
        payload.put("content", content);

        // 发送异步通知
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.postForObject(phpNotifyUrl, payload, String.class);

        // 记录投票日志
        VoteRecord record = new VoteRecord();
        record.setUserId(request.getUserId());
        record.setStoryId(request.getStoryId());
        record.setOptionId(request.getOptionId());
        record.setVoteTime(new Date());
        record.setGeneratedContent(content);
        voteRecordMapper.insertVoteRecord(record);
    }

    @Override
    @Async("voteTaskExecutor")
    public void notifyPhpSystem(VoteRecord record) {
        try {
            // 构建通知数据
            Map<String, Object> payload = new HashMap<>();
            payload.put("userId", record.getUserId());
            payload.put("storyId", record.getStoryId());
            payload.put("optionId", record.getOptionId());
            payload.put("content", record.getGeneratedContent());

            // 发送HTTP请求
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> response = restTemplate.postForEntity(
                    phpNotifyUrl, payload, String.class);

            if (response.getStatusCode() == HttpStatus.OK) {
                record.setNotifyStatus(1); // 通知成功
            } else {
                record.setNotifyStatus(2); // 通知失败
            }
        } catch (Exception e) {
            log.error("通知PHP系统失败: {}", e.getMessage());
            record.setNotifyStatus(2);
        }
        voteRecordMapper.updateById(record);
    }

    @Override
    @Scheduled(cron = "0 */10 * * * ?") // 每10分钟执行一次
    public void retryFailedNotifications() {
        List<VoteRecord> failedRecords = voteRecordMapper.selectUnnotifiedRecords();
        failedRecords.forEach(record -> {
            log.info("重试通知PHP系统: voteId={}", record.getId());
            this.notifyPhpSystem(record);
        });
    }
}
