package com.jeesharp.business.modules.setting.application;

import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.contentsecurity.api.ContentSecurityApi;
import com.jeesharp.business.modules.contentsecurity.dto.ContentSecurityBizRef;
import com.jeesharp.business.modules.contentsecurity.dto.ContentSecurityUgcCheckOutcome;
import com.jeesharp.business.modules.contentsecurity.enums.CheckDecisionEnum;
import com.jeesharp.business.modules.contentsecurity.enums.ContentSceneEnum;
import com.jeesharp.business.modules.contentsecurity.enums.ContentSecurityBizModuleEnum;
import com.jeesharp.business.modules.contentsecurity.event.ContentSecurityMediaCompletedEvent;
import com.jeesharp.business.modules.contentsecurity.support.ContentSecurityUgcCheckSupport;
import com.jeesharp.business.modules.setting.convert.FeedbackConvert;
import com.jeesharp.business.modules.setting.dto.FeedbackSubmitDTO;
import com.jeesharp.business.modules.setting.entity.Feedback;
import com.jeesharp.business.modules.setting.enums.FeedbackStatusEnum;
import com.jeesharp.business.modules.setting.service.FeedbackService;
import com.jeesharp.business.modules.setting.vo.FeedbackQueryVO;
import com.jeesharp.business.modules.setting.vo.FeedbackVO;
import com.jeesharp.framework.pojo.Page;
import com.jeesharp.framework.utils.WebFrameworkUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 意见反馈应用服务
 *
 * @author jeesharp
 * @version 2026-02-05
 */
@Service
@Transactional
@AllArgsConstructor
public class FeedbackApplicationService {

    private final FeedbackService feedbackService;
    private final ContentSecurityApi contentSecurityApi;

    /**
     * 提交意见反馈
     *
     * @param memberId 会员ID
     * @param dto      反馈提交DTO
     * @return 反馈ID
     */
    @Transactional(readOnly = false)
    public String submitFeedback(String memberId, FeedbackSubmitDTO dto) {
        String text = StrUtil.trimToEmpty(dto.getTitle()) + "\n" + StrUtil.trimToEmpty(dto.getContent());
        ContentSecurityUgcCheckOutcome csOutcome = ContentSecurityUgcCheckSupport.checkTextAndImages(
                contentSecurityApi,
                memberId,
                null,
                ContentSceneEnum.FEEDBACK,
                ContentSecurityBizRef.builder()
                        .bizModule(ContentSecurityBizModuleEnum.FEEDBACK.getCode())
                        .bizType("FEEDBACK")
                        .build(),
                text,
                dto.getImages());
        String feedbackId = feedbackService.submitFeedback(memberId, FeedbackConvert.INSTANCE.toEntity(dto));
        ContentSecurityUgcCheckSupport.bindAfterPersist(
                contentSecurityApi,
                ContentSecurityBizModuleEnum.FEEDBACK.getCode(),
                feedbackId,
                csOutcome);
        return feedbackId;
    }

    /**
     * 微信异步图片检测回调：违规时关闭反馈并写入说明。
     */
    @Transactional(readOnly = false)
    public void handleContentSecurityMediaCompleted(ContentSecurityMediaCompletedEvent event) {
        if (event == null || !ContentSecurityBizModuleEnum.FEEDBACK.getCode().equals(event.getBizModule())) {
            return;
        }
        if (event.getDecision() != CheckDecisionEnum.REJECT) {
            return;
        }
        Feedback feedback = feedbackService.get(event.getBizId());
        if (feedback == null) {
            return;
        }
        feedback.setStatus(FeedbackStatusEnum.CLOSED.getValue());
        feedback.setHandleResult("图片内容不符合规范，反馈已关闭");
        feedback.setHandleDate(LocalDateTime.now());
        feedbackService.update(feedback);
    }

    /**
     * 获取反馈详情
     *
     * @param id 反馈ID
     * @return 反馈VO
     */
    @Transactional(readOnly = true)
    public FeedbackVO getFeedback(String id) {
        Feedback feedback = feedbackService.get(id);
        return FeedbackConvert.INSTANCE.toVO(feedback);
    }

    /**
     * 分页查询反馈列表
     *
     * @param page  分页对象
     * @param query 查询条件
     * @return 分页结果
     */
    @Transactional(readOnly = true)
    public Page<FeedbackVO> findPage(Page<Feedback> page, FeedbackQueryVO query) {
        Page<Feedback> result = feedbackService.findPage(page, query);
        // 转换为 VO
        List<FeedbackVO> voList = FeedbackConvert.INSTANCE.toVOList(result.getRecords());
        // 构建返回分页
        Page<FeedbackVO> voPage = new Page<>();
        voPage.setRecords(voList);
        voPage.setTotal(result.getTotal());
        voPage.setPageNo(result.getPageNo());
        voPage.setPageSize(result.getPageSize());
        return voPage;
    }

    /**
     * 根据会员ID查询反馈列表
     *
     * @param memberId 会员ID
     * @return 反馈列表
     */
    @Transactional(readOnly = true)
    public List<FeedbackVO> listByMemberId(String memberId) {
        List<Feedback> list = feedbackService.listByMemberId(memberId);
        return FeedbackConvert.INSTANCE.toVOList(list);
    }

    // ==================== 后台管理：反馈处理 ====================

    /**
     * 处理反馈
     *
     * @param id           反馈ID
     * @param handleResult 处理结果/回复内容
     */
    @Transactional(readOnly = false)
    public void handleFeedback(String id, String handleResult) {
        feedbackService.handleFeedback(id, handleResult,
                WebFrameworkUtils.getLoginUserId(), WebFrameworkUtils.getLoginUserName());
    }

    /**
     * 完成反馈处理
     *
     * @param id           反馈ID
     * @param handleResult 处理结果/回复内容
     */
    @Transactional(readOnly = false)
    public void completeFeedback(String id, String handleResult) {
        feedbackService.completeFeedback(id, handleResult,
                WebFrameworkUtils.getLoginUserId(), WebFrameworkUtils.getLoginUserName());
    }

    /**
     * 关闭反馈
     *
     * @param id 反馈ID
     */
    @Transactional(readOnly = false)
    public void closeFeedback(String id) {
        feedbackService.closeFeedback(id,
                WebFrameworkUtils.getLoginUserId(), WebFrameworkUtils.getLoginUserName());
    }

    /**
     * 批量删除反馈
     *
     * @param ids 反馈ID，多个用逗号分隔
     */
    @Transactional(readOnly = false)
    public void delete(String ids) {
        feedbackService.batchDelete(StrUtil.splitTrim(ids, ','));
    }
}
