package org.springblade.common.utils.hangxin;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.utils.hangxin.bean.HangxinResultBean;
import org.springblade.common.utils.hangxin.conf.HangxinConfig;
import org.springblade.common.utils.hangxin.contants.HangxinConstants;
import org.springblade.core.tool.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class HangxinUtil {

	@Autowired
	private HangxinConfig hangxinConfig;


	public HangxinResultBean sendMsg (List<String> userEhrs, String title, String content){
		RestTemplate restTemplate = new RestTemplate();
		String url = hangxinConfig.getUrl() + HangxinConstants.SEND_MSG;
		HttpHeaders headers = createHttpHeaders();

		Map<String, Object> params = new HashMap<>();
		params.put("touser", StringUtil.join(userEhrs, "|"));
		params.put("sysid", hangxinConfig.getSysid() + "|text");
		params.put("title", title);
		params.put("content", content);

		HttpEntity<String> requestEntity = new HttpEntity<>(JSONUtil.toJsonStr(params), headers);
		URI uri = URI.create(url);
		ParameterizedTypeReference<HangxinResultBean> reference = new ParameterizedTypeReference<HangxinResultBean>() {};
		ResponseEntity<HangxinResultBean> response = restTemplate.exchange(uri, HttpMethod.POST, requestEntity, reference);

		return response.getBody();
	}






	private HttpHeaders createHttpHeaders(){
		HttpHeaders httpHeaders = new HttpHeaders();
		httpHeaders.add(HttpHeaders.CONTENT_TYPE, "application/json");
//		httpHeaders.add("appKey", elevatorConfig.getAppKey());
//		httpHeaders.add("appSecret", elevatorConfig.getAppSecret());
		return httpHeaders;
	}

}
