package com.yonge.cooleshow.biz.dal.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.entity.LiveRoom;
import com.yonge.cooleshow.biz.dal.service.LiveRoomService;
import com.yonge.toolset.base.exception.BizException;
import com.yonge.toolset.base.page.PageInfo;
import com.yonge.toolset.mybatis.support.PageUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.beans.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import com.yonge.cooleshow.biz.dal.entity.ImLiveBroadcastRoomMember;
import com.yonge.cooleshow.biz.dal.wrapper.liveroom.ImLiveBroadcastRoomMemberWrapper;
import com.yonge.cooleshow.biz.dal.mapper.ImLiveBroadcastRoomMemberMapper;
import com.yonge.cooleshow.biz.dal.service.ImLiveBroadcastRoomMemberService;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 直播间人员关系表
 * 2023-08-15 15:50:17
 */
@Slf4j
@Service
public class ImLiveBroadcastRoomMemberServiceImpl extends ServiceImpl<ImLiveBroadcastRoomMemberMapper, ImLiveBroadcastRoomMember> implements ImLiveBroadcastRoomMemberService {

    @Autowired
    private LiveRoomService liveRoomService;

    @Autowired
    private SysUserFeignService sysUserFeignService;

	/**
     * 查询详情
     * @param id 详情ID
     * @return ImLiveBroadcastRoomMember
     */
	@Override
    public ImLiveBroadcastRoomMember detail(Long id) {
        
        return baseMapper.selectById(id);
    }
    
    /**
     * 分页查询
     * @param page IPage<ImLiveBroadcastRoomMember>
     * @param query ImLiveBroadcastRoomMemberWrapper.ImLiveBroadcastRoomMemberQuery
     * @return IPage<ImLiveBroadcastRoomMember>
     */
    @Override
    public IPage<ImLiveBroadcastRoomMember> selectPage(IPage<ImLiveBroadcastRoomMember> page, ImLiveBroadcastRoomMemberWrapper.ImLiveBroadcastRoomMemberQuery query) {
        
        return page.setRecords(baseMapper.selectPage(page, query));
    }
	
    /**
     * 添加
     * @param imLiveBroadcastRoomMember ImLiveBroadcastRoomMemberWrapper.ImLiveBroadcastRoomMember
     * @return Boolean
     */
    @Override
    public Boolean add(ImLiveBroadcastRoomMemberWrapper.ImLiveBroadcastRoomMember imLiveBroadcastRoomMember) {    	
        
        return this.save(JSON.parseObject(imLiveBroadcastRoomMember.jsonString(), ImLiveBroadcastRoomMember.class));
    }

    /**
     * 更新
     * @param imLiveBroadcastRoomMember ImLiveBroadcastRoomMemberWrapper.ImLiveBroadcastRoomMember
     * @return Boolean
     */
    @Override
    public Boolean update(ImLiveBroadcastRoomMemberWrapper.ImLiveBroadcastRoomMember imLiveBroadcastRoomMember){

        return this.updateById(JSON.parseObject(imLiveBroadcastRoomMember.jsonString(), ImLiveBroadcastRoomMember.class));       
    }

    @Override
    public PageInfo<ImLiveBroadcastRoomMemberWrapper.ImLiveBroadcastRoomMember> queryRoomMember(Map<String, Object> param) {
        Page<ImLiveBroadcastRoomMemberWrapper.ImLiveBroadcastRoomMember> pageInfo = PageUtil.getPageInfo(param);

        IPage<ImLiveBroadcastRoomMemberWrapper.ImLiveBroadcastRoomMember> page = baseMapper.queryMemberPage(pageInfo, param);

        List<ImLiveBroadcastRoomMemberWrapper.ImLiveBroadcastRoomMember> records = page.getRecords();

        if (CollectionUtils.isNotEmpty(records)) {

            // 游客默认头像

            String roomUid = MapUtils.getString(param, "roomUid", RandomStringUtils.random(5));
            // 直播间信息
            LiveRoom room =liveRoomService.lambdaQuery()
                    .eq(LiveRoom::getRoomUid, roomUid)
                    .last("LIMIT 1")
                    .one();
            if (Objects.isNull(room)) {
                throw new BizException("直播间不存在");
            }
            // 直播间主讲老师
            SysUser speaker = sysUserFeignService.queryUserById(room.getSpeakerId());


            List<Integer> studentIds = records.stream()
                    .filter(x -> StringUtils.isBlank(x.getFingerprint()))
                    .map(ImLiveBroadcastRoomMemberWrapper.ImLiveBroadcastRoomMember::getStudentId)
                    .filter(Objects::nonNull)
                    .distinct().collect(Collectors.toList());

            // 学生报名乐团
            Map<Integer, String> musicGroupMap = Maps.newConcurrentMap();
            // 学生声部名称
            Map<Integer, String> subjectMap = Maps.newConcurrentMap();

            // 直播客户端查询在线用户信息时，忽略学生相关信息查询
            if (MapUtils.getIntValue(param, "rows", 10) < 100) {

                for (List<Integer> item : Lists.partition(studentIds, 500)) {
                    // 并发查询学生信息
                    Lists.partition(item, 50).parallelStream().forEach(data -> {

                        // 学生声部名称
                        Map<Integer, String> collect = baseMapper.selectStudentSubject(studentIds).stream()
                                .filter(x -> Objects.nonNull(x) && Objects.nonNull(x.getStudentId()))
                                .collect(Collectors.toMap(ImLiveBroadcastRoomMemberWrapper.ImLiveBroadcastRoomMember::getStudentId, x -> Optional.ofNullable(x.getSubName()).orElse(""), (o, n) -> n));
                        if (MapUtils.isNotEmpty(collect)) {
                            subjectMap.putAll(collect);
                        }
                    });
                }
            }

            for (ImLiveBroadcastRoomMemberWrapper.ImLiveBroadcastRoomMember item : records) {

                if (StringUtils.isNotEmpty(item.getFingerprint())) {

                } else {
                    // 设置默认数据
                    item.setSubName(subjectMap.getOrDefault(item.getStudentId(), ""));
                    item.setRoomTitle(room.getRoomTitle());
                    item.setSpeakerName(speaker.getRealName());
                }

            }
        }

        return PageUtil.pageInfo(page);
    }
}