package shop.alien.store.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import shop.alien.entity.store.*;
import shop.alien.entity.store.vo.*;
import shop.alien.mapper.*;
import shop.alien.store.service.StoreCommentService;
import shop.alien.store.util.FileUploadUtil;
import shop.alien.util.common.DateUtils;
import shop.alien.util.common.netease.ImageCheckUtil;
import shop.alien.util.common.netease.TextCheckUtil;
import shop.alien.util.common.safe.TextModerationResultVO;
import shop.alien.util.common.safe.TextModerationUtil;
import shop.alien.util.common.safe.TextReviewServiceEnum;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * 评论表 服务实现类
 *
 * @author ssk
 * @since 2025-01-02
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class StoreCommentServiceImpl extends ServiceImpl<StoreCommentMapper, StoreComment> implements StoreCommentService {

    private final StoreCommentMapper storeCommentMapper;

    private final LifeLikeRecordMapper lifeLikeRecordMapper;

    private final FileUploadUtil fileUploadUtil;

    private final StoreImgMapper storeImgMapper;

    private final LifeUserViolationMapper lifeUserViolationMapper;

    private final StoreUserMapper storeUserMapper;

    private final LifeUserMapper lifeUserMapper;

    private final StoreCommentAppealMapper storeCommentAppealMapper;

    private final StoreInfoMapper storeInfoMapper;

    @Autowired
    private TextModerationUtil textModerationUtil;

    /**
     * 评论列表
     *
     * @param pageNum      页数
     * @param pageSize     页容
     * @param businessId   业务id
     * @param businessType 业务类型(1:订单评论, 2:动态社区评论, 3:活动评论, 4:店铺打卡评论, 5:订单评价, 6:订单评论的评论)
     * @param storeId      门店id
     * @param replyStatus  回复状态(0:全部, 1:已回复, 2:未回复)
     * @param commentLevel 评论等级(0:全部, 1:好评, 2:中评, 3:差评)
     * @param days         查询时间, 多少天前
     * @param phoneId      消息标识
     * @param userType     评论的用户类型(0:商家, 其他:用户)
     * @return IPage<StoreComment>
     */
    @Override
    public IPage<StoreCommentVo> getList(Integer pageNum, Integer pageSize, Integer businessId, Integer businessType, Integer storeId, Integer replyStatus, Integer commentLevel, Integer days, String phoneId, Integer userType) {
        IPage<StoreCommentVo> storeCommentIPage = new Page<>(pageNum, pageSize);
        QueryWrapper<StoreCommentVo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(null != businessId, "a.business_id", businessId);
        queryWrapper.eq(null != businessType, "a.business_type", businessType);
        queryWrapper.eq(null != storeId, "a.store_id", storeId);
        //好评 a>=4
        queryWrapper.ge(null != commentLevel && 1 == commentLevel, "a.score", 4.5);
        //中评 a>=2&& a<4
        queryWrapper.ge(null != commentLevel && 2 == commentLevel, "a.score", 3).le(null != commentLevel && 2 == commentLevel, "a.score", 4);
        //差评 a<2
        queryWrapper.ge(null != commentLevel && 3 == commentLevel, "a.score", 0.5).le(null != commentLevel && 3 == commentLevel, "a.score", 2.5);
        if (null != days) {
            Date date = DateUtils.calcDays(new Date(), -days);
            queryWrapper.ge("a.created_time", DateUtils.formatDate(date, "yyyy-MM-dd"));
        }
        //通过当前登录人id 类型 查询举报业务id
        List<LifeUserViolation> lifeUserViolations = new ArrayList<>();
        if(businessType==2){
            String userId;
            if(phoneId.startsWith("store_")){
                userId = phoneId.substring("store_".length());
                StoreUser storeUser = storeUserMapper.selectOne(new LambdaQueryWrapper<StoreUser>().eq(StoreUser::getPhone,userId));
                if(storeUser!=null){
                    LambdaQueryWrapper<LifeUserViolation> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.eq(LifeUserViolation::getReportingUserId,storeUser.getId());
                    lambdaQueryWrapper.eq(LifeUserViolation::getReportingUserType,1);
                    lambdaQueryWrapper.ne(LifeUserViolation::getProcessingStatus,2);
                    lifeUserViolations = lifeUserViolationMapper.selectList(lambdaQueryWrapper);
                }
            }else{
                userId = phoneId.substring("user_".length());
                LifeUser lifeUser = lifeUserMapper.selectOne(new LambdaQueryWrapper<LifeUser>().eq(LifeUser::getUserPhone,userId));
                if(lifeUser!=null){
                    LambdaQueryWrapper<LifeUserViolation> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.eq(LifeUserViolation::getReportingUserId,lifeUser.getId());
                    lambdaQueryWrapper.eq(LifeUserViolation::getReportingUserType,2);
                    lambdaQueryWrapper.ne(LifeUserViolation::getProcessingStatus,2);
                    lifeUserViolations = lifeUserViolationMapper.selectList(lambdaQueryWrapper);
                }
            }
        }
        List<Integer> businessIds = lifeUserViolations.stream()
                .filter(Objects::nonNull)
                .map(LifeUserViolation::getBusinessId)
                .filter(id -> id != null && !id.toString().isEmpty())
                .collect(Collectors.toList());
        if(businessIds!=null && businessIds.size()>0){
            queryWrapper.notIn("a.id",businessIds);
        }

        //先查询父级评论
        queryWrapper.isNull(businessType != 1, "a.reply_id").eq("a.delete_flag", 0).orderByDesc("a.created_time");
        IPage<StoreCommentVo> page = storeCommentMapper.getCommentPage(storeCommentIPage, queryWrapper);
        List<StoreCommentVo> records = page.getRecords();
        List<StoreCommentVo> storeCommentVoList = new ArrayList<>();

        //评价图片
        Set<Integer> imgIdList = new HashSet<>();
        for (int i = 0; i < records.size(); i++) {
            StoreCommentVo storeCommentVo = new StoreCommentVo();
            BeanUtils.copyProperties(records.get(i), storeCommentVo);
            //首评
            storeCommentVo.setFirstComment(i == 0);
            //有无图片
            if (records.get(i).getImgId() != null) {
                storeCommentVo.setHasImage(true);
                String[] split = records.get(i).getImgId().split(",");
                for (String s : split) {
                    imgIdList.add(Integer.parseInt(s));
                }
            } else {
                storeCommentVo.setHasImage(false);
            }
            //低分
            storeCommentVo.setLowScore(records.get(i).getScore() <= 1);
            storeCommentVoList.add(storeCommentVo);

            QueryWrapper<StoreCommentAppealVo> storeCommentAppealVoQueryWrapper = new QueryWrapper<>();
            storeCommentAppealVoQueryWrapper.eq("a.comment_id", storeCommentVo.getId()).eq("a.delete_flag", 0).orderByDesc("a.created_time").last("limit 1");
            StoreCommentAppealVo commentDetail = storeCommentAppealMapper.getCommentDetail(storeCommentAppealVoQueryWrapper);
            if (ObjectUtils.isNotEmpty(commentDetail)) {
                storeCommentVo.setAppealFlag(1);
                storeCommentVo.setAppealStatusStr(commentDetail.getAppealStatusStr());
                storeCommentVo.setAppealStatus(commentDetail.getAppealStatus());
            }else {
                storeCommentVo.setAppealFlag(0);
            }
        }

        //塞图片
        if (!imgIdList.isEmpty()) {
            List<StoreImg> storeImgList = storeImgMapper.selectList(new QueryWrapper<StoreImg>().in("id", imgIdList));

            storeCommentVoList.forEach(storeCommentVo -> {
                if (null != storeCommentVo.getImgId()) {
                    storeCommentVo.setImgUrl(new ArrayList<>());
                    for (StoreImg storeImg : storeImgList) {
                        for (String s : storeCommentVo.getImgId().split(",")) {
                            if (storeImg.getId().equals(Integer.parseInt(s))) {
                                storeCommentVo.getImgUrl().add(storeImg.getImgUrl());
                            }
                        }
                    }
                }
            });
        }

        //父级评论下拼接子评论
        for (StoreCommentVo storeCommentVo : storeCommentVoList) {
            storeCommentVo.setCommitCount(0);
            //父级点赞状态
            if (StringUtils.isNotEmpty(phoneId)) {
                LambdaQueryWrapper<LifeLikeRecord> likeRecordQueryWrapper = new LambdaQueryWrapper<>();
                likeRecordQueryWrapper.eq(LifeLikeRecord::getDianzanId, phoneId).eq(LifeLikeRecord::getHuifuId, storeCommentVo.getId());
                Integer i = lifeLikeRecordMapper.selectCount(likeRecordQueryWrapper);
                if (i > 0) {
                    storeCommentVo.setIsLike(1);
                } else {
                    storeCommentVo.setIsLike(0);
                }
            }
            QueryWrapper<StoreCommentVo> childQueryWrapper = new QueryWrapper<>();
            if(businessIds!=null && businessIds.size()>0){
                childQueryWrapper.notIn("a.id",businessIds);
            }
            childQueryWrapper.eq(null != businessId && 6 == businessId, "a.business_id", businessId).eq("a.delete_flag", 0).eq("a.reply_id", storeCommentVo.getId()).orderByDesc("a.created_time");
            List<StoreCommentVo> childCommentList = storeCommentMapper.getCommentList(childQueryWrapper);
            storeCommentVo.setCommitCount(storeCommentVo.getCommitCount() + childCommentList.size());
            //评价的评论的评论
            childCommentList.forEach(child -> {
                QueryWrapper<StoreCommentVo> childQueryCommentWrapper = new QueryWrapper<>();
                childQueryCommentWrapper
//                        .eq(null != businessId && 6 == businessId, "a.business_id", businessId)
                        .eq("a.delete_flag", 0).eq("a.reply_id", child.getId()).orderByDesc("a.created_time");
                List<StoreCommentVo> childComment2List = storeCommentMapper.getCommentList(childQueryCommentWrapper);
                child.setStoreComment(childComment2List);
                storeCommentVo.setCommitCount(storeCommentVo.getCommitCount() + childComment2List.size());
            });
            //筛选商家评论
            List<StoreCommentVo> storeCommentList = new ArrayList<>();
            if (null != userType && userType == 0) {
                List<StoreCommentVo> collect = childCommentList.stream().filter(childComment -> childComment.getPhoneId().contains("store_")).collect(Collectors.toList());
                if (!collect.isEmpty()) {
                    storeCommentList.add(collect.get(0));
                    storeCommentVo.setStoreComment(storeCommentList);
                }
            } else {
                storeCommentVo.setStoreComment(childCommentList);
            }
            //子级点赞状态
            if (StringUtils.isNotEmpty(phoneId)) {
                childCommentList.forEach(child -> {
                    LambdaQueryWrapper<LifeLikeRecord> childlikeRecordQueryWrapper = new LambdaQueryWrapper<>();
                    childlikeRecordQueryWrapper.eq(LifeLikeRecord::getDianzanId, phoneId).eq(LifeLikeRecord::getHuifuId, child.getId());
                    if (lifeLikeRecordMapper.selectCount(childlikeRecordQueryWrapper) > 0) {
                        child.setIsLike(1);
                    } else {
                        child.setIsLike(0);
                    }
                });
            }
        }
        IPage<StoreCommentVo> resultPage = new Page<>();
        resultPage.setCurrent(page.getCurrent());
        resultPage.setSize(page.getSize());
        resultPage.setTotal(page.getTotal());
        resultPage.setPages(page.getPages());
        //筛选有无评论
        List<StoreCommentVo> collect = new ArrayList<>();
        if (replyStatus != null) {
            if (1 == replyStatus) {
                //只查询有回复的评论
                collect = storeCommentVoList.stream().filter(storeCommentVo -> ObjectUtils.isNotEmpty(storeCommentVo.getStoreComment())).collect(Collectors.toList());
            } else if (2 == replyStatus) {
                //只查询无回复的评论
                collect = storeCommentVoList.stream().filter(storeCommentVo -> ObjectUtils.isEmpty(storeCommentVo.getStoreComment())).collect(Collectors.toList());
            } else {
                collect = storeCommentVoList;
            }
        }
//        collect.forEach(item -> {
//            item.setCommitCount(null != item.getStoreComment() ? item.getStoreComment().size() : 0);
//        });
        resultPage.setRecords(collect);
        return resultPage;
    }

    /**
     * 获取最新一条评论/评价
     *
     * @param businessId   业务id
     * @param businessType 业务类型(1:订单评论, 2:动态社区评论, 3:活动评论,4:店铺打卡评论)
     * @param storeId      门店id
     * @return StoreCommentVo
     */
    @Override
    public StoreCommentVo getOne(Integer businessId, Integer businessType, Integer storeId) {
        AtomicReference<Integer> count = new AtomicReference<>(0);
        QueryWrapper<StoreCommentVo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(null != businessId, "a.business_id", businessId).eq(null != businessType, "a.business_type", businessType).eq(null != storeId, "a.store_id", storeId).eq("a.delete_flag", 0).orderByDesc("a.created_time");
        List<StoreCommentVo> commentList = storeCommentMapper.getCommentList(queryWrapper);
        count.updateAndGet(v -> v + commentList.size());
        //父级评论下拼接子评论
        for (StoreCommentVo storeCommentVo : commentList) {
            QueryWrapper<StoreCommentVo> childQueryWrapper = new QueryWrapper<>();
            childQueryWrapper.eq("a.delete_flag", 0).eq("a.reply_id", storeCommentVo.getId());
            List<StoreCommentVo> childCommentList = storeCommentMapper.getCommentList(childQueryWrapper);
            count.updateAndGet(v -> v + childCommentList.size());
            //评价的评论的评论
            childCommentList.forEach(child -> {
                QueryWrapper<StoreCommentVo> childQueryCommentWrapper = new QueryWrapper<>();
                childQueryCommentWrapper
//                        .eq(null != businessId && 6 == businessId, "a.business_id", businessId)
                        .eq("a.delete_flag", 0).eq("a.reply_id", child.getId()).orderByDesc("a.created_time");
                List<StoreCommentVo> childComment2List = storeCommentMapper.getCommentList(childQueryCommentWrapper);
                count.updateAndGet(v -> v + childComment2List.size());
            });
        }
        if (!commentList.isEmpty()) {
            StoreCommentVo storeCommentVo = commentList.get(0);
            storeCommentVo.setCommitCount(Integer.parseInt(String.valueOf(count)));
            return storeCommentVo;
        }
        return null;
    }

    /**
     * 评论/评价数量和评分
     *
     * @param businessId   业务id
     * @param businessType 业务类型(1:订单评论, 2:动态社区评论, 3:活动评论,4:店铺打卡评论)
     * @param storeId      门店id
     * @return Integer
     */
    @Override
    public Map<String, String> getCommitCountAndScore(Integer businessId, Integer businessType, Integer storeId, String phoneId, Integer days) {
        Map<String, String> map = new HashMap<>();
        AtomicReference<Integer> count = new AtomicReference<>(0);
        QueryWrapper<StoreCommentVo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(null != businessId, "a.business_id", businessId);
        queryWrapper.eq(null != businessType, "a.business_type", businessType);
        queryWrapper.eq(null != storeId, "a.store_id", storeId);

        if (null != days) {
            Date date = DateUtils.calcDays(new Date(), -days);
            queryWrapper.ge("a.created_time", DateUtils.formatDate(date, "yyyy-MM-dd"));
        }

        //通过当前登录人id 类型 查询举报业务id
        List<LifeUserViolation> lifeUserViolations = new ArrayList<>();
        if(businessType==2){
            String userId;
            if(phoneId!=null && !phoneId.equals("") && phoneId.startsWith("store_")){
                userId = phoneId.substring("store_".length());
                StoreUser storeUser = storeUserMapper.selectOne(new LambdaQueryWrapper<StoreUser>().eq(StoreUser::getPhone,userId));
                if(storeUser!=null){
                    LambdaQueryWrapper<LifeUserViolation> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.eq(LifeUserViolation::getReportingUserId,storeUser.getId());
                    lambdaQueryWrapper.eq(LifeUserViolation::getReportingUserType,1);
                    lambdaQueryWrapper.ne(LifeUserViolation::getProcessingStatus,2);
                    lifeUserViolations = lifeUserViolationMapper.selectList(lambdaQueryWrapper);
                }
            }else if(phoneId!=null && !phoneId.equals("") && phoneId.startsWith("user_")){
                userId = phoneId.substring("user_".length());
                LifeUser lifeUser = lifeUserMapper.selectOne(new LambdaQueryWrapper<LifeUser>().eq(LifeUser::getUserPhone,userId));
                if(lifeUser!=null){
                    LambdaQueryWrapper<LifeUserViolation> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.eq(LifeUserViolation::getReportingUserId,lifeUser.getId());
                    lambdaQueryWrapper.eq(LifeUserViolation::getReportingUserType,2);
                    lambdaQueryWrapper.ne(LifeUserViolation::getProcessingStatus,2);
                    lifeUserViolations = lifeUserViolationMapper.selectList(lambdaQueryWrapper);
                }
            }
        }

        List<Integer> businessIds = lifeUserViolations.stream()
                .filter(Objects::nonNull)
                .map(LifeUserViolation::getBusinessId)
                .filter(id -> id != null && !id.toString().isEmpty())
                .collect(Collectors.toList());
        if(businessIds!=null && businessIds.size()>0){
            queryWrapper.notIn("a.id",businessIds);
        }

        //先查询父级评论
        queryWrapper.isNull(businessType != 1, "a.reply_id").eq("a.delete_flag", 0).orderByDesc("a.created_time");
        List<StoreCommentVo> storeCommentVoList = storeCommentMapper.getCommentList(queryWrapper);
        count.updateAndGet(v -> v + storeCommentVoList.size());
        //评分合计
        Double sumScore = 0.0;
        //父级评论下拼接子评论
        for (StoreCommentVo storeCommentVo : storeCommentVoList) {
            sumScore += storeCommentVo.getScore();
            QueryWrapper<StoreCommentVo> childQueryWrapper = new QueryWrapper<>();
            childQueryWrapper.eq("a.delete_flag", 0).eq("a.reply_id", storeCommentVo.getId());
            List<StoreCommentVo> childCommentList = storeCommentMapper.getCommentList(childQueryWrapper);
            count.updateAndGet(v -> v + childCommentList.size());
            //评价的评论的评论
            childCommentList.forEach(child -> {
                QueryWrapper<StoreCommentVo> childQueryCommentWrapper = new QueryWrapper<>();
                childQueryCommentWrapper
//                        .eq(null != businessId && 6 == businessId, "a.business_id", businessId)
                        .eq("a.delete_flag", 0).eq("a.reply_id", child.getId()).orderByDesc("a.created_time");
                List<StoreCommentVo> childComment2List = storeCommentMapper.getCommentList(childQueryCommentWrapper);
                count.updateAndGet(v -> v + childComment2List.size());
            });
        }
        map.put("commitCount", count.toString());
        if (sumScore == 0 || storeCommentVoList.isEmpty()) {
            map.put("score", "0");
        } else {
            BigDecimal score = new BigDecimal(sumScore).divide(new BigDecimal(storeCommentVoList.size()), 2, BigDecimal.ROUND_HALF_UP);
            map.put("score", score.toString());
        }

//        Map<String, Object> commentCountAndScore = storeCommentMapper.getCommentCountAndScore(businessId, businessType, storeId);
//        Object scoreObj = commentCountAndScore.get("score");
//        double scoreDouble = 0.0;
//        if (scoreObj != null) {
//            if (scoreObj instanceof Number) {
//                scoreDouble = ((Number) scoreObj).doubleValue();
//            } else if (scoreObj instanceof String) {
//                scoreDouble = Double.parseDouble((String) scoreObj);
//            }
//        }
//        if (scoreDouble == 0) {
//            map.put("score", "0");
//        } else {
//            BigDecimal scoreBigDecimal = new BigDecimal(String.valueOf(scoreDouble)).divide(new BigDecimal(commentCountAndScore.get("rootCount").toString()), 2, BigDecimal.ROUND_HALF_UP);
//            map.put("score", scoreBigDecimal.toString());
//        }
//        map.put("commitCount", commentCountAndScore.get("count").toString());
        return map;
    }

    /**
     * 评论
     *
     * @param multipartRequest 文件
     * @param businessId       业务id
     * @param businessType     业务类型(1:订单评论, 2:动态社区评论, 3:活动评论,4:店铺打卡评论)
     * @param storeId          门店id
     * @param userId           用户id
     * @param replyId          回复id
     * @param commentContent   评价内容
     * @return 0:成功, 1:失败, 2:文本内容异常, 3:图片内容异常
     */
    @Override
    public Integer userComment(MultipartRequest multipartRequest, Integer businessId, Integer businessType, Integer storeId, Integer userId, Integer replyId, String commentContent) {
        try {
            Map<String, String> checkText = TextCheckUtil.check(commentContent);
            if (null == checkText || checkText.get("result").equals("1")) {
                return 2;
            }
            StoreComment storeComment = new StoreComment();
            storeComment.setStoreId(storeId);
            storeComment.setUserId(userId);
            storeComment.setCommentContent(commentContent);
            storeComment.setReplyId(replyId);
            storeComment.setBusinessId(businessId);
            storeComment.setBusinessType(businessType);
            List<String> fileNameSet = new ArrayList<>(multipartRequest.getMultiFileMap().keySet());
            if (!fileNameSet.isEmpty()) {
                StringBuilder imgId = new StringBuilder();
                for (int i = 0; i < fileNameSet.size(); i++) {
                    MultipartFile multipartFile = multipartRequest.getFileMap().get(fileNameSet.get(i));
                    if (null != multipartFile) {
                        byte[] fileByte;
                        try {
                            fileByte = multipartFile.getBytes();
                        } catch (IOException e) {
                            return 1;
                        }
                        String base64 = Base64.getEncoder().encodeToString(fileByte);
                        Map<String, String> checkImage = ImageCheckUtil.check(base64, 2);
                        if (checkImage != null && checkImage.get("result").equals("1")) {
                            return 3;
                        }
                        StoreImg storeImg = new StoreImg();
                        storeImg.setStoreId(storeComment.getStoreId());
                        storeImg.setImgType(8);
                        storeImg.setImgSort(i + 1);
                        storeImg.setImgUrl(fileUploadUtil.uploadOneFile(multipartFile));
                        storeImgMapper.insert(storeImg);
                        imgId.append(storeImg.getId()).append(",");
                    }
                }
                if (!imgId.toString().isEmpty()) {
                    storeComment.setImgId(imgId.substring(0, imgId.length() - 1));
                }
            }
            storeComment.setCreatedUserId(storeComment.getUserId());
            return this.save(storeComment) ? 0 : 1;
        } catch (Exception e) {
            log.error("StoreCommentService.userComment ERROR Msg={}", e.getMessage());
            return 1;
        }

    }

    /**
     * 新增或修改评论/评价
     *
     * @param multipartRequest 文件
     * @param id               主键
     * @param businessId       业务id
     * @param businessType     业务类型(1:订单评论, 2:动态社区评论, 3:活动评论,4:店铺打卡评论)
     * @param storeId          门店id
     * @param userId           用户id
     * @param replyId          回复id
     * @param commentContent   评价内容
     * @param score            评分
     * @param otherScore       其他评分
     * @param isAnonymous      是否匿名(0:否(默认), 1:是)
     * @param evaluationTags   评价标签
     * @param phoneId          用户id
     * @return 0:成功, 1:失败, 2:文本内容异常, 3:图片内容异常
     */
    @Override
    public Integer addComment(MultipartRequest multipartRequest, Integer id, Integer businessId, Integer businessType, Integer storeId, Integer userId, Integer replyId, String commentContent, Double score, String otherScore, Integer isAnonymous, String evaluationTags, String phoneId) {
        try {
            List<String> servicesList = Lists.newArrayList();
            servicesList.add(TextReviewServiceEnum.COMMENT_DETECTION_PRO.getService());
            servicesList.add(TextReviewServiceEnum.LLM_QUERY_MODERATION.getService());
            TextModerationResultVO textCheckResult = textModerationUtil.invokeFunction(commentContent, servicesList);
            if ("high".equals(textCheckResult.getRiskLevel())) {
                return 2;
            }

            /*Map<String, String> checkText = TextCheckUtil.check(commentContent);
            if (null == checkText || checkText.get("result").equals("1")) {
                return 2;
            }*/
            StoreComment storeComment = new StoreComment();
            storeComment.setId(id);
            storeComment.setStoreId(storeId);
            storeComment.setUserId(userId);
            storeComment.setCommentContent(commentContent);
            storeComment.setReplyId(replyId);
            storeComment.setBusinessId(businessId);
            storeComment.setBusinessType(businessType);
            storeComment.setScore(score);

            if (StringUtils.isNotEmpty(otherScore)) {
                List<LifeCouponVo> lifeCouponVos = JSONArray.parseArray(otherScore, LifeCouponVo.class);
                lifeCouponVos.stream().filter(i -> "口味".equals(i.getName())).findFirst().ifPresent(item -> storeComment.setTasteScore(Double.valueOf(item.getRateScore())));
                lifeCouponVos.stream().filter(i -> "环境".equals(i.getName())).findFirst().ifPresent(item -> storeComment.setEnScore(Double.valueOf(item.getRateScore())));
                lifeCouponVos.stream().filter(i -> "服务".equals(i.getName())).findFirst().ifPresent(item -> storeComment.setServiceScore(Double.valueOf(item.getRateScore())));
            }
            storeComment.setOtherScore(otherScore);
            storeComment.setIsAnonymous(isAnonymous);
            storeComment.setEvaluationTags(evaluationTags);
            storeComment.setPhoneId(phoneId);
            List<String> fileNameSet = new ArrayList<>(multipartRequest.getMultiFileMap().keySet());
            if (!fileNameSet.isEmpty() && storeId != null) {
                StringBuilder imgId = new StringBuilder();
                for (int i = 0; i < fileNameSet.size(); i++) {
                    MultipartFile multipartFile = multipartRequest.getFileMap().get(fileNameSet.get(i));
                   //b
                    System.out.println(multipartFile.getSize());
                    //kb
                    System.out.println(multipartFile.getSize() / 1024);
                    if (null != multipartFile && multipartFile.getSize() / 1024 > 0) {
                        byte[] fileByte;
                        try {
                            fileByte = multipartFile.getBytes();
                        } catch (IOException e) {
                            return 1;
                        }
                        String base64 = Base64.getEncoder().encodeToString(fileByte);
                        Map<String, String> checkImage = ImageCheckUtil.check(base64, 2);
                        if (checkImage != null && checkImage.get("result").equals("1")) {
                            return 3;
                        }
                        StoreImg storeImg = new StoreImg();
                        storeImg.setStoreId(storeComment.getStoreId());
                        storeImg.setImgType(8);
                        storeImg.setImgSort(i + 1);
                        storeImg.setImgUrl(fileUploadUtil.uploadOneFile(multipartFile));
                        storeImgMapper.insert(storeImg);
                        imgId.append(storeImg.getId()).append(",");
                    }
                }
                if (!imgId.toString().isEmpty()) {
                    storeComment.setImgId(imgId.substring(0, imgId.length() - 1));
                }
            }
            storeComment.setCreatedUserId(storeComment.getUserId());

            int i = this.save(storeComment) ? 0 : 1;
            Map<String, String> commentCountAndScore = storeCommentMapper.getCommentCountAndScoreInfo(storeId);
            String totalStr = String.valueOf(commentCountAndScore.get("total"));
            double total = StringUtils.isNotEmpty(totalStr) ? Double.parseDouble(totalStr) : 0;
            double scoreAvg = StringUtils.isNotEmpty(commentCountAndScore.get("score")) ? Double.parseDouble(commentCountAndScore.get("score")) / total : 0;
            double tasteScore = StringUtils.isNotEmpty(commentCountAndScore.get("tasteScore")) ? Double.parseDouble(commentCountAndScore.get("tasteScore")) / total : 0;
            double enScore = StringUtils.isNotEmpty(commentCountAndScore.get("enScore")) ? Double.parseDouble(commentCountAndScore.get("enScore")) / total : 0;
            double serviceScore = StringUtils.isNotEmpty(commentCountAndScore.get("serviceScore")) ? Double.parseDouble(commentCountAndScore.get("serviceScore")) / total : 0;
            StoreInfo storeInfo = new StoreInfo();
            storeInfo.setId(storeId);
            storeInfo.setScoreAvg(scoreAvg);
            storeInfo.setTasteScore(tasteScore);
            storeInfo.setEnScore(enScore);
            storeInfo.setServiceScore(serviceScore);
            storeInfoMapper.updateById(storeInfo);

            return i;
        } catch (Exception e) {
            log.error("StoreCommentService.userComment ERROR Msg={}", e.getMessage());
            return 1;
        }

    }

    /**
     * 回复率, 评价比例
     *
     * @param storeId 门店id
     * @return StoreCommitPercentVo
     */
    @Override
    public StoreCommitPercentVo getCommitPercent(Integer storeId) {
        StoreCommitPercentVo storeCommit = storeCommentMapper.getCommentByStoreId(storeId);
        if (storeCommit != null) {
            if ("0".equals(storeCommit.getAllCommentCount())) {
                storeCommit.setHighPercent("0%");
                storeCommit.setMidPercent("0%");
                storeCommit.setLowPercent("0%");
            } else {
                double highPercentDouble = Double.parseDouble(storeCommit.getHighCommentCount()) / Double.parseDouble(storeCommit.getRootCommentCount());
                BigDecimal highPercent = BigDecimal.valueOf(highPercentDouble).multiply(BigDecimal.valueOf(100)).setScale(2, RoundingMode.HALF_UP);
                //好评
                storeCommit.setHighPercent(highPercent + "%");
                double midPercentDouble = Double.parseDouble(storeCommit.getMidCommentCount()) / Double.parseDouble(storeCommit.getRootCommentCount());
                BigDecimal midPercent = BigDecimal.valueOf(midPercentDouble).multiply(BigDecimal.valueOf(100)).setScale(2, RoundingMode.HALF_UP);
                //中评
                storeCommit.setMidPercent(midPercent + "%");
                double lowPercentDouble = Double.parseDouble(storeCommit.getLowCommentCount()) / Double.parseDouble(storeCommit.getRootCommentCount());
                BigDecimal lowPercent = BigDecimal.valueOf(lowPercentDouble).multiply(BigDecimal.valueOf(100)).setScale(2, RoundingMode.HALF_UP);
                //差评
                storeCommit.setLowPercent(lowPercent + "%");
            }
            if ("0".equals(storeCommit.getRootCommentCount())) {
                storeCommit.setReplyPercent("0%");
            } else {
                double replyPercentDouble = Double.parseDouble(storeCommit.getCommentCount()) / Double.parseDouble(storeCommit.getRootCommentCount());
                BigDecimal replyPercent = BigDecimal.valueOf(replyPercentDouble).multiply(BigDecimal.valueOf(100)).setScale(2, RoundingMode.HALF_UP);
                //回复率
                storeCommit.setReplyPercent(replyPercent + "%");
            }
            return storeCommit;
        }
        return null;
    }

    @Override
    public IPage<LifeUserOrderCommentVo> getCommentOrderPage(Integer pageNum, Integer pageSize, Integer type, String userId) {
        IPage<LifeUserOrderCommentVo> lifeUserOrderCommentVoIPage = new Page<>(pageNum, pageSize);
        IPage<LifeUserOrderCommentVo> commentOrderPage;
        //1.未评价 2.已评价
        if (type == 1) {
            commentOrderPage = storeCommentMapper.getCommentOrderWPJPage(lifeUserOrderCommentVoIPage, userId);
        } else {
            commentOrderPage = storeCommentMapper.getCommentOrderYPJPage(lifeUserOrderCommentVoIPage, userId);
        }
        List<String> collect = commentOrderPage.getRecords().stream().map(LifeUserOrderCommentVo::getGroupBuyImgId).collect(Collectors.toList());

        if (ObjectUtils.isNotEmpty(collect)) {
            List<StoreImg> storeImgList = storeImgMapper.selectList(new QueryWrapper<StoreImg>().in("id", collect));
            commentOrderPage.getRecords().forEach(i -> i.setGroupBuyImgUrl(storeImgList.stream().filter(j -> j.getId().toString().equals(i.getGroupBuyImgId())).findFirst().map(StoreImg::getImgUrl).orElse(null)));
        }
        return commentOrderPage;
    }
}
