package com.xinelu.manage.service.aiob.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.xinelu.common.exception.ServiceException;
import com.xinelu.manage.domain.aiob.AIOBCallbackEntity;
import com.xinelu.manage.mapper.aiob.AIOBCallbackMapper;
import com.xinelu.manage.service.aiob.IAIOBCallbackService;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @description: 阿里云服务器百度外呼回调Service实现
 * @author: haown
 * @create: 2025-12-23 15:30
 **/
@Service
@Slf4j
public class AIOBCallbackServiceImpl implements IAIOBCallbackService {
	@Resource
	private AIOBCallbackMapper aiobCallbackMapper;
	@Value("${aiob.callBackUrl}")
	private String callBackUrl;
	@Override
	public List<AIOBCallbackEntity> getList(AIOBCallbackEntity query) {
		// 接口获取外呼回调数据app
		List<AIOBCallbackEntity> callbackEntityList = new ArrayList<>();
		HttpEntity<JSONObject> requestEntity = new HttpEntity<>((JSONObject) JSON.toJSON(query));
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity<String> responseEntity = restTemplate.exchange(callBackUrl + "/getList", HttpMethod.POST, requestEntity, String.class);
		JSONObject object = JSON.parseObject(responseEntity.getBody());
		if (object == null || object.getInteger("code") == null || object.getInteger("code") != 0) {
			return null;
		}
		if (object.containsKey("data")) {
			JSONArray data = object.getJSONArray("data");
			if (data != null && data.size() > 0) {
				callbackEntityList = data.toJavaList(AIOBCallbackEntity.class);
			}
		}
		return callbackEntityList;
	}

	@Override public Integer updateReadState(Integer readState, Integer id) {
		log.info("修改百度外呼回调数据已读状态--id：{}", id);
		JSONObject TaskCallbackUpdateDto = new JSONObject();
		TaskCallbackUpdateDto.fluentPut("id", id).fluentPut("readState", readState);
		HttpEntity<JSONObject> requestEntity = new HttpEntity<>(TaskCallbackUpdateDto);
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity<String> responseEntity = restTemplate.exchange(callBackUrl + "/updateReadState", HttpMethod.POST, requestEntity, String.class);
		JSONObject object = JSON.parseObject(responseEntity.getBody());
		if (object == null || object.getInteger("code") == null || object.getInteger("code") != 0) {
			log.info("修改百度外呼回调数据已读状态失败--id：{},原因：{}", id, object.getString("message"));
			return null;
		}
		log.info("修改百度外呼回调数据已读状态成功--id：{}", id);
		return 1;
	}

	@Override public Integer deleteData() {
		return aiobCallbackMapper.deleteData();
	}
}
