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

import cn.hutool.core.collection.CollectionUtil;
import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.utils.AssertUtils;
import com.seer.teach.mp.app.controller.resp.AppMpAgentResp;
import com.seer.teach.mp.app.convert.AppAgentConvert;
import com.seer.teach.mp.app.service.IAppAgentService;
import com.seer.teach.mp.entity.MpAgentEmployeeRelationEntity;
import com.seer.teach.mp.entity.MpAgentEntity;
import com.seer.teach.mp.service.IMpAgentEmployeeRelationService;
import com.seer.teach.mp.service.IMpAgentService;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.springframework.stereotype.Service;

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

/**
 * App端代理商服务实现类
 */
@Service
@RequiredArgsConstructor
public class AppAgentServiceImpl implements IAppAgentService {

    private final IMpAgentService mpAgentService;
    private final IMpAgentEmployeeRelationService mpAgentEmployeeRelationService;

    @Override
    public AppMpAgentResp getAgentRespByUserId(Integer userId) {
        List<MpAgentEntity> agents = mpAgentService.getListByUserId(userId);
        AssertUtils.notEmpty(agents, ResultCodeEnum.AGENT_NOT_FOUND);
        
        MpAgentEntity agentEntity = null;
        boolean hasContactPerson = false;
        for (MpAgentEntity agent : agents) {
            if (Objects.nonNull(agent.getContactUserId()) && agent.getContactUserId().equals(userId)) {
                agentEntity = agent;
                hasContactPerson = true;
                break;
            }
        }
        // 如果没找到对应的联系人，则取第一个代理商
        if (agentEntity == null) {
            agentEntity = agents.get(0);
        }
        AppMpAgentResp appMpAgentResp = AppAgentConvert.INSTANCE.entityToResp(agentEntity);
        appMpAgentResp.setIsContactPerson(hasContactPerson);
        appMpAgentResp.setHasMultipleAgents(agents.size() > 1);
        return appMpAgentResp;
    }

    @Override
    public List<Integer> getAgentIdListByUserId(Integer userId) {
        List<MpAgentEmployeeRelationEntity> mpAgentEmployeeRelations = mpAgentEmployeeRelationService.getListByUserId(userId);
        if (CollectionUtil.isEmpty(mpAgentEmployeeRelations)) {
            List<MpAgentEntity> mpAgentEntities = mpAgentService.lambdaQuery().eq(MpAgentEntity::getContactUserId, userId).list();
            if (CollectionUtil.isEmpty(mpAgentEntities)) {
                return Collections.emptyList();
            }
            return mpAgentEntities.stream().map(MpAgentEntity::getId).collect(Collectors.toList());
        }
        return mpAgentEmployeeRelations.stream().map(MpAgentEmployeeRelationEntity::getAgentId).collect(Collectors.toList());
    }
}