package com.xxfc.platform.tour.biz;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
import com.github.wxiaoqi.security.admin.vo.AppUserVo;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.xxfc.platform.tour.dto.ScoreTypeDTO;
import com.xxfc.platform.tour.dto.TourUserScoreDTO;
import com.xxfc.platform.tour.dto.TourUserScoreDetailDTO;
import com.xxfc.platform.tour.dto.TourUserScoreListDTO;
import com.xxfc.platform.tour.vo.ScoreTypeVo;
import com.xxfc.platform.tour.vo.TourUserScoreVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.xxfc.platform.tour.entity.TourUserScore;
import com.xxfc.platform.tour.mapper.TourUserScoreMapper;
import com.github.wxiaoqi.security.common.biz.BaseBiz;

import javax.annotation.Resource;
import java.time.Instant;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 用户评分表
 *
 * @author libin
 * @email 18178966185@163.com
 * @date 2019-06-21 20:27:43
 */
@Service
@Slf4j
public class TourUserScoreBiz extends BaseBiz<TourUserScoreMapper,TourUserScore> {

    @Resource
    private UserFeign userFeign;

    /**
     * 根据商品id查询
     * @param goodId
     * @return
     */
    public PageDataVO<TourUserScoreVo> findTourUserScorePageByGoodId(Integer goodId, Integer pageNo, Integer pageSize) {
        PageDataVO<TourUserScoreVo> pageDataVO = new PageDataVO<>();
        //根据模型id查找
        PageDataVO<TourUserScoreListDTO> tourUserScoreDTOPageDataVO  = PageDataVO.pageInfo(pageNo,pageSize,()->mapper.findyByGoodIdAndApproved(goodId,1));
        List<TourUserScoreListDTO> dataVOData = tourUserScoreDTOPageDataVO.getData();
        if (CollectionUtils.isEmpty(dataVOData)){
            return pageDataVO;
        }
        if (log.isDebugEnabled()){
            log.debug("根据商品id查找出的评价：【{}】",dataVOData);
        }
        //设置用户信息
        List<Integer> userIds = dataVOData.stream().map(TourUserScoreListDTO::getUserId).distinct().collect(Collectors.toList());
        List<AppUserVo> appUserVos = userFeign.getByUserIds(userIds).getData();
        if (log.isDebugEnabled()){
            log.debug("根据用户ids查询出用户信息：【{}】",appUserVos);
        }
        Map<Integer, AppUserVo> userMap = appUserVos.stream().collect(Collectors.toMap(AppUserVo::getUserid, Function.identity()));
        List<TourUserScoreVo> tourUserScoreVos = dataVOData.stream().map(vehicleUserScoreListDTO -> {
            TourUserScoreVo tourUserScoreVo = new TourUserScoreVo();
            BeanUtils.copyProperties(vehicleUserScoreListDTO, tourUserScoreVo);
            tourUserScoreVo.setUserName(userMap.get(vehicleUserScoreListDTO.getUserId()).getNickname());
            tourUserScoreVo.setHeadUrl(userMap.get(vehicleUserScoreListDTO.getUserId()).getHeadimgurl());
            return tourUserScoreVo;
        }).sorted(Comparator.comparing(TourUserScoreVo::getCrtTime).reversed()).collect(Collectors.toList());
        //组装数据
        pageDataVO.setPageNum(tourUserScoreDTOPageDataVO.getPageNum());
        pageDataVO.setPageSize(tourUserScoreDTOPageDataVO.getPageSize());
        pageDataVO.setTotalCount(tourUserScoreDTOPageDataVO.getTotalCount());
        pageDataVO.setTotalPage(tourUserScoreDTOPageDataVO.getTotalPage());
        pageDataVO.setData(tourUserScoreVos);
        return pageDataVO;
    }

    /**
     * 保存评分
     * @param tourUserScoreDTO
     * @return
     */
    public int saveTourUserScore(TourUserScoreDTO tourUserScoreDTO, AppUserDTO appUserDTO) {
        if (log.isDebugEnabled()){
            log.debug("用户:【{}】,评分的数据：【{}】",appUserDTO.getNickname(),tourUserScoreDTO);
        }
        tourUserScoreDTO.setCrtTime(Instant.now().toEpochMilli());
        List<ScoreTypeDTO> scoretype = tourUserScoreDTO.getScoretype();
        int avgScore =0;
        if (CollectionUtils.isNotEmpty(scoretype)) {
            //评分明细
            tourUserScoreDTO.setScores(JSONObject.toJSONString(scoretype));
            //计算平均分值
            double avgScored = scoretype.stream().mapToInt(ScoreTypeDTO::getScore).average().getAsDouble();
            avgScore  = Long.valueOf(Math.round(avgScored)).intValue();
            //更改商品的评分
          /*  if (0 != avgScore) {
                tourGoodBiz.updateScoreByModelIdAndavgScore(tourUserScoreDTO.getGoodId(), avgScore);
            }*/
        }
        TourUserScore trourUserScore = new TourUserScore();
        BeanUtils.copyProperties(tourUserScoreDTO,trourUserScore);
        trourUserScore.setAveScore(avgScore);
        trourUserScore.setUserId(appUserDTO.getUserid());
        trourUserScore.setUpdTime(Instant.now().toEpochMilli());
        return mapper.insertSelective(trourUserScore);
    }

    /**
     * 根据订单id查询订单评价
     * @param orderId
     * @return
     */
    public TourUserScoreVo findTourUserScoreDetailByOrderId(Integer orderId) {

        TourUserScoreVo toureUserScoreVo = new TourUserScoreVo();

        //根据订单id查询
        TourUserScoreDetailDTO tourUserScoreDetailDTO = mapper.findTourUserScoreDetailByOrderId(orderId);
        if (log.isDebugEnabled()){
            log.debug("根据订单id：【{}】查询到的订单评价内容：【{}】",orderId,tourUserScoreDetailDTO);
        }
        BeanUtils.copyProperties(tourUserScoreDetailDTO,toureUserScoreVo);
        //评分明细数据转换
        String scores = tourUserScoreDetailDTO.getScores();
        if (StringUtils.isNotEmpty(scores)){
            List<ScoreTypeVo> typeVos = JSONObject.parseObject(scores, new TypeReference<List<ScoreTypeVo>>() {});
            toureUserScoreVo.setScoreTypeVos(typeVos);
        }
        //根据用户id查询用户信息
        ObjectRestResponse<List<AppUserVo>> appuserResponse = userFeign.getByUserIds(Arrays.asList(tourUserScoreDetailDTO.getUserId()));
        if (log.isDebugEnabled()){
            log.debug("根据用户id:【{}】查询到的用户信息：【{}】",tourUserScoreDetailDTO.getUserId(),appuserResponse.getData());
        }
        AppUserVo appUserVo = appuserResponse.getData().get(0);
        toureUserScoreVo.setUserName(appUserVo.getNickname());
        toureUserScoreVo.setHeadUrl(appUserVo.getHeadimgurl());
        return toureUserScoreVo;
    }
}