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.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyksj.common.constant.Constant;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.util.Jsons;
import com.cyksj.mapper.SysCorpFollowMapper;
import com.cyksj.mapper.SysCorpFollowRelateMapper;
import com.cyksj.mapper.corp.CorpFollowMapper;
import com.cyksj.mapper.manage.cms.CmsUserMapper;
import com.cyksj.mapper.sys.SysConfigMapper;
import com.cyksj.model.dto.YhServiceDto;
import com.cyksj.model.entity.*;
import com.cyksj.model.request.sys.SysCorpFollowReq;
import com.cyksj.service.sys.SysConfigChangeRecordService;
import com.cyksj.service.sys.SysCorpFollowService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
 * 项目名: yhlxj
 * 文件名: SysCorpFollowServiceImpl
 * 创建者: JavaZou
 * 创建时间:2024/6/12 11:58
 */
@Service
@RequiredArgsConstructor
public class SysCorpFollowServiceImpl extends ServiceImpl<SysCorpFollowMapper, SysCorpFollow> implements SysCorpFollowService {
	private final SysCorpFollowRelateMapper sysCorpFollowRelateMapper;

	private final SysConfigMapper sysConfigMapper;

	private final SysConfigChangeRecordService sysConfigChangeRecordService;

	private final CorpFollowMapper corpFollowMapper;

	private final CmsUserMapper cmsUserMapper;

	@Override
	public void saveOrUpdateFollow(SysCorpFollowReq req) throws Exception {
		SysCorpFollow sysCorpFollow = new SysCorpFollow();
		sysCorpFollow.setId(req.getMid());
		sysCorpFollow.setName(req.getName());
		this.saveOrUpdate(sysCorpFollow);

		SysCorpFollowRelate sysCorpFollowRelate = new SysCorpFollowRelate();
		sysCorpFollowRelate.setId(req.getSid());
		sysCorpFollowRelate.setMid(sysCorpFollow.getId());
		sysCorpFollowRelate.setFollowId(req.getFollowId());
		sysCorpFollowRelate.setName(req.getFollowName());
		if (StrUtil.isEmpty(sysCorpFollowRelate.getName())) {
			CorpFollow corpFollow = corpFollowMapper.selectOne(Wrappers.lambdaQuery(CorpFollow.class)
					.eq(CorpFollow::getUserid, req.getFollowId())
					.last("limit 1"));
			if (corpFollow != null) {
				sysCorpFollowRelate.setName(corpFollow.getName());
			}
		}
		sysCorpFollowRelate.setImg(req.getImg());
		sysCorpFollowRelate.setStatus(req.getStatus());
		String followId = sysCorpFollowRelate.getFollowId();
		Integer selectCount = sysCorpFollowRelateMapper.selectCount(Wrappers.lambdaQuery(SysCorpFollowRelate.class)
				.eq(SysCorpFollowRelate::getFollowId, followId)
				.ne(sysCorpFollowRelate.getId() != null, SysCorpFollowRelate::getId, sysCorpFollowRelate.getId())
				.eq(SysCorpFollowRelate::getDeleted, 1));
		if (selectCount > 0) {
			throw BusinessRuntimeException.getInstance("已添加该客服");
		}
		if (sysCorpFollowRelate.getId() == null) {
			sysCorpFollowRelateMapper.insert(sysCorpFollowRelate);
		} else {
			SysCorpFollowRelate db = sysCorpFollowRelateMapper.selectById(sysCorpFollowRelate.getId());
			sysCorpFollowRelateMapper.updateById(sysCorpFollowRelate);
			//更新获客。活码 企业客服
			updateCorpFollowRelateConfig(sysCorpFollowRelate, db);
			//更新客服图片
			updateCorpFollowImg(sysCorpFollowRelate, req.getName());
		}
		//同步企业客服key
		syncSysCorpUserKey();
		//绑定银河登录账号
		bindLoginAccount(sysCorpFollow);
	}

	private void syncSysCorpUserKey() {
		//客服群发key
		SysConfig corpSendMsg = sysConfigMapper.selectOne(Wrappers.lambdaQuery(SysConfig.class)
				.eq(SysConfig::getSysKey, Constant.CORP_SERVICE_FOLLOWS_KEY).last("limit 1"));

		//客服跟进续费key
		SysConfig corpDutyServices = sysConfigMapper.selectOne(Wrappers.lambdaQuery(SysConfig.class)
				.eq(SysConfig::getSysKey, Constant.CORP_SERVICE_GROUPS_RELATION_FOLLOWS_KEY).last("limit 1"));

		//获取目前可用值班客服
		List<SysCorpFollowRelate> sysCorpFollowRelates = sysCorpFollowRelateMapper.selectList(Wrappers.lambdaQuery(SysCorpFollowRelate.class)
				.eq(SysCorpFollowRelate::getStatus, 1)
				.eq(SysCorpFollowRelate::getDeleted, 1));
		List<String> followIds = sysCorpFollowRelates.stream().map(SysCorpFollowRelate::getFollowId).collect(Collectors.toList());
		if (CollUtil.isNotEmpty(followIds)) {
			try {
//				String followIdsStr = Jsons.toJson(followIds);
//				corpSendMsg.setSysValue(followIdsStr);
//				sysConfigMapper.updateById(corpSendMsg);
//
//				corpDutyServices.setSysValue(followIdsStr);
//				sysConfigMapper.updateById(corpDutyServices);
			} catch (Exception e) {
			}

			//同步企业客服对应后台客服关系
			List<CorpFollow> corpFollows = corpFollowMapper.selectList(Wrappers.lambdaQuery(CorpFollow.class)
					.in(CorpFollow::getUserid, followIds)
					.isNull(CorpFollow::getCmsUserId));
			if (CollUtil.isNotEmpty(corpFollows)) {
				Map<String, List<SysCorpFollowRelate>> map = sysCorpFollowRelates.stream().collect(Collectors.groupingBy(SysCorpFollowRelate::getFollowId));
				corpFollows.forEach(e -> {
					List<SysCorpFollowRelate> sysCorpFollowRelates1 = map.get(e.getUserid());
					if (CollUtil.isNotEmpty(sysCorpFollowRelates1)) {
						SysCorpFollow sysCorpFollow = this.getById(sysCorpFollowRelates1.get(0).getMid());
						CmsUser cmsUser = cmsUserMapper.selectOne(Wrappers.lambdaQuery(CmsUser.class)
								.eq(CmsUser::getNickname, sysCorpFollow.getName()));
						if (cmsUser != null) {
							e.setCmsUserId(cmsUser.getId());
							corpFollowMapper.updateById(e);
						}
					}
				});
			}
		}
	}

	@Override
	public void delBySid(Long sid) throws Exception {
		SysCorpFollowRelate sysCorpFollowRelate = sysCorpFollowRelateMapper.selectById(sid);
		if (sysCorpFollowRelate == null || !sysCorpFollowRelate.getDeleted()) {
			return;
		}
		//是否已被选择
		SysConfig sysConfig = sysConfigMapper.selectOne(Wrappers.lambdaQuery(SysConfig.class)
				.eq(SysConfig::getSysKey, Constant.serviceKeys.get(0))
				.last("limit 1"));
		List<YhServiceDto> yhServiceDtos = Jsons.parseList(sysConfig.getSysValue(), YhServiceDto.class);

		yhServiceDtos.stream().forEach(s -> {
			List<YhServiceDto.CustomerServiceDto> select = s.getSelect();
			select.forEach(e -> {
				String followId = e.getFollowId();
				if (StrUtil.equals(followId, sysCorpFollowRelate.getFollowId())) {
					throw BusinessRuntimeException.getInstance("请先移除对应值班客服");
				}
			});
		});
		sysCorpFollowRelate.setDeleted(false);
		sysCorpFollowRelateMapper.updateById(sysCorpFollowRelate);
	}

	@Override
	public void bindLoginAccount(SysCorpFollow sysCorpFollow) {
		Long id = sysCorpFollow.getId();
		SysCorpFollow dbSysFollow = getById(id);
		Long cmsUserId = sysCorpFollow.getCmsUserId();
		if (cmsUserId != null) {
			dbSysFollow.setCmsUserId(cmsUserId);
			List<SysCorpFollowRelate> sysCorpFollowRelates = sysCorpFollowRelateMapper.selectList(Wrappers.lambdaQuery(SysCorpFollowRelate.class)
					.eq(SysCorpFollowRelate::getMid, id));
			for (SysCorpFollowRelate sysCorpFollowRelate : sysCorpFollowRelates) {
				Optional.ofNullable(corpFollowMapper.selectOne(Wrappers.lambdaQuery(CorpFollow.class)
						.eq(CorpFollow::getUserid, sysCorpFollowRelate.getFollowId())
						.last("limit 1"))).ifPresent(follow -> {
					follow.setCmsUserId(dbSysFollow.getCmsUserId());
					corpFollowMapper.updateById(follow);
				});
			}
			updateById(sysCorpFollow);
		}
	}

	public void updateCorpFollowRelateConfig(SysCorpFollowRelate sysCorpFollowRelate, SysCorpFollowRelate db) {
		Long sid = sysCorpFollowRelate.getId();
		if (!StrUtil.equals(db.getFollowId(), sysCorpFollowRelate.getFollowId())) {
			//更新活码，获客
			try {
				sysConfigChangeRecordService.updateCorpFollowLinkConfig(List.of(Integer.parseInt(sid.toString())));
			} catch (Exception e) {
			}

		}
	}

	/**
	 * 更新企业值班客服信息
	 */
	private void updateCorpFollowImg(SysCorpFollowRelate sysCorpFollowRelate, String mName) throws Exception {
		int sid = sysCorpFollowRelate.getId().intValue();
		//更新活码，获客
		SysConfig sysConfig = sysConfigMapper.selectOne(Wrappers.lambdaQuery(SysConfig.class)
				.eq(SysConfig::getSysKey, Constant.serviceKeys.get(0))
				.last("limit 1"));

		List<YhServiceDto> yhServiceDtos = Jsons.parseList(sysConfig.getSysValue(), YhServiceDto.class);
		AtomicBoolean isFlag = new AtomicBoolean(false);
		yhServiceDtos.forEach(ys -> {
			ys.getSelect().forEach(select -> {
				if (select.getIndex().intValue() == sid) {
					select.setFollowId(sysCorpFollowRelate.getFollowId());
					select.setImg(sysCorpFollowRelate.getImg());
					StringBuilder showName = new StringBuilder();
					showName.append(mName).append("(").append(sysCorpFollowRelate.getName()).append(")");
					select.setName(showName.toString());
					select.setStatus(sysCorpFollowRelate.getStatus());
					if (!isFlag.get()) {
						isFlag.set(true);
					}
				}
			});
		});
		if (isFlag.get()) {
			sysConfig.setSysValue(Jsons.toJson(yhServiceDtos));
			sysConfigMapper.updateById(sysConfig);
		}
	}
}
