package com.corewing.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.corewing.app.entity.Feedback;
import com.corewing.app.mapper.FeedbackMapper;
import com.corewing.app.service.FeedbackService;
import com.corewing.app.util.I18nUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 问题反馈 Service 实现类
 */
@Service
public class FeedbackServiceImpl extends ServiceImpl<FeedbackMapper, Feedback> implements FeedbackService {

    @Override
    public boolean createFeedback(Feedback feedback) {
        // 设置默认状态为待处理
        if (feedback.getStatus() == null) {
            feedback.setStatus(0);
        }
        return this.save(feedback);
    }

    @Override
    public List<Feedback> listByUserId(Long userId) {
        if (userId == null) {
            throw new RuntimeException(I18nUtil.getMessage("error.feedback.user.id.empty"));
        }
        LambdaQueryWrapper<Feedback> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Feedback::getUserId, userId)
                .orderByDesc(Feedback::getCreateTime);
        return this.list(wrapper);
    }

    @Override
    public IPage<Feedback> pageList(Page<Feedback> page, Long userId, String feedbackType, Integer status) {
        LambdaQueryWrapper<Feedback> wrapper = new LambdaQueryWrapper<>();

        // 条件查询
        if (userId != null) {
            wrapper.eq(Feedback::getUserId, userId);
        }
        if (StringUtils.hasText(feedbackType)) {
            wrapper.eq(Feedback::getFeedbackType, feedbackType);
        }
        if (status != null) {
            wrapper.eq(Feedback::getStatus, status);
        }

        // 按创建时间倒序排序
        wrapper.orderByDesc(Feedback::getCreateTime);

        return this.page(page, wrapper);
    }

    @Override
    public boolean updateStatus(Long id, Integer status) {
        if (id == null) {
            throw new RuntimeException(I18nUtil.getMessage("error.feedback.id.empty"));
        }
        if (status == null) {
            throw new RuntimeException(I18nUtil.getMessage("error.feedback.status.empty"));
        }

        Feedback feedback = new Feedback();
        feedback.setId(id);
        feedback.setStatus(status);

        return this.updateById(feedback);
    }
}
