package com.xxfc.platform.vehicle.biz;

import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
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.VehicleUserScoreListDTO;
import com.xxfc.platform.vehicle.pojo.vo.VehicleUserScoreVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.util.List;
import java.util.Map;
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> {

    /**
     * 根据车型id查询
     * @param modelId
     * @return
     */
    public PageDataVO<VehicleUserScoreVo> findVehicleUserScorePageByModelId(Integer modelId,Integer pageNo,Integer pageSize) {
        //根据模型id查找
         PageDataVO<VehicleUserScoreListDTO> vehicleUserScoreDTOPageDataVO  = PageDataVO.pageInfo(pageNo,pageSize,()->mapper.findyByModelIdAndApproved(modelId,1));
        List<Integer> userIds = vehicleUserScoreDTOPageDataVO.getData().stream().map(VehicleUserScoreListDTO::getUserId).collect(Collectors.toList());
        return null;
    }

    /**
     * 保存评分
     * @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();
        //评分明细
        vehicleUserScoreDTO.setComment(JSONObject.toJSONString(scoretype));
        //计算平均分值
        double avgScore = scoretype.stream().mapToInt(ScoreTypeDTO::getScore).average().getAsDouble();
        VehicleUserScore vehicleUserScore = new VehicleUserScore();
        BeanUtils.copyProperties(vehicleUserScoreDTO,vehicleUserScore);
        vehicleUserScore.setAveScore(Long.valueOf(Math.round(avgScore)).intValue());
        vehicleUserScore.setUserId(appUserDTO.getUserid());
        return mapper.insertSelective(vehicleUserScore);
    }
}