package com.testor.module.video.util;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.tongtech.tfw.backend.common.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Component
public class RequestVideoInfoUtil {

	@Autowired
	private RestTemplate restTemplate;


	@Value("${three.videoinfo.url}")
	private String threeVideoInfoUrl;

	@Value("${three.videoinfo.username}")
	private String username;

	@Value("${three.videoinfo.password}")
	private String password;

	private static final String TOKEN = "token";

	public <T> ResponseEntity<T> post(Class<T> responseType) {
		String url = threeVideoInfoUrl + "/jeeStudio/gtoa/a/zlm1/cameraSet/getCameraInfo";
		return request(url, HttpMethod.POST, responseType);
	}
	private <T> ResponseEntity<T> request(String url, HttpMethod httpMethod, Class<T> responseType) {
		ResponseEntity<T> response;
		try {
			if (StringUtils.isEmpty(url)) {

				throw new IllegalArgumentException();
			}
			//设置http的header
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_JSON);
			//先登录
			this.toLogin(headers);
			HttpEntity<String> requestEntity=new HttpEntity<String>(headers);;
			response = restTemplate.exchange(url, httpMethod, requestEntity, responseType);
			return response;
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}
	private void toLogin(HttpHeaders headers) throws BusinessException, JsonProcessingException {
		String url = threeVideoInfoUrl + "/jeeStudio/gtoa/a/zlm1/cameraSet/login?username={username}&password={password}";
		// 封装参数，千万不要替换为Map与HashMap，否则参数无法传递
		Map<String,String> params = new HashMap<>();
		params.put("username", username);
		params.put("password", password);
		HttpHeaders httpHeaders = new HttpHeaders();
		httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
		HttpEntity httpEntity = new HttpEntity(null,headers);		//构建请求参数
		Map map = restTemplate.postForObject(url, httpEntity, Map.class, params);
		Integer code = (Integer) map.get("code");
		String token = (String) map.get("token");
		if(code == 0){
			headers.add(TOKEN,token);
		}else{
			throw new BusinessException("获取设备信息出错");
		}
	}
}
