package com.liquidnet.service.chime.utils;

import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.chime.biz.ChimeUserBiz;
import com.liquidnet.service.chime.constant.ChimeConstant;
import com.liquidnet.service.chime.dto.ChimeJoinUserCountDto;
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 ChimeUserBiz chimeUserBiz;



    /**
     * 注册社交用户
     * @param chimeUserInfoVo
     */
    public void createChimeUser(ChimeUserInfoVo 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());
        update.set("updatedAt", chimeUserInfoVo.getUpdatedAt());
        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;
    }

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

        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("userIdArray",String.class);
            dto.setAvatarImgList(chimeUserBiz.getAvatarImgList(dto.getPerformancesId()));
            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;
    }
}
