package com.liquidnet.service.chime.utils;

import com.liquidnet.common.cache.redis.util.RedisUtil;
import com.liquidnet.commons.lang.util.BeanUtil;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.chime.constant.ChimeConstant;
import com.liquidnet.service.chime.dto.ChimeJoinUserCountDto;
import com.liquidnet.service.chime.dto.ChimeUserInfoDto;
import com.liquidnet.service.chime.dto.ChimeUserTagDto;
import com.liquidnet.service.chime.vo.mongo.ChimeUserInfoVo;
import com.liquidnet.service.chime.vo.mongo.ChimeUserTagsMappingVo;
import com.mongodb.client.result.UpdateResult;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Slf4j
@Component
public class DataUtils {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 注册社交用户
     * @param chimeUserInfoDto
     */
    public void createChimeUser(ChimeUserInfoDto chimeUserInfoDto){
        ChimeUserInfoVo chimeUserInfoVo = ChimeUserInfoVo.getNew();
        BeanUtil.copy(chimeUserInfoDto,chimeUserInfoVo);
        chimeUserInfoVo.setMid(ChimeConstant.getNewUserId());
        chimeUserInfoVo.setIsOnLine(true);
        mongoTemplate.save(chimeUserInfoVo,ChimeUserInfoVo.class.getSimpleName());
    }

    /**
     * 注册社交用户
     */
    public void createBatchChimeUser(List<ChimeUserInfoVo> chimeUserInfoVoList){
        mongoTemplate.insert(chimeUserInfoVoList,ChimeUserInfoVo.class.getSimpleName());
    }

    /**
     * 修改社交用户
     * @param chimeUserInfoVo
     */
    public void updateChimeUser(ChimeUserInfoVo chimeUserInfoVo) {
        Query query = Query.query(Criteria.where("userId").is(chimeUserInfoVo.getUserId()));
//        Update update = Update.fromDocument(Document.parse(JsonUtils.toJson(chimeUserInfoVo)));
        Update update = Update.fromDocument(Document.parse(JsonUtils.toJson(chimeUserInfoVo)));
        update.set("sex", chimeUserInfoVo.getSex());
        update.set("userTagsVoList", chimeUserInfoVo.getUserTagsVoList());
        UpdateResult result = mongoTemplate.updateFirst(query,update,ChimeUserInfoVo.class,ChimeUserInfoVo.class.getSimpleName());
        log.info("updateChimeUser result:{}",result.toString());
    }

    /**
     * 创建用户标签
     * @param chimeUserTagsMappingVoList
     */
    public void createUserTagMapping(List<ChimeUserTagsMappingVo> chimeUserTagsMappingVoList){
        mongoTemplate.insert(chimeUserTagsMappingVoList,ChimeUserTagsMappingVo.class.getSimpleName());
    }

    /**
     * 修改用户标签
     * @param userId
     * @param chimeUserTagsMappingVoList
     * @return
     */
    public boolean updateUserTagMapping(String userId,List<ChimeUserTagsMappingVo> chimeUserTagsMappingVoList){

        Query query = Query.query(Criteria.where("userId").is(userId));
        //  根据条件删除（可删除多条）
        mongoTemplate.remove(query,ChimeUserTagsMappingVo.class.getSimpleName());
        Collection rsList = mongoTemplate.insert(chimeUserTagsMappingVoList,ChimeUserTagsMappingVo.class.getSimpleName());
        return rsList.size()>0;
    }

    /**
     * 获取单个用户信息
     * @param userId
     * @return
     */
    public ChimeUserInfoVo getUserByUserId(String userId){
        Query query = Query.query(Criteria.where("userId").is(userId));
        ChimeUserInfoVo chimeUserInfoVo = mongoTemplate.findOne(query,ChimeUserInfoVo.class,ChimeUserInfoVo.class.getSimpleName());
        return chimeUserInfoVo;
    }

    /**
     * 获取用户标签
     * @param userId
     * @return
     */
    public List<ChimeUserTagDto> getUserTagList(String userId){
        Query query= Query.query(Criteria.where("userId").is(userId));
        return mongoTemplate.find(query, ChimeUserTagDto.class,ChimeUserTagsMappingVo.class.getSimpleName());
    }

    /**
     * 根据演出idList获取在场人数和默认头像图片(最多获取5个url)
     * @param performanceIdList
     * @return
     */
    public List<ChimeJoinUserCountDto> getJoinUserCountList(List<String> performanceIdList){
        Aggregation agg = Aggregation.newAggregation(
                // 挑选所需的字段，类似select *，*所代表的字段内容
                Aggregation.project("joinPerformanceId","avatar"),
                // sql where 语句筛选符合条件的记录
                Aggregation.match(Criteria.where("joinPerformanceId").in(performanceIdList)),
                // 分组条件，设置分组字段
                Aggregation.group("joinPerformanceId")
                        .first("joinPerformanceId").as("joinPerformanceId")
                        .addToSet("avatar").as("avatarArray")
                        .count().as("totalCount"),
                // 排序（根据某字段排序 倒序）
//                Aggregation.sort(Sort.Direction.DESC,"startDate"),
                // 重新挑选字段
                Aggregation.project("joinPerformanceId","totalCount","avatarArray")
        );

        AggregationResults<Document> results = mongoTemplate.aggregate(agg, ChimeUserInfoVo.class.getSimpleName(), Document.class);
        List<Document> mappedResultsList= results.getMappedResults();

        //拼装返回结果
        List<ChimeJoinUserCountDto> joinUserCountDtoList = new ArrayList<>();
        mappedResultsList.stream().forEach(document -> {
            ChimeJoinUserCountDto dto = ChimeJoinUserCountDto.getNew();
            dto.setPerformancesId(document.getString("joinPerformanceId"));
            dto.setCount(document.getInteger("totalCount"));
            List<String> ppl2 = document.getList("avatarArray",String.class);
            dto.setAvatarImgList(ppl2);
            joinUserCountDtoList.add(dto);
        });
        log.debug("排序后的code列表2：[{}]",results);
        return joinUserCountDtoList;
    }

    /**
     * 根据演出id更新在场演出id
     * @param performanceId
     * @return
     */
    public boolean updateUserIsOnline(String performanceId){
        Query query = Query.query(Criteria.where("joinPerformanceId").is(performanceId));
        Update update = Update.update("joinPerformanceId","-1");
        UpdateResult updateResult = mongoTemplate.updateMulti(query,update,ChimeUserInfoVo.class,ChimeUserInfoVo.class.getSimpleName());
        return updateResult.getModifiedCount()>0;
    }
}
