/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.service.impl;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.internal.LinkedTreeMap;
import com.yami.shop.bean.app.dto.ProdCommDataDto;
import com.yami.shop.bean.app.dto.ProdCommDto;
import com.yami.shop.bean.app.param.ProdCommParam;
import com.yami.shop.bean.model.Order;
import com.yami.shop.bean.model.OrderItem;
import com.yami.shop.bean.model.ProdComm;
import com.yami.shop.bean.po.CommPo;
import com.yami.shop.common.util.Arith;
import com.yami.shop.common.util.IPHelper;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.dao.OrderItemMapper;
import com.yami.shop.dao.OrderMapper;
import com.yami.shop.dao.ProdCommMapper;
import com.yami.shop.service.ProdCommService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 商品评论
 *
 * @author xwc
 * @date 2019-04-19 10:43:57
 */
@Service
@AllArgsConstructor
public class ProdCommServiceImpl extends ServiceImpl<ProdCommMapper, ProdComm> implements ProdCommService {

    private final ProdCommMapper prodCommMapper;

    private final OrderItemMapper orderItemMapper;

    private final OrderMapper orderMapper;

    @Override
    public ProdCommDataDto getProdCommDataByProdId(Long prodId) {
        ProdCommDataDto prodCommDataDto=prodCommMapper.getProdCommDataByProdId(prodId);
        //计算出好评率
        if(prodCommDataDto.getPraiseNumber() == 0||prodCommDataDto.getNumber() == 0){
            prodCommDataDto.setPositiveRating(0.0);
        }else{
//            prodCommDataDto.setPositiveRating(Arith.mul(Arith.div(prodCommDataDto.getPraiseNumber(),prodCommDataDto.getNumber()),100));
            prodCommDataDto.setPositiveRating(Arith.div(Arith.mul(prodCommDataDto.getPraiseNumber(),100),prodCommDataDto.getNumber(),2));
        }
        return prodCommDataDto;
    }

    @Override
    public IPage<ProdCommDto> getProdCommDtoPageByUserId(Page page, String userId) {
        return prodCommMapper.getProdCommDtoPageByUserId(page,userId);
    }

    @Override
    public IPage<ProdCommDto> getProdCommDtoPageByProdId(Page page, Long prodId, Integer evaluate) {

        IPage<ProdCommDto> prodCommDtos = prodCommMapper.getProdCommDtoPageByProdId(page, prodId, evaluate);
        prodCommDtos.getRecords().forEach(prodCommDto -> {
            // 匿名评价
            if (prodCommDto.getIsAnonymous() == 1) {
                prodCommDto.setNickName(null);
                prodCommDto.setPic(null);
            }
        });
        return prodCommDtos;
    }

    @Override
    public IPage<ProdComm> getProdCommPage(Page page,ProdComm prodComm,Long shopId) {
        return prodCommMapper.getProdCommPage(page,prodComm,shopId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void comm(Order order, ProdCommParam prodCommParam) {
            // 插入评论
            ProdComm prodComm = new ProdComm();
            prodComm.setProdId(0L);
            prodComm.setOrderNumber(order.getOrderNumber());
            prodComm.setUserId(order.getUserId());
            prodComm.setScore(prodCommParam.getScore());
            prodComm.setDeliveryPack(prodCommParam.getDeliveryPack());
            prodComm.setDeliverySpeed(prodCommParam.getDeliverySpeed());
            prodComm.setDeliveryService(prodCommParam.getDeliveryService());
            prodComm.setContent(prodCommParam.getContent());
            prodComm.setPics(StrUtil.isBlank(prodCommParam.getPics()) ?null:prodCommParam.getPics());
            prodComm.setIsAnonymous(prodCommParam.getIsAnonymous());
            prodComm.setRecTime(new Date());
            prodComm.setStatus(0);
            prodComm.setPostip(IPHelper.getIpAddr());
            // 好评
            if (Objects.equals(prodComm.getScore(), 5) || Objects.equals(prodComm.getScore(), 4)) {
                prodComm.setEvaluate(0);
            }
            // 中评
            else if(Objects.equals(prodComm.getScore(), 3)) {
                prodComm.setEvaluate(1);
            }
            // 差评
            else if(Objects.equals(prodComm.getScore(), 1) || Objects.equals(prodComm.getScore(), 2)) {
                prodComm.setEvaluate(2);
            }
            prodCommMapper.insert(prodComm);
        // 更新订单项评论状态
        order.setCommSts(1);
        orderMapper.updateById(order);
    }

    @Override
    public IPage<ProdComm> commList(PageParam<ProdComm> page, Long prodId,Long shopId,Integer commStatus,Long channelId) {
        IPage<ProdComm> commList = prodCommMapper.commList(page, prodId,shopId,commStatus,channelId);
        List<ProdComm> records = commList.getRecords();
        if (!records.isEmpty()){
            records.forEach(c->
                c.setOrderItems(orderItemMapper.selectList(
                        new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderNumber, c.getOrderNumber()))));
        }
        return commList;
    }

    @Override
    public Map<String, Object> commentCount(Long prodId, Long shopId,Long channelId) {
        Map<String, Object> map = new LinkedTreeMap<>();
        map.put("all", prodCommMapper.commentCount(prodId, shopId,null,channelId));
        map.put("goodCount", prodCommMapper.commentCount(prodId, shopId,0,channelId));
        map.put("middleCount", prodCommMapper.commentCount(prodId, shopId,1,channelId));
        map.put("badCount", prodCommMapper.commentCount(prodId, shopId,2,channelId));
        map.put("picCount", prodCommMapper.picCount(prodId, shopId,channelId));
        map.put("goodRate", prodCommMapper.goodRate(prodId, shopId,channelId));
        return map;
    }

    @Override
    public IPage<ProdComm> myCommList(PageParam<ProdComm> page, String userId) {
        IPage<ProdComm> commList = prodCommMapper.myCommList(page, userId);
        List<ProdComm> records = commList.getRecords();
        if (!records.isEmpty()){
            records.forEach(c->{
                List<OrderItem> orderItems = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderNumber, c.getOrderNumber()));
                c.setOrderItems(orderItems);
                c.setTotalCount(orderItems.stream().map(OrderItem::getProdCount).reduce(0, Integer::sum));
                c.setTotalPrice(orderItems.stream()
                        .mapToDouble(item -> item.getPrice() * item.getProdCount())
                        .sum());
                c.setShopName(prodCommMapper.getShopName(c.getOrderNumber()));
            });
        }
        return commList;
    }

    @Override
    public IPage<ProdComm> backendCommList(PageParam<ProdComm> page, CommPo po) {
        IPage<ProdComm> commList = prodCommMapper.backendCommList(page, po);
        List<ProdComm> records = commList.getRecords();
        if (!records.isEmpty()){
            records.forEach(c->{
                c.setOrderItems(orderItemMapper.selectList(
                        new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderNumber, c.getOrderNumber())));
                c.setShopName(prodCommMapper.getShopName(c.getOrderNumber()));
            });
        }
        return commList;
    }

    @Override
    public void backendCommAudit(Long prodCommId, Integer status) {
        ProdComm prodComm = prodCommMapper.selectById(prodCommId);
        if (prodComm!=null){
            prodComm.setStatus(status);
            prodCommMapper.updateById(prodComm);
        }
    }

    @Override
    public void reply(Long prodCommId, String replyContent) {
        ProdComm prodComm = prodCommMapper.selectById(prodCommId);
        if (prodComm!=null){
            prodComm.setReplyContent(replyContent);
            prodComm.setReplyTime(new Date());
            prodComm.setReplySts(1);
            prodCommMapper.updateById(prodComm);
        }
    }
}
