package com.ningdatech.pmapi.meeting.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ningdatech.pmapi.meeting.entity.domain.ExpertInviteRule;
import com.ningdatech.pmapi.meeting.entity.dto.AppointInviteRuleDTO;
import com.ningdatech.pmapi.meeting.entity.dto.RandomInviteRuleDTO;
import com.ningdatech.pmapi.meeting.entity.enumeration.ExpertInviteTypeEnum;
import com.ningdatech.pmapi.meeting.mapper.ExpertInviteRuleMapper;
import com.ningdatech.pmapi.meeting.service.IExpertInviteRuleService;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author WendyYang
 * @since 2022-07-26
 */
@Service
public class ExpertInviteRuleServiceImpl extends ServiceImpl<ExpertInviteRuleMapper, ExpertInviteRule> implements IExpertInviteRuleService {

    public static LambdaQueryWrapper<ExpertInviteRule> wrapperByMeetingId(Long meetingId) {
        return Wrappers.lambdaQuery(ExpertInviteRule.class).eq(ExpertInviteRule::getMeetingId, meetingId);
    }

    @Override
    public List<ExpertInviteRule> listByMeetingId(Long meetingId) {
        return list(wrapperByMeetingId(meetingId));
    }

    @Override
    public Map<Long, RandomInviteRuleDTO> randomRuleByMeetingId(Long meetingId) {
        LambdaQueryWrapper<ExpertInviteRule> query = wrapperByMeetingId(meetingId)
                .eq(ExpertInviteRule::getInviteType, ExpertInviteTypeEnum.RANDOM.getCode());
        List<ExpertInviteRule> inviteRules = baseMapper.selectList(query);
        return inviteRules.stream().collect(Collectors.toMap(ExpertInviteRule::getId,
                w -> JSONUtil.toBean(w.getInviteRule(), RandomInviteRuleDTO.class)));
    }

    @Override
    public AppointInviteRuleDTO appointRuleByMeetingId(Long meetingId) {
        LambdaQueryWrapper<ExpertInviteRule> query = wrapperByMeetingId(meetingId)
                .eq(ExpertInviteRule::getInviteType, ExpertInviteTypeEnum.APPOINT.getCode());
        ExpertInviteRule inviteRule = baseMapper.selectOne(query);
        AppointInviteRuleDTO rule = JSONUtil.toBean(inviteRule.getInviteRule(), AppointInviteRuleDTO.class);
        rule.setId(inviteRule.getId());
        return rule;
    }

}
