package com.cyksj.service.corp.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.util.Jsons;
import com.cyksj.mapper.corp.CorpFollowConfigMapper;
import com.cyksj.mapper.corp.CorpTagMapper;
import com.cyksj.model.dto.CorpFollowActiveCodeDto;
import com.cyksj.model.entity.CorpFollowConfig;
import com.cyksj.model.entity.CorpTag;
import com.cyksj.model.request.corp.CorpFollowContact;
import com.cyksj.model.views.SysCorpFollowView;
import com.cyksj.service.corp.CorpFollowDynamicConfigService;
import com.cyksj.service.corp.WxCorpOps;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

/*
 *项目名: netflix
 *文件名: CorpFollowDynamicConfigServiceImpl
 *创建者: JavaZou
 *创建时间:2023/7/6 12:25
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class CorpFollowDynamicConfigServiceImpl implements CorpFollowDynamicConfigService {
	private final WxCorpOps wxCorpOps;

	private final CorpFollowConfigMapper corpFollowConfigMapper;

	private final CorpTagMapper corpTagMapper;

	private final BeanSearcher beanSearcher;

	@Override
	public String corpFollowContactConfig(CorpFollowContact corpFollowContact) throws Exception {
		String body = wxCorpOps.corpFollowContactConfig(corpFollowContact);
		JSONObject jsonObject = Jsons.parseObject(body, JSONObject.class);
		List<String> followIds = corpFollowContact.getUser();
		log.info("body:{}", body);
		followIds.forEach(followId->{
			CorpFollowConfig corpFollowConfig = new CorpFollowConfig();
			corpFollowConfig.setFollowId(followId);
			corpFollowConfig.setQrCode(jsonObject.getStr("qr_code"));
			corpFollowConfig.setConfigId(jsonObject.getStr("config_id"));
			corpFollowConfig.setRemark(corpFollowContact.getRemark());
			corpFollowConfigMapper.insert(corpFollowConfig);
		});
		return body;
	}

	@Override
	public String createCorpFollowActiveCode(List<String> followIds, List<Integer> userIndxList, String state, Boolean isDuty) throws Exception {
		List<CorpFollowActiveCodeDto> codeList = new ArrayList<>();
		List<SysCorpFollowView> corpFollowServiceDtos = beanSearcher.searchAll(SysCorpFollowView.class, MapUtils.builder().build());
		Integer type = 1;
		if (!isDuty) {
			//不是值班 多人生成一个二维码
			//联系方式类型 2-多人
			if (followIds.size() > 1) {
				type = 2;
			}
			String serviceNames = null;
			if (corpFollowServiceDtos != null) {
				serviceNames = corpFollowServiceDtos.stream().filter(cs -> userIndxList.contains(Integer.parseInt(cs.getSid().toString()))).map(SysCorpFollowView::getShowName).collect(Collectors.joining(","));
			}
			if (StrUtil.isEmpty(serviceNames)) {
				throw BusinessRuntimeException.getInstance("存在被删除的客服,请刷新页面重试");
			}
			CorpFollowActiveCodeDto corpFollowActiveCodeDto = createCorpFollowActiveCode(followIds, userIndxList, state, type, serviceNames);
			codeList.add(corpFollowActiveCodeDto);
		} else {
			Map<String, List<SysCorpFollowView>> csMap = null;
			if (corpFollowServiceDtos != null) {
				csMap = corpFollowServiceDtos.stream().filter(cs -> userIndxList.contains(Integer.parseInt(cs.getSid().toString()))).collect(Collectors.groupingBy(SysCorpFollowView::getFollowId));
			}
			if (csMap == null || csMap.keySet().size() != followIds.size()) {
				throw BusinessRuntimeException.getInstance("存在被删除的客服,请刷新页面重试");
			}
			for (String followId : followIds) {
				SysCorpFollowView corpFollowServiceDto = csMap.get(followId).get(0);
				CorpFollowActiveCodeDto corpFollowActiveCodeDto = createCorpFollowActiveCode(List.of(followId), List.of(Integer.parseInt(corpFollowServiceDto.getSid().toString())), state, type, corpFollowServiceDto.getShowName());
				codeList.add(corpFollowActiveCodeDto);
			}
		}
		return Jsons.toJson(codeList);
	}

	@Override
	public void updateCorpFollowActiveCode(String oldMarkTag, String markTag) throws Exception {
		CorpTag corpTag = corpTagMapper.selectOne(Wrappers.lambdaQuery(CorpTag.class)
				.eq(CorpTag::getName, oldMarkTag).last("limit 1"));
		if (corpTag != null) {
			//更新该标签名
			JSONObject params = new JSONObject();
			params.putOpt("id", corpTag.getTagId());
			params.putOpt("name", markTag);
			wxCorpOps.editCorpTag(params);
			corpTag.setName(markTag);
			corpTagMapper.updateById(corpTag);
		}
	}

	public CorpFollowActiveCodeDto createCorpFollowActiveCode(List<String> followIds, List<Integer> userIndxList, String state, Integer type, String serviceName) throws Exception {
		CorpFollowContact c = new CorpFollowContact();
		c.setType(type);
		c.setScene(2);
		c.setUser(followIds);
		c.setState(state);
		c.setRemark("客服活动活码");
		c.setSkip_verify(true);
		String body = wxCorpOps.corpFollowContactConfig(c);
		JSONObject jsonObject = Jsons.parseObject(body, JSONObject.class);
		String qrCode = jsonObject.getStr("qr_code");
		String configId = jsonObject.getStr("config_id");
		CorpFollowActiveCodeDto corpFollowActiveCodeDto = new CorpFollowActiveCodeDto();
		corpFollowActiveCodeDto.setFollowIds(followIds.toString());
		corpFollowActiveCodeDto.setUserIndxList(userIndxList.toString());
		corpFollowActiveCodeDto.setServiceNames(serviceName);
		corpFollowActiveCodeDto.setQrCode(qrCode);
		corpFollowActiveCodeDto.setConfigId(configId);
		return corpFollowActiveCodeDto;
	}
}
