package org.security.xyun.service;

import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.security.config.XYunProperties;
import org.security.desk.xyun.res.MsgResponseBody;
import org.security.xyun.utils.XYunPubUtil;
import org.springblade.core.tool.api.R;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;

@Service
@AllArgsConstructor
@Slf4j
public class IXYunServiceImpl implements IXYunService {
	private final XYunProperties xYunProperties;
	private final RestTemplate restTemplate;

	@Override
	public R<MsgResponseBody> sendMessageToXYun(String to, String msg) {
		JSONObject pubToken = XYunPubUtil.generateFrom(xYunProperties);

		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.parseMediaType("application/json;charset=UTF-8"));
		headers.add("Accept", MediaType.APPLICATION_JSON.toString());

		String[] users = to.split(",");
		if (users.length < 1) {
			return R.fail("接收的用户为空！");
		}
		JSONObject to1 = new JSONObject();
		to1.put("no", xYunProperties.getEId());
		to1.put("user", users);
		to1.put("code", "2");
		ArrayList<JSONObject> tos = new ArrayList<>();
		tos.add(to1);

		HashMap<String, Object> msgContent = new HashMap<>();
		// msgContent.put("appid", xYunProperties.getAppId());
		msgContent.put("text", msg);
		// msgContent.put("todo", 0);
		// msgContent.put("url", "");

		JSONObject reqBody = new JSONObject();
		reqBody.put("from", pubToken);
		reqBody.put("to", tos);
		reqBody.put("type", 2);
		reqBody.put("msg", msgContent);

		HttpEntity<JSONObject> httpEntity = new HttpEntity<>(reqBody, headers);
		ParameterizedTypeReference<MsgResponseBody> typeRef =
			new ParameterizedTypeReference<MsgResponseBody>() {
			};
		MsgResponseBody msgResponse;
		String msgUrl = xYunProperties.getUrl() + "/pubacc/pubsend";
		log.info(">>>>>> 公共号发送消息url：" + msgUrl);
		log.info(">>>>>> 消息体" + reqBody.toJSONString());
		try {
			msgResponse = restTemplate.exchange(msgUrl, HttpMethod.POST, httpEntity, typeRef).getBody();
		} catch (ResourceAccessException e) {
			return R.fail("消息发送失败，发送超时，url：" + msgUrl);
		} catch (Exception e) {
			e.printStackTrace();
			return R.fail("消息发送失败，错误原因：" + e.getMessage());
		}
		log.info(">>>>>> 消息发送结果：");
		log.info(JSONObject.toJSONString(msgResponse));

		return R.data(msgResponse);
	}
}
