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

import com.liquidnet.commons.lang.util.BeanUtil;
import com.liquidnet.commons.lang.util.CurrentUtil;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.commons.lang.util.StringUtil;
import com.liquidnet.service.adam.dto.rsc.AdamChimeUinfoDto;
import com.liquidnet.service.chime.biz.ChimeUserBiz;
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 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.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.Collections;
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;

    @Autowired
    private ChimeUserBiz chimeUserBiz;
    /**
     * 用户关联查询
     * @param reqDto
     * @return
     */
    @Override
    public NewPageResult<ChimeUserInfoDto> getUserListByCon(ChimeUserListQueryReqDto reqDto) {
        log.info("getUserListByCon req:{} ", JsonUtils.toJson(reqDto));
        NewPageResult<ChimeUserInfoDto> pagedResult = ObjectUtil.getChimeUserInfoDtoPagedResult();
        try {
            int pageNum = reqDto.getPageNum() - 1;
            int pageSize = reqDto.getPageSize();
            //初始化分页
            pagedResult.setPageSize(pageSize).setCurrentPage(pageNum+1);
            //获取总数
            Criteria criteria = Criteria.where("joinPerformanceId").is(reqDto.getPerformanceId());
            //过滤本人 获取当前用户id
            String userId = CurrentUtil.getCurrentUid();
            if(StringUtil.isNotEmpty(userId)){
                criteria = criteria.and("userId").ne(userId);
            }
            //过滤标签
            if(StringUtil.isNotEmpty(reqDto.getTags())){
                criteria = criteria.and("userTagsVoList.tagCode").in(Arrays.asList(reqDto.getTags().split(",")));
            }
            //过滤性别
            if(StringUtil.isNotEmpty(reqDto.getSex())){
                criteria = criteria.and("sex").is(reqDto.getSex());
            }

            Pageable pageableCount = PageRequest.of(0, 1000); // get 5 profiles on a page
            Query queryCount = Query.query(criteria);
            queryCount.fields().include("1");
            queryCount.with(pageableCount);

            // 查询总数
            long startTime = System.currentTimeMillis();
            int count = (int) mongoTemplate.count(queryCount, ChimeUserInfoVo.class, ChimeUserInfoVo.class.getSimpleName());
            long endTime = System.currentTimeMillis();
            log.info("查询标签数据 count:{} 耗时：{}ms",count,endTime-startTime);


            // 每页五个
            Pageable pageable = PageRequest.of(pageNum, pageSize); // get 5 profiles on a page
            Query query = Query.query(criteria);
            query.with(pageable);
            query.with(Sort.by(	//根据集合中对象的某个字段排序
                    Sort.Order.desc("createdAt")
            ));

            startTime = System.currentTimeMillis();
            List<ChimeUserInfoVo> chimeUserInfoVoList = mongoTemplate.find(query, ChimeUserInfoVo.class, ChimeUserInfoVo.class.getSimpleName());
            //打乱排序
            Collections.shuffle(chimeUserInfoVoList);
            endTime = System.currentTimeMillis();
            log.info("查询标签数据 分页数据 耗时：{}ms",endTime-startTime);


            startTime = System.currentTimeMillis();
            //获取分页结果list中的userId
            List<String> userIdList = chimeUserInfoVoList.stream().map(ChimeUserInfoVo::getUserId).collect(Collectors.toList());
            //批量获取用户信息
            List<AdamChimeUinfoDto> adamChimeUinfoDtoList = chimeUserBiz.getAdamUserInfoDtoList(userIdList);
            endTime = System.currentTimeMillis();
            log.info("从adam批量获取用户信息 耗时：{}ms",endTime-startTime);

            //处理Vo
            List<ChimeUserInfoDto> dtoList = new ArrayList<>();
            startTime = System.currentTimeMillis();
            for (ChimeUserInfoVo item : chimeUserInfoVoList) {
                ChimeUserInfoDto dto = ChimeUserInfoDto.getNew();
                BeanUtil.copy(item,dto);
                dto.setPassWord("123456");
                //补充用户信息
                if(StringUtil.isNotNull(adamChimeUinfoDtoList)&&adamChimeUinfoDtoList.size()>0){
                    adamChimeUinfoDtoList.stream().forEach(adamUserDto -> {
                        if(adamUserDto.getUserId().equalsIgnoreCase(item.getUserId())){
                            dto.setNickName(adamUserDto.getNickName());
                            dto.setAvatar(adamUserDto.getAvatar());
                            dto.setUserCover(adamUserDto.getUserCover());
                            dto.setBirthday(adamUserDto.getBirthday());
                            dto.setSignature(adamUserDto.getSignature());
                            dto.setArea(adamUserDto.getArea());
                        }
                    });
                }

                //获取标签转换
                List<ChimeUserTagDto> userTagDtoList = chimeUserBiz.buildUserTagDtoListFromVo(item.getUserTagsVoList());
                dto.setUserTags(userTagDtoList);
                dtoList.add(dto);
            }
            endTime = System.currentTimeMillis();
            log.info("dto转换vo 耗时：{}ms",endTime-startTime);
            pagedResult.setList(dtoList).setTotal(count, pageSize);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pagedResult;
    }
}
