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.base.PagedResult;
import com.liquidnet.service.chime.dto.ChimeUserInfoDto;
import com.liquidnet.service.chime.dto.ChimeUserListQueryReqDto;
import com.liquidnet.service.chime.service.IChimePerformanceService;
import com.liquidnet.service.chime.utils.ObjectUtil;
import com.liquidnet.service.chime.vo.mongo.ChimeUserInfoVo;
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.stereotype.Service;

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

/**
 * @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 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());

            //关联表
            LookupOperation lookupToLots = LookupOperation.newLookup().
                    from("ChimeUserTagsMappingVo").//关联表名 lots
                    localField("userId").//关联字段
                    foreignField("userId").//主表关联字段对应的次表字段
                    as("userTag");//查询结果集合名
            if(StringUtil.isNotEmpty(reqDto.getTags())){
                criteria = criteria.and("userTag.tagCode").in(Arrays.asList(reqDto.getTags().split(",")));
            }
            AggregationOperation matchToLots = Aggregation.match(criteria);
            ProjectionOperation project  = Aggregation.project("mid","userId","sex","avatar","joinPerformanceId","userTag.tagCode","userTag.tagDesc");
//            if (!reqDto.getPerformanceId().isEmpty()) {
//                criteria.and("title").regex(".*?\\" + reqDto.getTitle());
//            }
            project.andInclude("_id");

            //获取总数
            Aggregation newAggregation = Aggregation.newAggregation(lookupToLots,matchToLots,project);
            List<ChimeUserInfoVo> tempChimeUserInfoVoList =  mongoTemplate.aggregate(newAggregation,ChimeUserInfoVo.class.getSimpleName(),ChimeUserInfoVo.class).getMappedResults();
            long count = tempChimeUserInfoVoList.size();

            //查询分页数据
            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();

            //处理Vo
            List<ChimeUserInfoDto> dtoList = new ArrayList<>();
            for (ChimeUserInfoVo item : chimeUserInfoVoList) {
                ChimeUserInfoDto voData = ChimeUserInfoDto.getNew();
                BeanUtil.copy(item,voData);
                voData.setPassWord("123456");
                voData.setUserTags(null);
                dtoList.add(voData);
            }
            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;
//    }
}
