package com.cyksj.service.corp.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.cyksj.common.util.Jsons;
import com.cyksj.mapper.corp.CorpFollowActiveCodeClickRecordMapper;
import com.cyksj.mapper.corp.CorpFollowActiveCodeMapper;
import com.cyksj.model.dto.CorpFollowActiveCodeDto;
import com.cyksj.model.entity.CorpFollowActiveCode;
import com.cyksj.model.entity.CorpFollowActiveCodeClickRecord;
import com.cyksj.redis.RedisService;
import com.cyksj.service.corp.CorpFollowActiveCodeFrontService;
import com.cyksj.service.sys.SysConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

/**
 * 项目名: yhlxj
 * 文件名: CorpFollowActiveCodeFrontServiceImpl
 * 创建者: JavaZou
 * 创建时间:2023/10/10 14:37
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class CorpFollowActiveCodeFrontServiceImpl implements CorpFollowActiveCodeFrontService {

	private final CorpFollowActiveCodeMapper corpFollowActiveCodeMapper;

	private final CorpFollowActiveCodeClickRecordMapper corpFollowActiveCodeClickRecordMapper;

	private final RedisService redisService;

	private final SysConfigService sysConfigService;

	@Override
	public String getCorpActiveQrCode(Long acId) throws Exception {
		CorpFollowActiveCode corpFollowActiveCode = corpFollowActiveCodeMapper.selectById(acId);
		if (corpFollowActiveCode == null) {
			return null;
		}
		CorpFollowActiveCodeClickRecord clickRecord = new CorpFollowActiveCodeClickRecord();
		clickRecord.setAcId(acId);
		corpFollowActiveCodeClickRecordMapper.insert(clickRecord);
		String qrCode;
		String activeCodeKey = null;
		List<CorpFollowActiveCodeDto> activeCodeDtos = null;
		if (!corpFollowActiveCode.getIsDuty()) {
			int hour = DateUtil.thisHour(true);
			activeCodeKey = RedisService.key.CORP_FOLLOW_ACTIVE_CODE_KEY.getNameFormat(acId, hour);
			qrCode = redisService.getStr(activeCodeKey);
			if (StrUtil.isNotBlank(qrCode)) {
				return qrCode;
			}
		}

		String followStr = corpFollowActiveCode.getFollowStr();
		List<String> followIds = Jsons.parseList(followStr, String.class);
		String codeStr = corpFollowActiveCode.getCodeStr();
		activeCodeDtos = Jsons.parseList(codeStr, CorpFollowActiveCodeDto.class);
		if (CollUtil.isEmpty(activeCodeDtos)) {
			return null;
		}
		if (!corpFollowActiveCode.getIsDuty()) {
			qrCode = activeCodeDtos.get(0).getQrCode();
			redisService.set(activeCodeKey, qrCode, RedisService.key.CORP_FOLLOW_ACTIVE_CODE_KEY.getTimeout());
			return qrCode;
		}
		//星期五-->星期六 星期六--->星期天 星期天-->星期一
		//值班
		if (corpFollowActiveCode.getIsDuty()) {
			qrCode = getDutyServiceCode(activeCodeDtos);
			return qrCode;
		}
		return null;
	}

	/**
	 * 获取对应值班客服的二维码
	 */
	public String getDutyServiceCode(List<CorpFollowActiveCodeDto> activeCodeDtos) throws Exception {
		if (activeCodeDtos.size() == 1) {
			return activeCodeDtos.get(0).getQrCode();
		}
		List<Integer> dutyServices = sysConfigService.getDutyServices();
		Integer chooseFollowId = null;
		//值班
		if (CollUtil.isNotEmpty(dutyServices)) {
			List<Integer> collectFollow = new ArrayList<>();
			activeCodeDtos.stream().forEach(e -> {
				try {
					collectFollow.addAll(JSONUtil.parseArray(e.getUserIndxList()).toList(Integer.class));
				} catch (Exception ex) {
					System.out.println(ex.getMessage());
				}
			});
			List<Integer> collect = dutyServices.stream().filter(fid -> collectFollow.contains(fid)).collect(Collectors.toList());
			if (CollUtil.isNotEmpty(collect)) {
				chooseFollowId = collect.get(RandomUtil.randomInt(collect.size()));
			}
		}

		CorpFollowActiveCodeDto activeCodeDto = null;
		if (chooseFollowId != null) {
			log.info("寻找合适值班客服:{}", chooseFollowId);
			final Integer csFollowId = chooseFollowId;
			activeCodeDto = activeCodeDtos.stream().filter(active -> {
				try {
					return Jsons.parseList(active.getUserIndxList(), Integer.class).contains(csFollowId);
				} catch (Exception e) {
				}
				return false;
			}).findFirst().get();
		}

		if (activeCodeDto == null) {
			//兜底
			Integer randNum = RandomUtil.randomInt(activeCodeDtos.size());
			log.info("当前时间段:{}未找到对应活码客服，兜底选择", DateUtil.hour(DateTime.now(), true));
			activeCodeDto = activeCodeDtos.get(randNum);
		}
		return activeCodeDto.getQrCode();
	}
}
