package com.cyksj.service.sys.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.constant.Constant;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.util.Jsons;
import com.cyksj.mapper.sys.SysConfigMapper;
import com.cyksj.model.dto.CorpFollowServiceDto;
import com.cyksj.model.entity.SysConfig;
import com.cyksj.service.sys.SysCorpServiceRelateService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

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

/**
 * 项目名: yhlxj2
 * 文件名: SysCorpServiceRelateServiceImpl
 * 创建者: JavaZou
 * 创建时间:2024/1/11 12:07
 */
@Service
@RequiredArgsConstructor
public class SysCorpServiceRelateServiceImpl implements SysCorpServiceRelateService {
	private final SysConfigMapper sysConfigMapper;


	@Override
	public List<String> getFollowIdsByRelateIds(List<Integer> indxIds) throws Exception {
		//值班客服
		Map<Integer, List<CorpFollowServiceDto>> corpYhFollowService = this.getCorpYhFollowService();
		return getFollowIdsByIndxs(indxIds, corpYhFollowService);
	}

	@Override
	public List<String> getFollowIdsByRelateIds(List<Integer> indxIds, Map<Integer, List<CorpFollowServiceDto>> corpYhFollowService) throws Exception {
		return getFollowIdsByIndxs(indxIds, corpYhFollowService);
	}


	@Override
	public Map<Integer, List<CorpFollowServiceDto>> getCorpYhFollowService() throws Exception {
		SysConfig config = sysConfigMapper.selectOne(Wrappers.lambdaQuery(SysConfig.class)
				.eq(SysConfig::getSysKey, Constant.serviceKeys.get(1)).last("limit 1"));
		if (config == null || StrUtil.isEmpty(config.getSysValue())) {
			throw BusinessRuntimeException.getInstance("未配置对应系统值班客服");
		}
		String sysValue = config.getSysValue();
		List<CorpFollowServiceDto> corpFollowServiceDtos = Jsons.parseList(sysValue, CorpFollowServiceDto.class);
		return corpFollowServiceDtos.stream().collect(Collectors.groupingBy(CorpFollowServiceDto::getIndx));
	}

	private List<String> getFollowIdsByIndxs(List<Integer> indxIds, Map<Integer, List<CorpFollowServiceDto>> corpYhFollowService) {
		List<String> followIds = new ArrayList<>();
		indxIds.forEach(indx -> {
			List<CorpFollowServiceDto> corpFollowServiceDtos = corpYhFollowService.get(indx);
			if (CollUtil.isEmpty(corpFollowServiceDtos)) {
				throw BusinessRuntimeException.getInstance("存在被删除的值班客服");
			}
			followIds.add(corpFollowServiceDtos.get(0).getFollowId());
		});
		return followIds;
	}
}
