package top.tqx.demo_1.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import top.tqx.demo_1.dto.FAQItem;
import top.tqx.demo_1.dto.FAQListResponse;
import top.tqx.demo_1.dto.FAQSuggestionItem;
import top.tqx.demo_1.dto.FAQSuggestionListResponse;
import top.tqx.demo_1.mapper.FAQMapper;
import top.tqx.demo_1.mapper.FAQSuggestionMapper;
import top.tqx.demo_1.dto.FAQCreateRequest;
import top.tqx.demo_1.dto.FAQUpdateRequest;
import top.tqx.demo_1.entity.FAQ;
import top.tqx.demo_1.entity.FAQSuggestion;
import top.tqx.demo_1.service.FAQService;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class FAQServiceImpl implements FAQService {

    @Autowired
    private FAQMapper faqMapper;

    @Autowired
    private FAQSuggestionMapper faqSuggestionMapper;

    @Override
    public FAQListResponse getFAQList(Integer page, Integer pageSize) {
        log.info("获取FAQ列表: page={}, pageSize={}", page, pageSize);

        IPage<FAQ> pageResult = faqMapper.selectPage(
                new Page<>(page, pageSize),
                new LambdaQueryWrapper<FAQ>().eq(FAQ::getStatus, "approved").orderByDesc(FAQ::getCreatedAt)
        );

        FAQListResponse response = new FAQListResponse();
        response.setSuccess(true);

        List<FAQItem> faqs = new ArrayList<>();
        for (FAQ faq : pageResult.getRecords()) {
            FAQItem item = new FAQItem();
            item.setId(faq.getId());
            item.setQuestion(faq.getQuestion());
            item.setAnswer(faq.getAnswer());
            item.setAvgRating(faq.getAvgRating());
            item.setFrequency(faq.getFrequency());
            item.setStatus(faq.getStatus());
            faqs.add(item);
        }
        response.setFaqs(faqs);
        response.setTotal((int) pageResult.getTotal());

        log.info("获取FAQ列表成功: count={}", faqs.size());
        return response;
    }

    @Override
    public FAQSuggestionListResponse getFAQSuggestions(Integer page, Integer pageSize) {
        log.info("获取FAQ建议列表: page={}, pageSize={}", page, pageSize);

        IPage<FAQSuggestion> pageResult = faqSuggestionMapper.selectPage(
                new Page<>(page, pageSize),
                new LambdaQueryWrapper<FAQSuggestion>().eq(FAQSuggestion::getStatus, "pending").orderByDesc(FAQSuggestion::getCreatedAt)
        );

        FAQSuggestionListResponse response = new FAQSuggestionListResponse();
        response.setSuccess(true);

        List<FAQSuggestionItem> suggestions = new ArrayList<>();
        for (FAQSuggestion suggestion : pageResult.getRecords()) {
            FAQSuggestionItem item = new FAQSuggestionItem();
            item.setId(suggestion.getId());
            item.setQuery(suggestion.getQuery());
            item.setAnswer(suggestion.getAnswer());
            item.setAvgRating(suggestion.getAvgRating());
            item.setFrequency(suggestion.getFrequency());
            suggestions.add(item);
        }
        response.setSuggestions(suggestions);
        response.setTotal((int) pageResult.getTotal());

        log.info("获取FAQ建议列表成功: count={}", suggestions.size());
        return response;
    }

    @Override
    public boolean approveSuggestion(Long id, String answer) {
        log.info("批准FAQ建议: id={}", id);

        FAQSuggestion suggestion = faqSuggestionMapper.selectById(id);
        if (suggestion == null) {
            log.warn("FAQ建议不存在: id={}", id);
            return false;
        }

        FAQ faq = new FAQ();
        faq.setQuestion(suggestion.getQuery());
        faq.setAnswer(answer != null && !answer.isEmpty() ? answer : suggestion.getAnswer());
        faq.setStatus("approved");
        faq.setAvgRating(suggestion.getAvgRating());
        faq.setFrequency(suggestion.getFrequency());
        faq.setCreatedAt(LocalDateTime.now());
        faq.setUpdatedAt(LocalDateTime.now());

        faqMapper.insert(faq);

        suggestion.setStatus("approved");
        suggestion.setFaqId(faq.getId());
        faqSuggestionMapper.updateById(suggestion);

        log.info("批准FAQ建议成功: id={}, faqId={}", id, faq.getId());
        return true;
    }

    @Override
    public boolean rejectSuggestion(Long id) {
        log.info("拒绝FAQ建议: id={}", id);

        FAQSuggestion suggestion = faqSuggestionMapper.selectById(id);
        if (suggestion == null) {
            log.warn("FAQ建议不存在: id={}", id);
            return false;
        }

        suggestion.setStatus("rejected");
        faqSuggestionMapper.updateById(suggestion);

        log.info("拒绝FAQ建议成功: id={}", id);
        return true;
    }

    @Override
    public FAQ createFAQ(FAQCreateRequest request) {
        FAQ faq = new FAQ();
        faq.setQuestion(request.getQuestion());
        faq.setAnswer(request.getAnswer());
        faq.setStatus("approved");
        faq.setAvgRating(BigDecimal.ZERO);
        faq.setFrequency(0);

        if (request.getSourceDocuments() != null && !request.getSourceDocuments().isEmpty()) {
            faq.setSourceDocuments(String.join(",", request.getSourceDocuments()));
        }

        faq.setCreatedAt(LocalDateTime.now());
        faq.setUpdatedAt(LocalDateTime.now());

        faqMapper.insert(faq);
        log.info("创建FAQ成功: id={}", faq.getId());
        return faq;
    }

    @Override
    public FAQ getFAQById(Long id) {
        return faqMapper.selectById(id);
    }

    @Override
    public FAQ updateFAQ(Long id, FAQUpdateRequest request) {
        FAQ faq = faqMapper.selectById(id);
        if (faq == null) {
            throw new IllegalArgumentException("FAQ不存在");
        }

        if (request.getQuestion() != null) {
            faq.setQuestion(request.getQuestion());
        }
        if (request.getAnswer() != null) {
            faq.setAnswer(request.getAnswer());
        }
        if (request.getAvgRating() != null) {
            faq.setAvgRating(request.getAvgRating());
        }
        if (request.getFrequency() != null) {
            faq.setFrequency(request.getFrequency());
        }
        if (request.getStatus() != null) {
            faq.setStatus(request.getStatus());
        }
        if (request.getSourceDocuments() != null) {
            faq.setSourceDocuments(String.join(",", request.getSourceDocuments()));
        }

        faq.setUpdatedAt(LocalDateTime.now());
        faqMapper.updateById(faq);
        return faq;
    }

    @Override
    public boolean deleteFAQ(Long id) {
        return faqMapper.deleteById(id) > 0;
    }

    @Override
    public int batchDeleteFAQs(List<Long> ids) {
        return faqMapper.deleteBatchIds(ids);
    }

    @Override
    public List<FAQ> listFAQs(String status, Integer limit) {
        LambdaQueryWrapper<FAQ> wrapper = new LambdaQueryWrapper<>();

        if (status != null && !status.isEmpty()) {
            wrapper.eq(FAQ::getStatus, status);
        }

        wrapper.orderByDesc(FAQ::getCreatedAt);
        wrapper.last("LIMIT " + (limit != null ? limit : 100));

        return faqMapper.selectList(wrapper);
    }
}