package com.xxfc.platform.vehicle.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.biz.BaseBiz;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.xxfc.platform.vehicle.entity.VehicleUserScore;
import com.xxfc.platform.vehicle.mapper.VehicleUserScoreMapper;
import com.xxfc.platform.vehicle.pojo.dto.ScoreTypeDTO;
import com.xxfc.platform.vehicle.pojo.dto.VehicleUserScoreDTO;
import com.xxfc.platform.vehicle.pojo.dto.VehicleUserScoreDetailDTO;
import com.xxfc.platform.vehicle.pojo.dto.VehicleUserScoreListDTO;
import com.xxfc.platform.vehicle.pojo.vo.ScoreTypeVo;
import com.xxfc.platform.vehicle.pojo.vo.VehicleUserScoreVo;
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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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-18 15:03:58
 */
@Service
@Slf4j
public class VehicleUserScoreBiz extends BaseBiz<VehicleUserScoreMapper, VehicleUserScore> {

        @Resource
        private  UserFeign userFeign;

        @Autowired
        private  VehicleModelBiz vehicleModelBiz;
    /**
     * 根据车型id查询
     * @param modelId
     * @return
     */
    public PageDataVO<VehicleUserScoreVo> findVehicleUserScorePageByModelId(Integer modelId,Integer pageNo,Integer pageSize) {
        PageDataVO<VehicleUserScoreVo> pageDataVO = new PageDataVO<>();
        //根据模型id查找
         PageDataVO<VehicleUserScoreListDTO> vehicleUserScoreDTOPageDataVO  = PageDataVO.pageInfo(pageNo,pageSize,()->mapper.findyByModelIdAndApproved(modelId,1));
        List<VehicleUserScoreListDTO> dataVOData = vehicleUserScoreDTOPageDataVO.getData();
        if (CollectionUtils.isEmpty(dataVOData)){
            return pageDataVO;
        }
        if (log.isDebugEnabled()){
            log.debug("根据车型id查找出的评价：【{}】",dataVOData);
        }
        //设置用户信息
        List<Integer> userIds = dataVOData.stream().map(VehicleUserScoreListDTO::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<VehicleUserScoreVo> vehicleUserScoreVos = dataVOData.stream().map(vehicleUserScoreListDTO -> {
            VehicleUserScoreVo vehicleUserScoreVo = new VehicleUserScoreVo();
            BeanUtils.copyProperties(vehicleUserScoreListDTO, vehicleUserScoreVo);
            vehicleUserScoreVo.setUserName(userMap.get(vehicleUserScoreListDTO.getUserId()).getNickname());
            vehicleUserScoreVo.setHeadUrl(userMap.get(vehicleUserScoreListDTO.getUserId()).getHeadimgurl());
            return vehicleUserScoreVo;
        }).sorted(Comparator.comparing(VehicleUserScoreVo::getCrtTime).reversed()).collect(Collectors.toList());
        //组装数据
        pageDataVO.setPageNum(vehicleUserScoreDTOPageDataVO.getPageNum());
        pageDataVO.setPageSize(vehicleUserScoreDTOPageDataVO.getPageSize());
        pageDataVO.setTotalCount(vehicleUserScoreDTOPageDataVO.getTotalCount());
        pageDataVO.setTotalPage(vehicleUserScoreDTOPageDataVO.getTotalPage());
        pageDataVO.setData(vehicleUserScoreVos);
        return pageDataVO;
    }

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

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

        VehicleUserScoreVo vehicleUserScoreVo = new VehicleUserScoreVo();

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