package com.younike.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.younike.common.exception.GlobalException;
import com.younike.common.utils.StringUtils;
import com.younike.common.utils.bean.BeanUtils;
import com.younike.system.domain.*;
import com.younike.system.domain.vo.GoodsCommentDimensionVo;
import com.younike.system.domain.vo.GoodsCommentVo;
import com.younike.system.enums.BeanPointCodeEnum;
import com.younike.system.mapper.*;
import com.younike.system.param.CommentQueryParam;
import com.younike.system.param.GoodsCommentParam;
import com.younike.system.service.CoinService;
import com.younike.system.service.IGoodsCommentDimensionService;
import com.younike.system.service.IGoodsCommentService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * 商品评价Service业务层处理
 *
 * @author elev
 * @date 2022-01-05
 */
@Service
public class GoodsCommentServiceImpl implements IGoodsCommentService {

    private Log log = LogFactory.getLog(this.getClass());

    @Autowired
    private GoodsCommentMapper goodsCommentMapper;
    @Autowired
    private GoodsCommentResourceMapper goodsCommentResourceMapper;
    @Autowired
    private GoodsCommentDimensionMapper goodsCommentDimensionMapper;

    @Autowired
    private IGoodsCommentDimensionService goodsCommentDimensionService;

    @Autowired
    private CoinService coinService;

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private IntegralRecordMapper integralRecordMapper;


    @Override
    public List<GoodsCommentVo> commentList(CommentQueryParam param) {
        return goodsCommentMapper.commentList(param);
    }

    /**
     * 查询商品评价
     *
     * @param commontId 商品评价主键
     * @return 商品评价
     */
    @Override
    public GoodsComment selectGoodsCommentByCommontId(Long commontId) {
        return goodsCommentMapper.selectGoodsCommentByCommontId(commontId);
    }

    /**
     * 查询商品评价列表
     *
     * @param goodsComment 商品评价
     * @return 商品评价
     */
    @Override
    public List<GoodsComment> selectGoodsCommentList(GoodsComment goodsComment) {
        return goodsCommentMapper.selectGoodsCommentList(goodsComment);
    }

    /**
     * 新增商品评价
     *
     * @param goodsComment 商品评价
     * @return 结果
     */
    @Override
    public int insertGoodsComment(GoodsComment goodsComment) {
        goodsComment.setCreateTime(LocalDateTime.now());
        return goodsCommentMapper.insertGoodsComment(goodsComment);
    }

    /**
     * 修改商品评价
     *
     * @param goodsComment 商品评价
     * @return 结果
     */
    @Override
    public int updateGoodsComment(GoodsComment goodsComment) {
        goodsComment.setUpdateTime(LocalDateTime.now());
        return goodsCommentMapper.updateGoodsComment(goodsComment);
    }

    /**
     * 批量删除商品评价
     *
     * @param commontIds 需要删除的商品评价主键
     * @return 结果
     */
    @Override
    public int deleteGoodsCommentByCommontIds(Long[] commontIds) {
        return goodsCommentMapper.deleteGoodsCommentByCommontIds(commontIds);
    }

    /**
     * 删除商品评价信息
     *
     * @param commontId 商品评价主键
     * @return 结果
     */
    @Override
    public int deleteGoodsCommentByCommontId(Long commontId)
    {
        return goodsCommentMapper.deleteGoodsCommentByCommontId(commontId);
    }

    /**
     * 查询我的商品评价列表
     * @param memberId
     * @return
     */
    @Override
    public List<GoodsCommentVo> getCommentlist(Long memberId) {
      return goodsCommentMapper.getCommentlist(memberId);
    }

    /**
     * 删除商品追评价
     * @param commontId
     * @return
     */
    @Override
    public int traceRemove(Long commontId) {
        GoodsComment goodsComment = new GoodsComment();
        goodsComment.setCommontId(commontId);
        goodsComment.setUpdateTime(LocalDateTime.now());
        return goodsCommentMapper.traceRemove(goodsComment);
    }

    /**
     * 删除商品评价
     * @param commontId
     * @return
     */
    @Override
    public int commentRemove(Long commontId) {
        GoodsComment goodsComment = new GoodsComment();
        goodsComment.setCommontId(commontId);
        goodsComment.setDelFlag("2");
        goodsComment.setUpdateTime(LocalDateTime.now());
        return goodsCommentMapper.updateGoodsComment(goodsComment);
    }

    /**
     * 根据商品id查询评价
     * @param goodsId
     * @return
     */
    @Override
    public List<GoodsCommentVo> getCommentVolist(Long goodsId) {
        return goodsCommentMapper.getCommentVolist(goodsId);
    }

    @Override
    public List<GoodsCommentVo> getCommentlistByServerId(GoodsComment goodsComment) {
        List<GoodsCommentVo> commentlist = goodsCommentMapper.getCommentlistByServerId(goodsComment);
        for(GoodsCommentVo item : commentlist){
            item.setResourceList(goodsCommentResourceMapper.selectResourcByCommentId(item.getCommontId()));
            item.setGradeList(goodsCommentDimensionMapper.selectDimensionByCommentId(item.getCommontId()));
        }
        return commentlist;
    }

    /**
     * 会员订单评价
     *
     * @param goodsCommentParam
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveMemberGoodsComment(GoodsCommentParam goodsCommentParam) {
        // 保存GoodsComment
        GoodsComment goodsComment = new GoodsComment();
        BeanUtils.copyProperties(goodsCommentParam, goodsComment);
        int goodsCommentInsertResult = goodsCommentMapper.insertGoodsComment(goodsComment);
        if (goodsCommentInsertResult <= 0) {
            throw new GlobalException("评论保存失败!");
        }

        // 保存GoodsCommentDimension
        List<GoodsCommentDimension> goodsCommentDimensionList = goodsCommentParam.getGoodsCommentDimensionList();
        if (CollectionUtils.isNotEmpty(goodsCommentDimensionList)) {
            for (GoodsCommentDimension goodsCommentDimension : goodsCommentDimensionList) {
                // 设置评论id
                goodsCommentDimension.setCommentId(String.valueOf(goodsComment.getCommontId()));
                int goodsCommentDimensionInsertResult = goodsCommentDimensionMapper.insertGoodsCommentDimension(goodsCommentDimension);
                if (goodsCommentDimensionInsertResult <= 0) {
                    throw new GlobalException("评论保存失败!");
                }
            }
        }

        // 保存GoodsCommentResource
        List<GoodsCommentResource> goodsCommentResourceList = goodsCommentParam.getGoodsCommentResourceList();
        if (CollectionUtils.isNotEmpty(goodsCommentResourceList)) {
            for (GoodsCommentResource goodsCommentResource : goodsCommentResourceList) {
                // 设置评论id
                goodsCommentResource.setCommentId(goodsComment.getCommontId());
                // 设置商户id
                goodsCommentResource.setMerchantId(goodsComment.getMerchantId());
                int goodsCommentResourceInsertResult = goodsCommentResourceMapper.insertGoodsCommentResource(goodsCommentResource);
                if (goodsCommentResourceInsertResult <= 0) {
                    throw new GlobalException("评论保存失败!");
                }
            }
        }

        // 更新订单评价状态
        Order order = new Order();
        order.setOrderId(goodsComment.getOrderId());
        // 已评价
        order.setCommentState("002");
        int updateOrderResult = orderMapper.updateOrder(order);
        if (updateOrderResult <= 0) {
            throw new GlobalException("评论保存失败!");
        }

        // 评论超过10个字或者上传图片或视频都会获得优金豆，调用远程接口增加用户优金豆数量
        BigDecimal coin = BigDecimal.ZERO;
        if (StringUtils.length(goodsComment.getContent()) > 10) {
            coin = coin.add(goodsCommentParam.getCommentCoin());
        }
        if (CollectionUtils.size(goodsCommentResourceList) > 0) {
            coin = coin.add(goodsCommentParam.getVideoImageCoin());
        }
        // 增加的优金豆数大于0
        if (coin.compareTo(BigDecimal.ZERO) > 0) {
            // 查询会员信息
            Member member = memberMapper.selectMemberByMemberId(goodsComment.getMemberId());
            if (member != null) {
                FamilyParam familyParam = new FamilyParam();
                familyParam.setNum(coin);
                familyParam.setPhone(member.getPhone());
                familyParam.setCode(BeanPointCodeEnum.ORDER_COMMENT.getCode());
                String jsonCode = coinService.increasePoints(familyParam);
                if (Objects.equals(jsonCode, "200")) {
                    // 优金豆增加成功
                    IntegralRecord integralRecord = new IntegralRecord();
                    integralRecord.setChange(coin.intValue());
                    integralRecord.setReason(BeanPointCodeEnum.ORDER_COMMENT.getCode());
                    integralRecord.setResult(1);
                    integralRecord.setMsg(JSON.toJSONString(familyParam));
                    int insertIntegralRecord = integralRecordMapper.insertIntegralRecord(integralRecord);
                    if (insertIntegralRecord <= 0) {
                        log.error("订单评价优金豆增加成功，但是优金豆积分变动记录insert失败!integralRecord=" + JSON.toJSONString(integralRecord));
                    }
                } else {
                    // 优金豆增加失败
                    IntegralRecord integralRecord = new IntegralRecord();
                    integralRecord.setChange(coin.intValue());
                    integralRecord.setReason(BeanPointCodeEnum.ORDER_COMMENT.getCode());
                    integralRecord.setResult(0);
                    integralRecord.setMsg(JSON.toJSONString(familyParam));
                    int insertIntegralRecord = integralRecordMapper.insertIntegralRecord(integralRecord);
                    if (insertIntegralRecord <= 0) {
                        log.error("订单评价优金豆增加失败，并且优金豆积分变动记录insert失败!integralRecord=" + JSON.toJSONString(integralRecord));
                    }
                }
            } else {
                log.error("订单评价增加优金豆时通过会员id未查询到会员信息!memberId=" + goodsComment.getMemberId());
            }
        }

        return goodsCommentInsertResult;
    }

    /**
     * 查询订单评价详情
     *
     * @param commontId
     * @return
     */
    @Override
    public GoodsCommentVo getMemberGoodsCommentDetail(Long commontId) {
        // 查询订单评价信息
        GoodsCommentVo goodsCommentVo = goodsCommentMapper.getMemberGoodsCommentDetail(commontId);
        if (goodsCommentVo == null) {
            return null;
        }
        // 查询评价维度信息
        List<GoodsCommentDimensionVo> goodsCommentDimensionVoList = goodsCommentDimensionMapper.selectDimensionByCommentId(commontId);
        goodsCommentVo.setGradeList(goodsCommentDimensionVoList);
        // 查询评价资源信息
        List<GoodsCommentResource> goodsCommentResourceList = goodsCommentResourceMapper.selectResourcByCommentId(commontId);
        goodsCommentVo.setResourceList(goodsCommentResourceList);

        return goodsCommentVo;
    }
}
