package com.seer.teach.mp.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seer.teach.common.PageListBean;
import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.exception.CommonException;
import com.seer.teach.common.utils.PageConverterUtils;
import com.seer.teach.mp.app.controller.req.AgentActivityParentQueryReq;
import com.seer.teach.mp.app.controller.resp.AgentActivityParentInfoResp;
import com.seer.teach.mp.app.service.IAppAgentActivityParentInfoService;
import com.seer.teach.mp.app.service.IAppAgentService;
import com.seer.teach.mp.entity.MpActivityInfoCollectionEntity;
import com.seer.teach.mp.service.IMpActivityInfoCollectionService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 * 代理商活动参与家长信息服务实现类
 * </p>
 *
 * @author Lingma
 * @since 2025-12-30
 */
@Slf4j
@Service
@AllArgsConstructor
public class AppAgentActivityParentInfoServiceImpl implements IAppAgentActivityParentInfoService {

    private final IMpActivityInfoCollectionService activityInfoCollectionService;
    private final IAppAgentService appAgentService;

    @Override
    public List<AgentActivityParentInfoResp> getParentsByActivityAndAgent(Integer activityId, Integer agentId,Integer userId) {
        var userAgentId = appAgentService.getAgentIdByUserId(userId);
        if (Objects.isNull(userAgentId)) {
            return List.of();
        }
        log.info("getParentsByActivityAndAgent userAgentId:{}", userAgentId);
        if(userAgentId.intValue() != agentId){
            throw new CommonException(ResultCodeEnum.RELATION_NOT_FOUND);
        }
        LambdaQueryWrapper<MpActivityInfoCollectionEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MpActivityInfoCollectionEntity::getActivityId, activityId)
                .eq(MpActivityInfoCollectionEntity::getAgentId, agentId);

        // 查询所有符合条件的记录
        List<MpActivityInfoCollectionEntity> entities = activityInfoCollectionService.list(queryWrapper);

        // 转换为响应对象列表
        return entities.stream()
                .map(this::convertToResp)
                .collect(Collectors.toList());
    }

    @Override
    public PageListBean<AgentActivityParentInfoResp> getParentsByActivityAndAgent(Integer userId,AgentActivityParentQueryReq queryReq) {
        var userAgentId = appAgentService.getAgentIdByUserId(userId);
        if (Objects.isNull(userAgentId)) {
            return new PageListBean<>();
        }
        log.info("userAgentId:{}", userAgentId);
        if(userAgentId.intValue() != queryReq.getAgentId()){
            throw new CommonException(ResultCodeEnum.RELATION_NOT_FOUND);
        }
        // 创建分页对象
        Page<MpActivityInfoCollectionEntity> page = new Page<>(queryReq.getPageNo(), queryReq.getPageSize());
        
        // 构建查询条件
        LambdaQueryWrapper<MpActivityInfoCollectionEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MpActivityInfoCollectionEntity::getActivityId, queryReq.getActivityId())
                .eq(MpActivityInfoCollectionEntity::getAgentId, userAgentId);

        // 执行分页查询
        Page<MpActivityInfoCollectionEntity> pageResult = activityInfoCollectionService.page(page, queryWrapper);

        // 返回分页结果
        return PageConverterUtils.convertPageList(pageResult,this::convertToResp);
    }

    @Override
    public boolean recordContactCall(Integer collectionId, Integer incrementCount,Integer userId) {
        // 查询指定的活动信息收集记录
        MpActivityInfoCollectionEntity entity = activityInfoCollectionService.getById(collectionId);
        if (entity == null) {
            throw new CommonException(ResultCodeEnum.ACTIVITY_NOT_FOUND);
        }
        // 更新联系次数
        Integer currentCount = entity.getContactCallCount();
        if (currentCount == null) {
            currentCount = 0;
        }
        Integer newCount = currentCount + incrementCount;
        entity.setContactCallCount(newCount);
        return activityInfoCollectionService.updateById(entity);
    }

    private AgentActivityParentInfoResp convertToResp(MpActivityInfoCollectionEntity entity) {
        AgentActivityParentInfoResp resp = new AgentActivityParentInfoResp();
        resp.setId(entity.getId());
        resp.setRelationId(entity.getRelationId());
        resp.setActivityId(entity.getActivityId());
        resp.setAgentId(entity.getAgentId());
        resp.setParentId(entity.getParentId());
        resp.setChildName(entity.getChildName());
        resp.setChildGender(entity.getChildGender());
        resp.setChildBirthDate(entity.getChildBirthDate());
        resp.setGrade(entity.getGrade());
        resp.setSchool(entity.getSchool());
        resp.setRegion(entity.getRegion());
        resp.setParentIdentity(entity.getParentIdentity());
        resp.setLearningSituation(entity.getLearningSituation());
        resp.setStrongSubjectIds(entity.getStrongSubjectIds());
        resp.setWeakSubjectIds(entity.getWeakSubjectIds());
        return resp;
    }
}