package com.sckw.system.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sckw.core.exception.SystemException;
import com.sckw.core.web.constant.HttpStatus;
import com.sckw.system.model.Feedbacks;
import com.sckw.system.model.vo.req.FeedbackListReqVo;
import com.sckw.system.model.vo.req.SubmitFeedbackReqVo;
import com.sckw.system.model.vo.res.FeedbackResVo;
import com.sckw.system.repository.FeedbacksService;
import com.sckw.system.repository.KwsUserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 意见反馈业务Service实现类
 * @author chenxiaofei
 * @date 2026-01-12
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class KwsFeedbackService {

    private final FeedbacksService feedbacksService;
    private final KwsUserRepository kwsUserRepository;

    @Transactional(rollbackFor = Exception.class)
    public FeedbackResVo submitFeedback(SubmitFeedbackReqVo reqVo) {
        log.info("提交意见反馈，用户ID: {}", reqVo.getUserId());

        // 1. 校验用户是否存在
        if (Objects.isNull(kwsUserRepository.getById(reqVo.getUserId()))) {
            throw new SystemException(HttpStatus.QUERY_FAIL_CODE, "用户不存在");
        }

        // 2. 构建反馈实体
        Feedbacks feedback = new Feedbacks();
        feedback.setUserId(reqVo.getUserId());
        feedback.setContent(reqVo.getContent());
        
        // 3. 处理图片列表，转换为JSON字符串
        if (CollUtil.isNotEmpty(reqVo.getImages())) {
            feedback.setImages(JSON.toJSONString(reqVo.getImages()));
        } else {
            feedback.setImages("[]");
        }
        
        feedback.setContactInfo(StrUtil.isNotBlank(reqVo.getContactInfo()) ? reqVo.getContactInfo() : "");
        // 默认未处理
        feedback.setIsProcessed(0);
        feedback.setCreatedAt(new Date());

        // 4. 保存到数据库
        if (!feedbacksService.save(feedback)) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, "提交反馈失败");
        }

        log.info("意见反馈提交成功，反馈ID: {}", feedback.getId());

        // 5. 返回响应对象
        return convertToResVo(feedback);
    }


    public Page<FeedbackResVo> getFeedbackList(FeedbackListReqVo reqVo) {
        log.info("查询用户反馈列表，用户ID: {}, 页码: {}, 每页数量: {}", 
                reqVo.getUserId(), reqVo.getPageNum(), reqVo.getPageSize());

        // 1. 校验用户是否存在
        if (Objects.isNull(kwsUserRepository.getById(reqVo.getUserId()))) {
            throw new SystemException(HttpStatus.QUERY_FAIL_CODE, "用户不存在");
        }

        // 2. 构建分页查询条件
        Page<Feedbacks> page = new Page<>(reqVo.getPageNum(), reqVo.getPageSize());
        LambdaQueryWrapper<Feedbacks> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Feedbacks::getUserId, reqVo.getUserId())
                    .orderByDesc(Feedbacks::getCreatedAt);

        // 3. 执行查询
        Page<Feedbacks> feedbackPage = feedbacksService.page(page, queryWrapper);

        // 4. 转换为响应对象
        Page<FeedbackResVo> resPage = new Page<>(feedbackPage.getCurrent(), feedbackPage.getSize(), feedbackPage.getTotal());
        List<FeedbackResVo> resVoList = feedbackPage.getRecords().stream()
                .map(this::convertToResVo)
                .collect(Collectors.toList());
        resPage.setRecords(resVoList);

        log.info("查询反馈列表成功，共 {} 条记录", resPage.getTotal());
        return resPage;
    }


    public FeedbackResVo getFeedbackDetail(Long feedbackId) {
        log.info("查询反馈详情，反馈ID: {}", feedbackId);

        // 1. 根据ID查询反馈
        Feedbacks feedback = feedbacksService.getById(feedbackId);
        if (Objects.isNull(feedback)) {
            throw new SystemException(HttpStatus.QUERY_FAIL_CODE, "反馈记录不存在");
        }

        // 2. 转换为响应对象
        return convertToResVo(feedback);
    }

    /**
     * 将实体对象转换为响应对象
     * @param feedback 反馈实体
     * @return FeedbackResVo
     */
    private FeedbackResVo convertToResVo(Feedbacks feedback) {
        // 解析图片JSON字符串为列表
        List<String> imageList = new ArrayList<>();
        if (StrUtil.isNotBlank(feedback.getImages())) {
            try {
                imageList = JSON.parseArray(feedback.getImages(), String.class);
            } catch (Exception e) {
                log.warn("解析图片JSON失败，反馈ID: {}, images: {}", feedback.getId(), feedback.getImages(), e);
                imageList = new ArrayList<>();
            }
        }

        // 处理状态描述
        String processedDesc = feedback.getIsProcessed() == 1 ? "已处理" : "未处理";

        return FeedbackResVo.builder()
                .id(feedback.getId())
                .userId(feedback.getUserId())
                .content(feedback.getContent())
                .images(imageList)
                .contactInfo(feedback.getContactInfo())
                .isProcessed(feedback.getIsProcessed())
                .processedDesc(processedDesc)
                .createdAt(feedback.getCreatedAt())
                .build();
    }

}


