package com.xinelu.quartz.task;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.exceptions.ClientException;
import com.xinelu.manage.domain.aiob.AIOBCallbackEntity;
import com.xinelu.manage.dto.aiob.TaskCallbackDataDto;
import com.xinelu.manage.service.aiob.IAIOBCallbackService;
import com.xinelu.manage.service.aiob.IAIOBService;
import java.util.List;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

/**
 * @description: 获取百度外呼回调数据
 * @author: haown
 * @create: 2025-12-23 15:12
 **/
@Slf4j
@Component("GetAiobCallbackDataTask")
public class GetAiobCallbackDataTask {
	@Resource
	private IAIOBService aiobService;
	@Resource
	private IAIOBCallbackService aiobCallbackService;

	public void syncCallbackData() {
		log.info("开始执行同步百度外呼回调数据定时任务......");
		AIOBCallbackEntity aiobCallbackEntity = new AIOBCallbackEntity();
		aiobCallbackEntity.setReadState(0);
		List<AIOBCallbackEntity> callbackEntityList = aiobCallbackService.getList(aiobCallbackEntity);
		if (!CollectionUtils.isEmpty(callbackEntityList)) {
			// 回调数据解析
			callbackEntityList.forEach(callbackEntity -> {
				// JSONString 转 TaskCallbackDataDto
				TaskCallbackDataDto taskCallbackDataDto = JSON.parseObject(callbackEntity.getCallbackData(), TaskCallbackDataDto.class);
				try {
					// 执行回调
					aiobService.taskCallBack(callbackEntity.getCallbackType(), taskCallbackDataDto);
					// 修改阿里云服务器回调数据已读状态
					aiobCallbackService.updateReadState(1, callbackEntity.getId());
				} catch (ClientException e) {
					throw new RuntimeException(e);
				}
			});
		}
		log.info("完成同步百度外呼回调数据定时任务......");
	}

	public void clearCallbackData() {
		log.info("开始执行清除过期的百度外呼回调数据定时任务......");
		// 清除一个月前的数据
		int count = aiobCallbackService.deleteData();
		log.info("完成清除过期的百度外呼回调数据定时任务,共清除" + count +"条......");
	}
}
