package com.liquidnet.service.chime.service.impl;

import com.liquidnet.commons.lang.util.BeanUtil;
import com.liquidnet.commons.lang.util.StringUtil;
import com.liquidnet.service.chime.dto.ChimeUserInfoDto;
import com.liquidnet.service.chime.dto.ChimeUserListQueryReqDto;
import com.liquidnet.service.chime.dto.ChimeUserTagDto;
import com.liquidnet.service.chime.dto.NewPageResult;
import com.liquidnet.service.chime.service.IChimePerformanceService;
import com.liquidnet.service.chime.utils.ObjectUtil;
import com.liquidnet.service.chime.vo.mongo.ChimeUserInfoVo;
import com.liquidnet.service.chime.vo.mongo.ChimeUserTagsMappingVo;
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.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.*;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

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: ChimePerformanceServiceImpl
 * @Package com.liquidnet.service.chime.service.impl
 * @Copyright: LightNet @ Copyright (c) 2021
 * @date 2021/9/9 12:04
 */
@Slf4j
@Service
public class ChimePerformanceServiceImpl implements IChimePerformanceService{
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 用户关联查询
     * @param reqDto
     * @return
     */
    @Override
    public NewPageResult<ChimeUserInfoDto> getUserListByCon(ChimeUserListQueryReqDto reqDto) {
        NewPageResult<ChimeUserInfoDto> pagedResult = ObjectUtil.getChimeUserInfoDtoPagedResult();
        try {
            int pageNum = reqDto.getPageNum() - 1;
            int pageSize = reqDto.getPageSize();
            //初始化分页
            pagedResult.setPageSize(pageSize).setCurrentPage(pageNum+1);

            // 排序 分页
            Pageable pageable = PageRequest.of(pageNum, pageSize, Sort.by(Sort.Direction.DESC, "userId"));

            //关联表
            LookupOperation lookupToLots = LookupOperation.newLookup().
                    from("ChimeUserTagsMappingVo").//关联表名 lots
                    localField("userId").//关联字段
                    foreignField("userId").//主表关联字段对应的次表字段
                    as("userTag");//查询结果集合名

            //条件
            Criteria criteria = Criteria.where("joinPerformanceId").is(reqDto.getPerformanceId());
            if(StringUtil.isNotEmpty(reqDto.getTags())){
                criteria = criteria.and("userTag.tagCode").in(Arrays.asList(reqDto.getTags().split(",")));
            }
            if(StringUtil.isNotEmpty(reqDto.getSex())){
                criteria = criteria.and("sex").is(reqDto.getSex());
            }
            AggregationOperation matchToLots = Aggregation.match(criteria);
            ProjectionOperation project  = Aggregation.project("mid","userId","sex","avatar","joinPerformanceId");
//            if (!reqDto.getPerformanceId().isEmpty()) {
//                criteria.and("title").regex(".*?\\" + reqDto.getTitle());
//            }
            project.andInclude("_id");


            //获取总数
            long startTime = System.currentTimeMillis();
            SkipOperation skipOp = Aggregation.skip(0);
            LimitOperation limitOp = Aggregation.limit(1000);
            Aggregation newAggregation = Aggregation.newAggregation(lookupToLots,matchToLots,project,skipOp,limitOp);
            List<ChimeUserInfoVo> tempChimeUserInfoVoList =  mongoTemplate.aggregate(newAggregation,ChimeUserInfoVo.class.getSimpleName(),ChimeUserInfoVo.class).getMappedResults();
            long count = tempChimeUserInfoVoList.size();
//            long count = 1000;
            long endTime = System.currentTimeMillis();
            log.info("获取总数 count：{}条",count);
            log.info("获取总数 耗时：{}ms",endTime-startTime);

            //查询分页数据
            startTime = System.currentTimeMillis();
            SkipOperation skipOperation = Aggregation.skip(pageNum*pageSize);
            LimitOperation limitOperation = Aggregation.limit(pageSize);
            Aggregation aggregation = Aggregation.newAggregation(lookupToLots,matchToLots,project,skipOperation,limitOperation);
            List<ChimeUserInfoVo> chimeUserInfoVoList =  mongoTemplate.aggregate(aggregation,ChimeUserInfoVo.class.getSimpleName(),ChimeUserInfoVo.class).getMappedResults();
            endTime = System.currentTimeMillis();
            log.info("查询分页数据 耗时：{}ms",endTime-startTime);

            //获取标签
            if(StringUtil.isNull(chimeUserInfoVoList)){
                return pagedResult;
            };

            //处理Vo
            List<ChimeUserInfoDto> dtoList = new ArrayList<>();
            startTime = System.currentTimeMillis();

            List<String> userIdList = chimeUserInfoVoList.parallelStream().map(ChimeUserInfoVo::getUserId).collect(Collectors.toList());
            Query query= Query.query(Criteria.where("userId").in(userIdList));
            List<ChimeUserTagDto> tagVoList = mongoTemplate.find(query, ChimeUserTagDto.class,ChimeUserTagsMappingVo.class.getSimpleName());

            for (ChimeUserInfoVo item : chimeUserInfoVoList) {
                ChimeUserInfoDto voData = ChimeUserInfoDto.getNew();
                BeanUtil.copy(item,voData);
                voData.setPassWord("123456");
                List<ChimeUserTagDto> tempUserTag = tagVoList.parallelStream().filter(userVo -> userVo.getUserId().equalsIgnoreCase(voData.getUserId())).collect(Collectors.toList());
                voData.setUserTags(tempUserTag);
                dtoList.add(voData);
            }
            endTime = System.currentTimeMillis();
            log.info("查询标签数据 耗时：{}ms",endTime-startTime);

            pagedResult.setList(dtoList).setTotal(count, pageSize);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pagedResult;
    }

//    @Override
//    public PagedResult<ChimeUserInfoDto> getUserListByCon(ChimeUserListQueryReqDto reqDto) {
//        PagedResult<ChimeUserInfoDto> pagedResult = ObjectUtil.getChimeUserInfoDtoPagedResult();
//        try {
//            int pageNum = reqDto.getPageNum() - 1;
//            int pageSize = reqDto.getPageSize();
//            //初始化分页
//            pagedResult.setPageSize(pageSize).setCurrentPage(pageNum+1);
//
//            // 排序 分页
//            Pageable pageable = PageRequest.of(pageNum, pageSize, Sort.by(Sort.Direction.DESC, "userId"));
//            //条件
//            Criteria criteria = Criteria.where("joinPerformanceId").is(reqDto.getPerformanceId());
////            if (!reqDto.getPerformanceId().isEmpty()) {
////                criteria.and("title").regex(".*?\\" + reqDto.getTitle());
////            }
//            Query query = Query.query(criteria);
//            // 查询总数
//            long count = mongoTemplate.count(query, ChimeUserInfoVo.class, ChimeUserInfoVo.class.getSimpleName());
//
//            query.with(pageable);
//            List<ChimeUserInfoVo> chimeUserInfoVoList = mongoTemplate.find(query, ChimeUserInfoVo.class, ChimeUserInfoVo.class.getSimpleName());
//            //处理Vo
//            List<ChimeUserInfoDto> dtoList = new ArrayList<>();
//            for (ChimeUserInfoVo item : chimeUserInfoVoList) {
//                ChimeUserInfoDto voData = ChimeUserInfoDto.getNew();
//                BeanUtil.copy(item,voData);
//                voData.setUserTags(null);
//                dtoList.add(voData);
//            }
//            pagedResult.setList(dtoList).setTotal(count, pageSize);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return pagedResult;
//    }
}
