package com.liquidnet.service.chime.biz;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.liquidnet.commons.lang.util.BeanUtil;
import com.liquidnet.commons.lang.util.CurrentUtil;
import com.liquidnet.commons.lang.util.StringUtil;
import com.liquidnet.service.adam.dto.rsc.AdamChimeUinfoDto;
import com.liquidnet.service.adam.dto.rsc.AdamChimeUinfoReq;
import com.liquidnet.service.adam.dto.vo.AdamTagVo;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.chime.dto.ChimeJoinUserCountDto;
import com.liquidnet.service.chime.dto.ChimeUserTagDto;
import com.liquidnet.service.chime.dto.PerformanceDto;
import com.liquidnet.service.chime.utils.DataUtils;
import com.liquidnet.service.chime.utils.ObjectUtil;
import com.liquidnet.service.chime.utils.RedisDataUtil;
import com.liquidnet.service.chime.vo.mongo.ChimeUserInfoVo;
import com.liquidnet.service.chime.vo.mongo.ChimeUserTagsMappingVo;
import com.liquidnet.service.feign.adam.api.FeignAdamBaseClient;
import com.liquidnet.service.feign.kylin.api.FeignKylinForChimeClient;
import com.liquidnet.service.kylin.constant.KylinPerformanceStatusEnum;
import com.liquidnet.service.kylin.dto.vo.mongo.KylinPerformanceVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author AnJiabin <anjiabin@zhengzai.tv>
 * @version V1.0
 * @Description: TODO
 * @class: ChimeUserBiz
 * @Package com.liquidnet.service.chime.biz
 * @Copyright: LightNet @ Copyright (c) 2021
 * @date 2021/9/11 16:16
 */
@Slf4j
@Component
public class ChimeUserBiz {
    @Autowired
    private DataUtils dataUtils;

    @Autowired
    private RedisDataUtil redisDataUtil;

    @Autowired
    private FeignKylinForChimeClient feignKylinForChimeClient;

    @Autowired
    private FeignAdamBaseClient feignAdamBaseClient;

    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * Json转换list
     * @param tags
     * @return
     */
    public List<ChimeUserTagsMappingVo> buildUserTagVoList(String userId,String tags){
        List<AdamTagVo> userTagVoList = ObjectUtil.getAdamTagVoArrayList();
        if(StringUtil.isNotEmpty(tags)){
            ObjectMapper mapper = new ObjectMapper();
            try {
                userTagVoList = mapper.readValue(tags, new TypeReference<List<AdamTagVo>>() {});
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                log.error("createChimeUserInfo msg:{}",e.getMessage());
                log.error("createChimeUserInfo error : ",e);
                return null;
            }
        }
        List<ChimeUserTagsMappingVo> userTagList = new ArrayList<>();
        //设置用户id
        userTagVoList.forEach(vo -> {
            ChimeUserTagsMappingVo userTagsMappingVo = ChimeUserTagsMappingVo.getNew();
            userTagsMappingVo.setTagCode(vo.getVal());
            userTagsMappingVo.setTagDesc(vo.getDesc());
            userTagList.add(userTagsMappingVo);
        });
        return userTagList;
    }

    /**
     * Json转换list
     * @param tags
     * @return
     */
//    public List<ChimeUserTagDto> buildUserTagDtoList(String userId, String tags){
//        List<AdamTagVo> userTagVoList = ObjectUtil.getAdamTagVoArrayList();
//        List<ChimeUserTagDto> userTagDtoList = ObjectUtil.getChimeUserTagDtoList();
//        if(StringUtil.isNotEmpty(tags)){
//            ObjectMapper mapper = new ObjectMapper();
//            try {
//                userTagVoList = mapper.readValue(tags, new TypeReference<List<AdamTagVo>>() {});
//            } catch (JsonProcessingException e) {
//                e.printStackTrace();
//                log.error("createChimeUserInfo msg:{}",e.getMessage());
//                log.error("createChimeUserInfo error : ",e);
//                return null;
//            }
//        }
//        //设置用户id
//        userTagVoList.forEach(vo -> {
//            ChimeUserTagDto userTagDto = ChimeUserTagDto.getNew();
//            userTagDto.setTagCode(vo.getVal());
//            userTagDto.setTagDesc(vo.getDesc());
//            userTagDtoList.add(userTagDto);
//        });
//        return userTagDtoList;
//    }

    /**
     * 演出voList转换为DtoList
     * @param performanceVoList
     * @return
     */
    public List<PerformanceDto> buildPerformanceDtoList(List<KylinPerformanceVo> performanceVoList){
        List<PerformanceDto> performanceDtoList = new ArrayList<>();
        //获取在场用户加入人数和指定头像列表
        if(StringUtil.isEmpty(performanceVoList)){
            return null;
        }
        List<String> performancesIdList = performanceVoList.stream().map(KylinPerformanceVo::getPerformancesId).collect(Collectors.toList());
        //获取在场用户人数统计
        List<ChimeJoinUserCountDto> joinUserCountDtoList =  dataUtils.getJoinUserCountList(performancesIdList);

        for(KylinPerformanceVo performanceVo:performanceVoList){
            /**
             * 过滤演出
             */
            boolean perIsAllow = redisDataUtil.isPassedByPerformanceId(performanceVo.getPerformancesId());
            boolean cityIsAllow = redisDataUtil.isPassedByCityName(performanceVo.getCityName());
            log.info("buildPerformanceDtoList perIsAllow:{} ",perIsAllow);
            log.info("buildPerformanceDtoList cityIsAllow:{} ",cityIsAllow);
            if(!perIsAllow||!cityIsAllow){
                continue;
            }

            PerformanceDto dto = PerformanceDto.getNew();
            dto.setPerformancesId(performanceVo.getPerformancesId());
            dto.setTitle(performanceVo.getTitle());
            dto.setImgPoster(performanceVo.getImgPoster());
            dto.setTimeStart(performanceVo.getTimeStart());
            dto.setTimeEnd(performanceVo.getTimeEnd());
            dto.setCityName(performanceVo.getCityName());
            dto.setFieldName(performanceVo.getFieldName());
            //初始化
            dto.setJoinUserCount(0);
            if(StringUtil.isNotEmpty(joinUserCountDtoList)){
                joinUserCountDtoList.stream().forEach(joinUserCountDto -> {
                    if(joinUserCountDto.getPerformancesId().equalsIgnoreCase(performanceVo.getPerformancesId())){
                        dto.setJoinUserCount(joinUserCountDto.getCount());
                        dto.setAvatarImgList(joinUserCountDto.getAvatarImgList());
                    }
                });
            }
//            else{
//                dto.setJoinUserCount(123);
//                List<String> imgList = new ArrayList<>();
//                imgList.add("https://img.zhengzai.tv/user/2021/07/27/a4cc2a4e6dcd44d1812dc60e079086b4.png");
//                imgList.add("https://img.zhengzai.tv/user/2021/07/27/a4cc2a4e6dcd44d1812dc60e079086b4.png");
//                imgList.add("https://img.zhengzai.tv/user/2021/07/27/a4cc2a4e6dcd44d1812dc60e079086b4.png");
//                imgList.add("https://img.zhengzai.tv/user/2021/07/27/a4cc2a4e6dcd44d1812dc60e079086b4.png");
//                imgList.add("https://img.zhengzai.tv/user/2021/07/27/a4cc2a4e6dcd44d1812dc60e079086b4.png");
//                dto.setAvatarImgList(imgList);
//            }
            performanceDtoList.add(dto);
        }
        //
        return performanceDtoList;
    }

    /**
     * 根据演出id判断是否在场
     * @param performanceId
     * @return
     */
    public boolean userIsOnline(String performanceId){
        boolean isOnline = false;
        if(StringUtil.isNotNull(performanceId)){
            if(performanceId.equalsIgnoreCase("-1")){
                isOnline = true;
            }else{
                //获取演出状态信息
                ResponseDto<KylinPerformanceVo> responseDto = feignKylinForChimeClient.getDetail(performanceId);
                if(responseDto.isSuccess()&&StringUtil.isNotNull(responseDto.getData())){
                    KylinPerformanceVo kylinPerformanceVo = responseDto.getData();
                    if(kylinPerformanceVo.getAppStatus() == KylinPerformanceStatusEnum.PERFORMANCESTATUS6.getIndex()
                            ||kylinPerformanceVo.getAppStatus() == KylinPerformanceStatusEnum.PERFORMANCESTATUS8.getIndex()
                            ||kylinPerformanceVo.getAppStatus() == KylinPerformanceStatusEnum.PERFORMANCESTATUS11.getIndex()
                            ||kylinPerformanceVo.getAppStatus() == KylinPerformanceStatusEnum.PERFORMANCESTATUS9.getIndex()){
                        isOnline = true;
                    }
                }
                //根据演出状态判断是否全部清退当前演出在场人数
                if(!isOnline){
                    //把所有当前演出在场人清退，重置为云在场
                    dataUtils.updateUserIsOnline(performanceId);
                }

            }
        }
        return isOnline;
    }

    /**
     * 根据userId获取adam用户信息
     * @param userId
     * @return
     */
    public AdamChimeUinfoDto getAdamUserInfoDto(String userId){
        List<AdamChimeUinfoDto> userInfoDtoList = this.getAdamUserInfoDtoList(Arrays.asList(new String[]{userId}));
        if(StringUtil.isNotNull(userInfoDtoList)&&userInfoDtoList.size()>0){
            return userInfoDtoList.get(0);
        }
        return null;
    }

    /**
     * 根据userIdlist获取用户列表
     * @param userIdList
     * @return
     */
    public List<AdamChimeUinfoDto> getAdamUserInfoDtoList(List<String> userIdList){
        ResponseDto<List<AdamChimeUinfoDto>> responseDto = null;
        try {
            AdamChimeUinfoReq adamChimeUinfoReq = new AdamChimeUinfoReq();
            adamChimeUinfoReq.setUidList(userIdList);
            responseDto = feignAdamBaseClient.queryForChimeUserInfo(adamChimeUinfoReq);
        } catch (Exception e) {
            log.error("feignAdamBaseClient.queryForChimeUserInfo error:{} e:{}",e.getMessage(),e);
            return null;
        }
        return responseDto.getData();
    }

    public String getSexDesc(String sexJson){
        AdamTagVo adamTagVo = AdamTagVo.getNew();
        if(StringUtil.isNotEmpty(sexJson)){
            ObjectMapper mapper = new ObjectMapper();
            try {
                adamTagVo = mapper.readValue(sexJson, new TypeReference<AdamTagVo>(){});
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                log.error("getSexDesc msg:{}",e.getMessage());
                log.error("getSexDesc error : ",e);
                return null;
            }
        }
        String rsSexDesc = "保密";
        switch (adamTagVo.getDesc()){
            case "男性":
                rsSexDesc = "男";
                break;
            case "女性":
                rsSexDesc = "女";
                break;
        }
        return rsSexDesc;
    }

    /**
     * userTagMappingVo转换为dtoList
     * @param userTagsMappingVoList
     * @return
     */
    public List<ChimeUserTagDto> buildUserTagDtoListFromVo(List<ChimeUserTagsMappingVo> userTagsMappingVoList){
        //获取标签转换
        List<ChimeUserTagDto> userTagDtoList = ObjectUtil.getChimeUserTagDtoList();
        if(StringUtil.isNotNull(userTagsMappingVoList)){
            userTagsMappingVoList.stream().forEach(chimeUserTagsMappingVo -> {
                ChimeUserTagDto userTagDto = ChimeUserTagDto.getNew();
                BeanUtil.copy(chimeUserTagsMappingVo,userTagDto);
                userTagDtoList.add(userTagDto);
            });
        }
        return userTagDtoList;
    }

    /**
     * 根据演出id获取用户信息
     * @param performanceId
     * @return
     */
    public List<String> getAvatarImgList(String performanceId){
        //根据演出id获取用户信息 只查询5条
        List<String> userIdList = new ArrayList<>();
        //获取总数
        Criteria criteria = Criteria.where("joinPerformanceId").is(performanceId);
        //过滤本人 获取当前用户id
        String userId = CurrentUtil.getCurrentUid();
        if(StringUtil.isNotEmpty(userId)){
            criteria = criteria.and("userId").ne(userId);
        }

        // 每页五个
        Pageable pageable = PageRequest.of(0, 5);
        Query query = Query.query(criteria);
        query.with(pageable);

        long startTime = System.currentTimeMillis();
        List<ChimeUserInfoVo> chimeUserInfoVoList = mongoTemplate.find(query, ChimeUserInfoVo.class, ChimeUserInfoVo.class.getSimpleName());
        long endTime = System.currentTimeMillis();
        log.info("getAvatarImgList 获取演出列表头像 耗时：{}ms",endTime-startTime);

        //根据用户id获取头像信息
        List<String> avatarImgList = new ArrayList<>();
        if(StringUtil.isNotNull(chimeUserInfoVoList)){
            userIdList = chimeUserInfoVoList.stream().map(ChimeUserInfoVo::getUserId).collect(Collectors.toList());
        }
        List<AdamChimeUinfoDto> adamChimeUinfoDtoList = this.getAdamUserInfoDtoList(userIdList);
        if(StringUtil.isNotNull(adamChimeUinfoDtoList)){
            avatarImgList = adamChimeUinfoDtoList.stream().map(AdamChimeUinfoDto::getAvatar).collect(Collectors.toList());
        }
        return avatarImgList;
    }
}
