package com.yiqi.core.service.impl;

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

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yiqi.common.enums.OrderGoodsStatusType;
import com.yiqi.common.exception.ServiceException;
import com.yiqi.app.domain.AppUser;
import com.yiqi.app.service.IAppUserService;
import com.yiqi.common.enums.DeleteStatus;
import com.yiqi.common.enums.StatusType;
import com.yiqi.common.enums.SysBoolType;
import com.yiqi.common.utils.DateUtils;
import com.yiqi.core.domain.*;
import com.yiqi.core.domain.dto.GoodsCommentQueryDTO;
import com.yiqi.core.domain.dto.weapp.WeAppGoodsCommentQueryDTO;
import com.yiqi.core.domain.vo.GoodsCommentQueryVO;
import com.yiqi.core.domain.vo.GoodsSkuInfoByCommentVO;
import com.yiqi.core.domain.vo.weapp.WeAppGoodsCommentQueryVO;
import com.yiqi.core.domain.vo.weapp.WeAppGoodsCommentVO;
import com.yiqi.core.service.*;
import com.yiqi.order.domain.OrderGoods;
import com.yiqi.order.domain.OrderGoodsSku;
import com.yiqi.order.service.IOrderGoodsService;
import com.yiqi.order.service.IOrderGoodsSkuService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yiqi.core.mapper.GoodsCommentMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 商品评论Service业务层处理
 *
 * @author ruoyi
 * @date 2023-12-19
 */
@Service
public class GoodsCommentServiceImpl extends ServiceImpl<GoodsCommentMapper, GoodsComment> implements IGoodsCommentService {

    @Autowired
    private IOrderGoodsSkuService orderGoodsSkuService;

    @Autowired
    private IGoodsCommentRelationService goodsCommentRelationService;

    @Autowired
    private IAppUserService appUserService;

    @Autowired
    private IGoodsInfoService goodsInfoService;

    @Autowired
    private IGoodsSkuSpecService goodsSkuSpecService;

    @Autowired
    private IOrderGoodsService orderGoodsService;

    /**
     * 查询商品评论
     *
     * @param id 商品评论主键
     * @return 商品评论
     */
    @Override
    public GoodsComment selectGoodsCommentById(Long id) {
        return baseMapper.selectGoodsCommentById(id);
    }

    /**
     * 查询商品评论列表
     *
     * @param goodsCommentQueryDTO 商品评论
     * @return 商品评论
     */
    @Override
    public List<GoodsCommentQueryVO> selectGoodsCommentList(GoodsCommentQueryDTO goodsCommentQueryDTO) {
        return baseMapper.selectGoodsCommentList(goodsCommentQueryDTO);
    }

    @Override
    public Integer countNumberByGoodsCommentList(GoodsCommentQueryDTO goodsCommentQueryDTO) {
        return baseMapper.countNumberByGoodsCommentList(goodsCommentQueryDTO);
    }

    /**
     * 新增商品评论
     *
     * @param goodsComment 商品评论
     * @return 结果
     */
    @Override
    public int insertGoodsComment(GoodsComment goodsComment, Long goodsId, Long goodsSkuId) {

        // app评论
        if (SysBoolType.NO.getCode().equals(goodsComment.getIsVirtual())) {
            List<OrderGoodsSku> list = orderGoodsSkuService.list(new QueryWrapper<OrderGoodsSku>().lambda()
                    .eq(OrderGoodsSku::getOrderId, goodsComment.getOrderId()));
            if (CollUtil.isEmpty(list)) {
                throw new ServiceException("未查询到该订单的商品物料信息, orderId : {} " + goodsComment.getOrderId());
            }
            Set<Long> keySetGoodsId = list.stream().collect(Collectors.groupingBy(OrderGoodsSku::getGoodsId)).keySet();
            List<GoodsInfo> goodsInfoList = goodsInfoService.list(new QueryWrapper<GoodsInfo>().lambda().in(GoodsInfo::getId, keySetGoodsId));
            Map<Long, String> goodsInfoMap = goodsInfoList.stream().collect(Collectors.toMap(GoodsInfo::getId, GoodsInfo::getGoodsName));
            GoodsInfo goodsInfo = goodsInfoList.get(0);
            if(goodsInfoList.size()==1){
                goodsComment.setGoodsType(goodsInfo.getGoodsType());
                goodsComment.setGoodsId(goodsInfo.getId());
            }else{
                goodsComment.setGoodsType(goodsInfo.getGoodsType());
            }
            this.save(goodsComment);
            List<GoodsCommentRelation> relationList = new ArrayList<>();
            list.forEach(sku -> {
                GoodsCommentRelation goodsCommentRelation = new GoodsCommentRelation();
                goodsCommentRelation.setGoodsCommentId(goodsComment.getId());
                goodsCommentRelation.setGoodsSkuId(sku.getSkuId());
                goodsCommentRelation.setSkuName(sku.getSkuName());
                goodsCommentRelation.setGoodsName(goodsInfoMap.get(sku.getGoodsId()) == null ? "" : goodsInfoMap.get(sku.getGoodsId()));
                goodsCommentRelation.setOrderId(sku.getOrderId());
                goodsCommentRelation.setGoodsId(sku.getGoodsId());
                goodsCommentRelation.setBuyNum(sku.getBuyNum());
                goodsCommentRelation.setCreateTime(DateUtils.getNowDate());
                relationList.add(goodsCommentRelation);
            });
            goodsCommentRelationService.saveBatch(relationList);
            if (goodsComment.getOrderId() != null) {
                OrderGoods updateEntity = new OrderGoods();
                updateEntity.setOrderStatus(OrderGoodsStatusType.HAS_COMMENT.getCode());
// 使用 LambdaUpdateWrapper 构建更新条件
                LambdaUpdateWrapper<OrderGoods> updateWrapper = new LambdaUpdateWrapper<OrderGoods>()
                        .eq(OrderGoods::getId, goodsComment.getOrderId());
// 执行更新操作
                orderGoodsService.update(updateEntity, updateWrapper);
            }
        }
        // 总部虚拟评论
        if (SysBoolType.YES.getCode().equals(goodsComment.getIsVirtual())) {
            this.save(goodsComment);
            GoodsCommentRelation goodsCommentRelation = new GoodsCommentRelation();
            // 按选择的商品id 查商品信息
            GoodsInfo goodsInfo = goodsInfoService.getOne(new QueryWrapper<GoodsInfo>().lambda().eq(GoodsInfo::getId, goodsId), Boolean.FALSE);
            if (goodsInfo == null) {
                throw new ServiceException("商品信息不存在");
            }
            // 按选择的商品物料id 查商品物料信息
            List<GoodsSkuSpec> skuSpecList = goodsSkuSpecService.list(new QueryWrapper<GoodsSkuSpec>().lambda()
                    .eq(GoodsSkuSpec::getGoodsSkuId, goodsSkuId)
                    .eq(GoodsSkuSpec::getDelFlag, DeleteStatus.OK.getCode()));
            // 设置物料名称
            if (skuSpecList.size() > 0) {
                String name = "";
                for (GoodsSkuSpec goodsSkuSpec : skuSpecList) {
                    name = name.equals("") ? name + goodsSkuSpec.getSpecName() + ":" + goodsSkuSpec.getSpecValue() :
                            name + "|" + goodsSkuSpec.getSpecName() + ":" + goodsSkuSpec.getSpecValue();
                }
                goodsCommentRelation.setSkuName(name);
            }
            // 设置商品名称
            goodsCommentRelation.setGoodsName(goodsInfo.getGoodsName());
            goodsCommentRelation.setCreateTime(DateUtils.getNowDate());
            goodsCommentRelation.setGoodsCommentId(goodsComment.getId());
            goodsCommentRelation.setGoodsSkuId(goodsSkuId);
            goodsCommentRelation.setGoodsId(goodsId);
            goodsCommentRelation.setBuyNum(1);
            goodsCommentRelationService.save(goodsCommentRelation);
        }
        return 1;
    }

    @Override
    public WeAppGoodsCommentQueryVO findPage(WeAppGoodsCommentQueryDTO weAppGoodsCommentQueryDTO) {
        WeAppGoodsCommentQueryVO weAppGoodsCommentQueryVO = new WeAppGoodsCommentQueryVO();
        List<GoodsCommentRelation> relationList = goodsCommentRelationService.list(new QueryWrapper<GoodsCommentRelation>().lambda()
                .eq(GoodsCommentRelation::getGoodsId, weAppGoodsCommentQueryDTO.getGoodsId())
                .orderByDesc(GoodsCommentRelation::getCreateTime)
                .last("limit " + weAppGoodsCommentQueryDTO.getStartRow() + "," + weAppGoodsCommentQueryDTO.getPageSize()));
        if (CollUtil.isEmpty(relationList)) {
            weAppGoodsCommentQueryVO.setWeAppGoodsCommentVOS(new ArrayList<>());
            return weAppGoodsCommentQueryVO;
        }
        // 按评论id分组
        Map<Long, List<GoodsCommentRelation>> relationMap = relationList.stream().collect(Collectors.groupingBy(GoodsCommentRelation::getGoodsCommentId));

        // 通过评论id，获取评论信息
        List<GoodsComment> goodsComments = this.list(new QueryWrapper<GoodsComment>().lambda()
                .in(GoodsComment::getId, relationMap.keySet())
                .eq(GoodsComment::getIsShow, SysBoolType.YES.getCode())
                .eq(GoodsComment::getDelFlag, DeleteStatus.OK.getCode()));

        // 按客户id分组
        Map<Long, List<GoodsComment>> commentMap = goodsComments.stream().collect(Collectors.groupingBy(GoodsComment::getUserId));
        if(CollUtil.isEmpty(commentMap)){
            weAppGoodsCommentQueryVO.setWeAppGoodsCommentVOS(new ArrayList<>());
            return weAppGoodsCommentQueryVO;
        }
        // 通过客户id，获取客户信息
        List<AppUser> appUserList = appUserService.list(new QueryWrapper<AppUser>().lambda()
                .in(AppUser::getId, commentMap.keySet())
                .eq(AppUser::getStatus, StatusType.OK.getCode()));

        Map<Long, String> userMap = appUserList.stream().collect(Collectors.toMap(AppUser::getId, AppUser::getNickName));

        List<WeAppGoodsCommentVO> appGoodsCommentVOS = new ArrayList<>();
        for (GoodsComment goodsComment : goodsComments) {
            WeAppGoodsCommentVO weAppGoodsCommentVO = new WeAppGoodsCommentVO();
            BeanUtils.copyProperties(goodsComment, weAppGoodsCommentVO);
            weAppGoodsCommentVO.setSkuVOS(relationMap.get(goodsComment.getId()));
            weAppGoodsCommentVO.setNickName(userMap.get(goodsComment.getUserId()));
            weAppGoodsCommentVO.setTotalBuyNum(relationMap.get(goodsComment.getId()).stream().mapToInt(GoodsCommentRelation::getBuyNum).sum());
            appGoodsCommentVOS.add(weAppGoodsCommentVO);
        }
        weAppGoodsCommentQueryVO.setWeAppGoodsCommentVOS(appGoodsCommentVOS);
        GoodsInfo goodsInfo = goodsInfoService.getOne(new QueryWrapper<GoodsInfo>().lambda()
                .eq(GoodsInfo::getId, weAppGoodsCommentQueryDTO.getGoodsId()));
        if (goodsInfo != null) {
            weAppGoodsCommentQueryVO.setGoodComment(goodsInfo.getGoodComment());
        }
        return weAppGoodsCommentQueryVO;
    }
}
