package com.cyksj.task;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.util.StringUtil;
import com.cyksj.mapper.corp.CorpUserAuthMapper;
import com.cyksj.mapper.corp.CorpUserMapper;
import com.cyksj.model.entity.CorpUser;
import com.cyksj.model.entity.CorpUserAuth;
import com.cyksj.model.entity.OrderDonPost;
import com.cyksj.redis.RedisService;
import com.cyksj.service.order.OrderDonPostService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Optional;
import java.util.Set;

/**
 * @author chan
 * @date 2024-04-29 12:14
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class CorpChatScheduler {

	private final CorpUserMapper corpUserMapper;

	private final CorpUserAuthMapper corpUserAuthMapper;

	private final RedisService redisService;

	private final OrderDonPostService orderDonPostService;

	/**
	 * 客服业绩数据统计
	 */
//    @Scheduled(cron = "5 0/2 * * * ?")
	public void chatPost() {
		Set<Object> chatRecord = redisService.sGet(RedisService.key.CORP_CUSTOMER_ACQUISTION_START_CHAT_SET.getName());
		log.info("发起对话回传. size: {}", chatRecord.size());
		chatRecord.forEach((key) -> {
			log.info("发起对话回传. key: {}", key);
			CorpUserAuth corpUserAuth = corpUserAuthMapper.selectOne(Wrappers.lambdaQuery(CorpUserAuth.class)
					.eq(CorpUserAuth::getExternalUserid, key).last("limit 1"));
			String unionId = null;
			if (corpUserAuth != null) {
				CorpUser corpUser = corpUserMapper.selectById(corpUserAuth.getCorpUserId());
				if (corpUser != null) {
					unionId = corpUser.getUnionid();
				}
			}
			log.info("发起对话回传. unionId: {}", unionId);
			if (StrUtil.isNotBlank(unionId)) {
				String json = StringUtil.getString(redisService.hget(RedisService.key.CORP_CUSTOMER_ACQUISTION_START_CHAT.getName(), unionId));
				if (StringUtil.isNotBlank(json)) {
					JSONObject jsonObject = JSONUtil.parseObj(json);
					String callback = jsonObject.getStr("callback");
					try {
						orderDonPostService.post(OrderDonPost.Type.OE.getType(), callback, Optional.ofNullable(jsonObject.getStr("event")).orElse("customer_effective"));
						redisService.setRemove(RedisService.key.CORP_CUSTOMER_ACQUISTION_START_CHAT_SET.getName(), key);
						log.info("发起对话回传成功. {}", key);
					} catch (Exception e) {
						log.error("发起对话回传失败. {}", e.getMessage());
					}
				}
			}else {
				Long count = redisService.incr(RedisService.key.CORP_CUSTOMER_ACQUISTION_START_CHAT_COUNT.getNameFormat(key), 1L);
				if(count > 3){
					redisService.setRemove(RedisService.key.CORP_CUSTOMER_ACQUISTION_START_CHAT_SET.getName(), key);
				}
			}
		});
	}
}
