package com.xindazhou.business.service.service.feedback;

import com.xindazhou.business.controller.admin.service.feedback.vo.FeedbackHandleReqVO;
import com.xindazhou.framework.common.util.json.JsonUtils;
import com.xindazhou.business.controller.admin.service.feedback.vo.FeedbackPageReqVO;
import com.xindazhou.business.controller.admin.service.feedback.vo.FeedbackRespVO;
import com.xindazhou.business.convert.service.feedback.FeedbackConvert;
import com.xindazhou.business.dal.service.dataobject.feedback.FeedbackDO;
import com.xindazhou.business.dal.service.mysql.feedback.FeedbackMapper;
import com.xindazhou.framework.common.exception.util.ServiceExceptionUtil;
import com.xindazhou.framework.common.pojo.PageResult;
import com.xindazhou.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.xindazhou.framework.security.core.util.SecurityFrameworkUtils;
import com.xindazhou.user.api.user.MemberUserApi;
import com.xindazhou.user.api.user.dto.MemberUserRespDTO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

import static com.xindazhou.framework.common.exception.enums.GlobalErrorCodeConstants.NOT_FOUND;

/**
 * APP意见反馈 Service 实现类
 *
 * @author xindazhou
 */
@Service("serviceFeedbackServiceImpl")
@Validated
@Slf4j
public class FeedbackServiceImpl implements FeedbackService {

    @Resource
    private FeedbackMapper feedbackMapper;

    @Resource
    private MemberUserApi memberUserApi;

    @Override
    public PageResult<FeedbackRespVO> getFeedbackPage(FeedbackPageReqVO pageReqVO) {
        // 处理关键字搜索（用户手机号/昵称需要通过RPC查询，这里先按用户ID搜索）
        PageResult<FeedbackDO> pageResult = feedbackMapper.selectPage(pageReqVO, new LambdaQueryWrapperX<FeedbackDO>()
                .eqIfPresent(FeedbackDO::getType, pageReqVO.getType())
                .eqIfPresent(FeedbackDO::getHandleStatus, pageReqVO.getHandleStatus())
                .betweenIfPresent(FeedbackDO::getCreateTime, pageReqVO.getCreateTimeStart(), pageReqVO.getCreateTimeEnd())
                .orderByDesc(FeedbackDO::getId));

        // 转换为VO
        List<FeedbackRespVO> respList = FeedbackConvert.INSTANCE.convertList(pageResult.getList());

        // 填充用户信息
        fillUserInfoList(respList);

        // 解析图片列表
        respList.forEach(feedback -> {
            if (feedback.getImages() == null && feedback.getContent() != null) {
                // 从content中提取图片（如果有）
                // 这里可以根据实际需求处理
            }
        });

        return new PageResult<>(respList, pageResult.getTotal());
    }

    @Override
    public FeedbackRespVO getFeedback(Long id) {
        FeedbackDO feedback = feedbackMapper.selectById(id);
        if (feedback == null) {
            throw ServiceExceptionUtil.exception(NOT_FOUND, "意见反馈不存在");
        }

        FeedbackRespVO respVO = FeedbackConvert.INSTANCE.convert(feedback);

        // 填充用户信息
        fillUserInfo(respVO, feedback.getUserId());

        // 解析图片列表
        if (feedback.getImages() != null && !feedback.getImages().isEmpty()) {
            try {
                List<String> images = JsonUtils.parseArray(feedback.getImages(), String.class);
                respVO.setImages(images);
            } catch (Exception e) {
                log.warn("解析反馈图片列表失败", e);
            }
        }

        return respVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleFeedback(Long id, FeedbackHandleReqVO handleReqVO) {
        // 校验反馈存在
        FeedbackDO feedback = feedbackMapper.selectById(id);
        if (feedback == null) {
            throw ServiceExceptionUtil.exception(NOT_FOUND, "意见反馈不存在");
        }

        // 只有待处理的反馈才能处理
        if (feedback.getHandleStatus() != 0) {
            throw ServiceExceptionUtil.exception(NOT_FOUND, "该反馈已处理，不能重复处理");
        }

        // 更新处理信息
        FeedbackDO updateObj = new FeedbackDO();
        updateObj.setId(id);
        updateObj.setHandleStatus(1);
        updateObj.setHandleResult(handleReqVO.getHandleResult());
        updateObj.setHandleRemark(handleReqVO.getHandleRemark());
        updateObj.setHandleTime(LocalDateTime.now());
        
        // 获取当前登录用户信息
        Long handlerId = SecurityFrameworkUtils.getLoginUserId();
        if (handlerId != null) {
            updateObj.setHandlerId(handlerId);
            // 获取处理人名称（可以通过AdminUserApi获取，这里先简化）
            updateObj.setHandlerName("管理员");
        }

        feedbackMapper.updateById(updateObj);
    }

    /**
     * 填充单个反馈的用户信息
     */
    private void fillUserInfo(FeedbackRespVO respVO, Long userId) {
        if (userId == null) {
            return;
        }
        try {
            MemberUserRespDTO user = memberUserApi.getUser(userId).getCheckedData();
            if (user != null) {
                FeedbackRespVO.UserInfo userInfo = new FeedbackRespVO.UserInfo();
                userInfo.setNickname(user.getNickname());
                userInfo.setMobile(user.getMobile());
                userInfo.setAvatar(user.getAvatar());
                respVO.setUserInfo(userInfo);
            }
        } catch (Exception e) {
            log.warn("获取用户信息失败", e);
        }
    }

    /**
     * 批量填充反馈列表的用户信息
     */
    private void fillUserInfoList(List<FeedbackRespVO> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        Set<Long> userIds = list.stream()
                .map(FeedbackRespVO::getUserId)
                .filter(userId -> userId != null)
                .collect(Collectors.toSet());
        if (userIds.isEmpty()) {
            return;
        }
        try {
            Map<Long, MemberUserRespDTO> userMap = memberUserApi.getUserMap(userIds);
            list.forEach(feedback -> {
                MemberUserRespDTO user = userMap.get(feedback.getUserId());
                if (user != null) {
                    FeedbackRespVO.UserInfo userInfo = new FeedbackRespVO.UserInfo();
                    userInfo.setNickname(user.getNickname());
                    userInfo.setMobile(user.getMobile());
                    userInfo.setAvatar(user.getAvatar());
                    feedback.setUserInfo(userInfo);
                }
            });
        } catch (Exception e) {
            log.warn("批量获取用户信息失败", e);
        }
    }

}

