package top.tqx.demo_1.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import top.tqx.demo_1.dto.FeedbackCreateRequest;
import top.tqx.demo_1.dto.FeedbackItem;
import top.tqx.demo_1.dto.FeedbackListResponse;
import top.tqx.demo_1.dto.FeedbackResponse;
import top.tqx.demo_1.dto.FeedbackStatsResponse;
import top.tqx.demo_1.entity.Feedback;
import top.tqx.demo_1.mapper.FeedbackMapper;
import top.tqx.demo_1.service.FeedbackService;

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

@Slf4j
@Service
public class FeedbackServiceImpl implements FeedbackService {

    @Autowired
    private FeedbackMapper feedbackMapper;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public FeedbackResponse submitFeedback(FeedbackCreateRequest request) {
        log.info("提交反馈: sessionId={}, rating={}", request.getSessionId(), request.getRating());

        String feedbackId = UUID.randomUUID().toString();
        
        try {
            Feedback feedback = new Feedback();
            feedback.setFeedbackId(feedbackId);
            feedback.setSessionId(request.getSessionId());
            feedback.setQuery(request.getQuery());
            feedback.setAnswer(request.getAnswer());
            feedback.setRating(request.getRating());
            feedback.setReason(request.getReason());
            if (request.getSources() != null && !request.getSources().isEmpty()) {
                feedback.setSources(objectMapper.writeValueAsString(request.getSources()));
            }
            feedback.setFaqSuggested(0);

            feedbackMapper.insert(feedback);

            FeedbackResponse response = new FeedbackResponse();
            response.setSuccess(true);
            response.setFeedbackId(feedbackId);
            response.setFaqSuggested(false);

            log.info("反馈提交成功: feedbackId={}", feedbackId);
            return response;

        } catch (Exception e) {
            log.error("提交反馈失败: {}", e.getMessage(), e);
            FeedbackResponse response = new FeedbackResponse();
            response.setSuccess(false);
            response.setFeedbackId(feedbackId);
            return response;
        }
    }

    @Override
    public FeedbackListResponse getFeedbackList(Integer page, Integer pageSize) {
        log.info("获取反馈列表: page={}, pageSize={}", page, pageSize);

        IPage<Feedback> pageResult = feedbackMapper.selectPage(
                new Page<>(page, pageSize),
                null
        );

        FeedbackListResponse response = new FeedbackListResponse();
        response.setSuccess(true);
        response.setTotal((int) pageResult.getTotal());

        List<FeedbackItem> feedbacks = new ArrayList<>();
        for (Feedback fb : pageResult.getRecords()) {
            FeedbackItem item = new FeedbackItem();
            item.setFeedbackId(fb.getFeedbackId());
            item.setSessionId(fb.getSessionId());
            item.setQuery(fb.getQuery());
            item.setAnswer(fb.getAnswer());
            item.setRating(fb.getRating());
            item.setReason(fb.getReason());
            item.setCreatedAt(fb.getCreatedAt() != null ? fb.getCreatedAt().toString() : null);
            feedbacks.add(item);
        }
        response.setFeedbacks(feedbacks);

        log.info("获取反馈列表成功: total={}", response.getTotal());
        return response;
    }

    @Override
    public FeedbackStatsResponse getFeedbackStats() {
        log.info("获取反馈统计");

        FeedbackStatsResponse response = new FeedbackStatsResponse();
        try {
            int total = feedbackMapper.selectCount(null).intValue();
            int positive = feedbackMapper.countByRating(1);
            int negative = feedbackMapper.countByRating(-1);
            Double avgRating = feedbackMapper.avgRating();

            response.setTotal(total);
            response.setPositive(positive);
            response.setNegative(negative);
            response.setAvgRating(avgRating != null ? avgRating : 0.0);
            response.setSatisfactionRate(total > 0 ? (positive * 100.0 / total) : 0.0);
            response.setSuccess(true);

            log.info("获取反馈统计成功: total={}, positive={}, negative={}", total, positive, negative);
        } catch (Exception e) {
            log.error("获取反馈统计失败: {}", e.getMessage(), e);
            response.setSuccess(false);
        }
        return response;
    }

    @Override
    public FeedbackListResponse getBadCases() {
        log.info("获取差评案例");

        FeedbackListResponse response = new FeedbackListResponse();
        try {
            List<Feedback> badCases = feedbackMapper.selectBadCases();
            List<FeedbackItem> items = new ArrayList<>();
            for (Feedback fb : badCases) {
                FeedbackItem item = new FeedbackItem();
                item.setFeedbackId(fb.getFeedbackId());
                item.setQuery(fb.getQuery());
                item.setAnswer(fb.getAnswer());
                item.setRating(fb.getRating());
                item.setReason(fb.getReason());
                items.add(item);
            }
            response.setFeedbacks(items);
            response.setTotal(items.size());
            response.setSuccess(true);

            log.info("获取差评案例成功: count={}", items.size());
        } catch (Exception e) {
            log.error("获取差评案例失败: {}", e.getMessage(), e);
            response.setSuccess(false);
        }
        return response;
    }
}