package com.xindazhou.platform.service.service.evaluation;

import com.xindazhou.platform.controller.admin.service.evaluation.vo.EvaluationPageReqVO;
import com.xindazhou.platform.controller.admin.service.evaluation.vo.EvaluationRespVO;
import com.xindazhou.platform.convert.service.evaluation.EvaluationConvert;
import com.xindazhou.platform.dal.service.dataobject.evaluation.EvaluationDO;
import com.xindazhou.platform.dal.service.mysql.evaluation.EvaluationMapper;
import com.xindazhou.framework.common.exception.util.ServiceExceptionUtil;
import com.xindazhou.framework.common.pojo.CommonResult;
import com.xindazhou.framework.common.pojo.PageResult;
import com.xindazhou.framework.common.util.json.JsonUtils;
import com.xindazhou.framework.mybatis.core.query.LambdaQueryWrapperX;
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.validation.annotation.Validated;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

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

/**
 * 服务评价 Service 实现类
 *
 * @author xindazhou
 */
@Service("platformEvaluationServiceImpl")
@Validated
@Slf4j
public class EvaluationServiceImpl implements EvaluationService {

    @Resource
    private EvaluationMapper evaluationMapper;

    @Resource
    private MemberUserApi memberUserApi;

    @Override
    public PageResult<EvaluationRespVO> getEvaluationPage(EvaluationPageReqVO pageReqVO) {
        // 处理关键字搜索（用户手机号/订单号）
        LambdaQueryWrapperX<EvaluationDO> queryWrapper = new LambdaQueryWrapperX<EvaluationDO>()
                .likeIfPresent(EvaluationDO::getOrderNo, pageReqVO.getKeyword())
                .eqIfPresent(EvaluationDO::getRating, pageReqVO.getRating())
                .betweenIfPresent(EvaluationDO::getCreateTime, pageReqVO.getCreateTimeStart(), pageReqVO.getCreateTimeEnd())
                .orderByDesc(EvaluationDO::getId);

        // 如果关键字不为空，还需要通过RPC查询用户信息（这里先简化，只按订单号搜索）
        PageResult<EvaluationDO> pageResult = evaluationMapper.selectPage(pageReqVO, queryWrapper);

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

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

        // 解析图片列表
        respList.forEach(evaluation -> {
            if (evaluation.getImages() == null) {
                EvaluationDO evaluationDO = pageResult.getList().stream()
                        .filter(e -> e.getId().equals(evaluation.getId()))
                        .findFirst()
                        .orElse(null);
                if (evaluationDO != null && evaluationDO.getImages() != null && !evaluationDO.getImages().isEmpty()) {
                    try {
                        List<String> images = JsonUtils.parseArray(evaluationDO.getImages(), String.class);
                        evaluation.setImages(images);
                    } catch (Exception e) {
                        log.warn("解析评价图片列表失败", e);
                    }
                }
            }
        });

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

    @Override
    public EvaluationRespVO getEvaluation(Long id) {
        EvaluationDO evaluation = evaluationMapper.selectById(id);
        if (evaluation == null) {
            throw ServiceExceptionUtil.exception(NOT_FOUND, "服务评价不存在");
        }

        EvaluationRespVO respVO = EvaluationConvert.INSTANCE.convert(evaluation);

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

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

        return respVO;
    }

    /**
     * 填充单个评价的用户信息
     */
    private void fillUserInfo(EvaluationRespVO respVO, Long userId) {
        if (userId == null) {
            return;
        }
        try {
            CommonResult<MemberUserRespDTO> result = memberUserApi.getUser(userId);
            if (result.isSuccess() && result.getData() != null) {
                MemberUserRespDTO user = result.getData();
                EvaluationRespVO.UserInfo userInfo = new EvaluationRespVO.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<EvaluationRespVO> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        Set<Long> userIds = list.stream()
                .map(EvaluationRespVO::getUserId)
                .filter(userId -> userId != null)
                .collect(Collectors.toSet());
        if (userIds.isEmpty()) {
            return;
        }
        try {
            CommonResult<List<MemberUserRespDTO>> result = memberUserApi.getUserList(userIds);
            if (result.isSuccess() && result.getData() != null) {
                Map<Long, MemberUserRespDTO> userMap = result.getData().stream()
                        .collect(Collectors.toMap(MemberUserRespDTO::getId, user -> user));
                list.forEach(evaluation -> {
                    MemberUserRespDTO user = userMap.get(evaluation.getUserId());
                    if (user != null) {
                        EvaluationRespVO.UserInfo userInfo = new EvaluationRespVO.UserInfo();
                        userInfo.setNickname(user.getNickname());
                        userInfo.setMobile(user.getMobile());
                        userInfo.setAvatar(user.getAvatar());
                        evaluation.setUserInfo(userInfo);
                    }
                });
            }
        } catch (Exception e) {
            log.warn("批量获取用户信息失败", e);
        }
    }

}

