package com.palmnest.service.ws;


import com.alibaba.fastjson.JSON;
import com.palmnest.application.CodeConstants;
import com.palmnest.application.Constants;
import com.palmnest.application.dto.OrgKoalaInfoVo;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.estateserve.VisitorInfo;
import com.palmnest.service.redis.BaseRedisService;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.*;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.HttpClientErrorException;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * facePlus 接口调用
 *
 * @author HJY
 */
@Slf4j
public class FacePlusClient {

	
	@Autowired
	private static BaseRedisService    baseRedisService;

	/**
	 * 登录 获取cookie
	 *
	 * @param url      接口地址
	 * @param username 账号
	 * @param password 密码
	 * @return cookie
	 */
	public static CookieStore authLogin(String url,String username, String password) {
		log.info("init 初始化 登录facePlus 账号：" + username + "，密码：" + password);
		if(StringUtils.isEmpty(url)){
			url = Constants.KOALOA_PLUS_URL;
		}
		try {
			CloseableHttpClient httpclient = HttpClients.createDefault();
			//HttpPost            request    = new HttpPost(Constants.FACE_PLUS_CLIENT_URL + "/auth/login");
			HttpPost            request    = new HttpPost(url + "/auth/login");
			request.setHeader("User-Agent", "Koala Admin");
			request.setHeader("Content-Type", "application/json");
			JSONObject json = new JSONObject();
			json.put("username", username);
			json.put("password", password);
			request.setEntity(new StringEntity(json.toString(), "UTF-8"));
			HttpClientContext     context      = HttpClientContext.create();
			CloseableHttpResponse response     = httpclient.execute(request, context);
			String                responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
			// 解析JSON数据
			JSONObject resp   = new JSONObject(responseBody);
			int        result = resp.optInt("code", -1);
			if (result != 0) {
				log.info("Login failed, code:" + result);
			} else {
				log.info("Login Success,id:" + resp.getJSONObject("data").getInt("id"));
				return context.getCookieStore();
			}
		} catch (Exception e) {
			log.error("Login error, code:" + e.getMessage());
			return null;
		}
		return null;
	}

	/**
	 * 上传用户信息接口
	 *
	 * @param paramMap [subjectType(用户类型0为员工1普通访客2为VIP访客),photo_ids 图片集合ID,
	 *                 obj(subjectType为0是Appuser员工对象,其他则为VisitorInfo访客对象)]参数
	 * @return
	 * @throws Exception
	 */
	public static Integer subject(Map<String, Object> paramMap, CookieStore cookieStore) throws Exception {
		log.info("调起上传用户信息接口  请求方式post 创建用户 ...");
		try {
			CloseableHttpClient httpclient  = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
			Integer             subjectType = (Integer) paramMap.get("subjectType");//subjectType为0是员工对象 其他则为访客
			@SuppressWarnings("unchecked")
			List<Integer> photo_ids = (List<Integer>) paramMap.get("photo_ids");
			HttpPost request = new HttpPost(Constants.KOALOA_PLUS_URL + "/subject");
			request.setHeader("Content-Type", "application/json");
			JSONObject json = new JSONObject();
			json.put("subject_type", subjectType);// 如果subject_type不等于0，必须要指定start_time，end_time
			json.put("photo_ids", photo_ids);//识别头像列表
			
			if(paramMap.containsKey("come_from")){
				json.put("come_from", paramMap.get("come_from"));
			}
			if(paramMap.containsKey("interviewee")){
				json.put("interviewee", paramMap.get("interviewee"));
			}	
			if(paramMap.containsKey("phone")){
				json.put("phone", paramMap.get("phone"));
			}
			if(paramMap.containsKey("extra_id")){
				json.put("extra_id", paramMap.get("extra_id"));
			}			
			
			//上传访客
			if (subjectType != 0) {
				VisitorInfo tbVisitorInfo = (VisitorInfo) paramMap.get("obj");//员工或者访客对象 subjectType为0是员工对象
				json.put("start_time", tbVisitorInfo.getVisitorStartTime().getTime() / 1000);//起始时间
				json.put("end_time", tbVisitorInfo.getVisitorEndTime().getTime() / 1000);//结束时间
				json.put("name", tbVisitorInfo.getVisitorName());//访客名称
			} else {
				//上传用户
				AppUser appUser = (AppUser) paramMap.get("obj");
				json.put("name", appUser.getUserName());
			}
			request.setEntity(new StringEntity(json.toString(), "UTF-8"));
			CloseableHttpResponse response     = httpclient.execute(request);
			String                responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
			// 解析JSON数据
			JSONObject resp   = new JSONObject(responseBody);
			int        result = resp.optInt("code", -1);
			if (result != 0) {
				log.error("code:" + result + ",desc:" + resp.getString("desc"));
			} else {
				log.info("id:" + resp.getJSONObject("data").getInt("id"));
				return resp.getJSONObject("data").getInt("id");
			}
		} catch (Exception e) {
			log.error("调起上传用户信息接口 错误：" + e.getMessage());
		}
		return null;
	}

	
	/**
	 * 上传用户信息接口
	 *
	 * @param paramMap [subjectType(用户类型0为员工1普通访客2为VIP访客),photo_ids 图片集合ID,
	 *                 obj(subjectType为0是Appuser员工对象,其他则为VisitorInfo访客对象)]参数
	 * @return
	 * @throws Exception
	 */
	public static Integer koalaSubject(Map<String, Object> paramMap,OrgKoalaInfoVo orgKoalaInfoVo) throws Exception {
		log.info("调起上传用户信息接口  请求方式post 创建用户 ...");
		try {
			
			Integer  orgId = (Integer) paramMap.get("orgId");
			//OrgKoalaInfoVo orgKoalaInfoVo = getOrgKoalaInfoVoByOrgId(orgId);
			//因一个小时 token 会失效 不能用定时任务 要校验token 是否失效 不如每次登录
	        CookieStore cookieStore = authLogin(orgKoalaInfoVo.getKoalaAuthUrl(),orgKoalaInfoVo.getKoalaUserName(),orgKoalaInfoVo.getKoalaUserPwd());
			
			
			CloseableHttpClient httpclient  = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
			String             extra_id =  (String)paramMap.get("extra_id");
			String             name = (String) paramMap.get("name");
			Integer             subjectType = (Integer) paramMap.get("subjectType");//subjectType为0是员工对象 其他则为访客
			@SuppressWarnings("unchecked")
			List<Integer> photo_ids = (List<Integer>) paramMap.get("photo_ids");
			HttpPost request = new HttpPost(orgKoalaInfoVo.getKoalaAuthUrl() + "/subject");
			request.setHeader("Content-Type", "application/json");
			JSONObject json = new JSONObject();
			json.put("subject_type", subjectType);// 如果subject_type不等于0，必须要指定start_time，end_time
			json.put("extra_id", extra_id);
			//json.put("photo_ids", photo_ids);//识别头像列表
			
			 if(null!=photo_ids && photo_ids.size()>=0){//用就更新、没有就删除(解除用户和图片关系
	                json.put("photo_ids", photo_ids);//识别头像列表
			 }	
		
			//上传访客
			if (subjectType != 0) {
				VisitorInfo tbVisitorInfo = (VisitorInfo) paramMap.get("obj");//员工或者访客对象 subjectType为0是员工对象
				json.put("start_time", tbVisitorInfo.getVisitorStartTime().getTime() / 1000);//起始时间
				json.put("end_time", tbVisitorInfo.getVisitorEndTime().getTime() / 1000);//结束时间
				json.put("name", tbVisitorInfo.getVisitorName());//访客名称
			} else {
				//上传用户
				AppUser appUser = (AppUser) paramMap.get("obj");
				json.put("name", name);
			}
			request.setEntity(new StringEntity(json.toString(), "UTF-8"));
			CloseableHttpResponse response     = httpclient.execute(request);
			String                responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
			// 解析JSON数据
			JSONObject resp   = new JSONObject(responseBody);
			int        result = resp.optInt("code", -1);
			if (result != 0) {
				log.error("code:" + result + ",desc:" + resp.getString("desc"));
			} else {
				 log.info("Login Success,返回内容:" + resp.getJSONObject("data"));
				return resp.getJSONObject("data").getInt("id");
			}
		} catch (Exception e) {
			log.error("调起上传用户信息接口 错误：" + e.getMessage());
		}
		return null;
	}

	/**
	 * 获取用户信息接口
	 *
	 * @param facePlusUserId(facePlus唯一标识)
	 * @return
	 * @throws Exception
	 */

	public static String getSubject(Integer facePlusUserId, Map<String, Object> paramMap,OrgKoalaInfoVo orgKoalaInfoVo) throws Exception {
		log.info("调起获取用户信息接口  请求方式GET 获取用户接口 ...");
		try {
			
			Integer  orgId = (Integer) paramMap.get("orgId");
			//OrgKoalaInfoVo orgKoalaInfoVo = getOrgKoalaInfoVoByOrgId(orgId);
			//因一个小时 token 会失效 不能用定时任务 要校验token 是否失效 不如每次登录
	        CookieStore cookieStore = authLogin(orgKoalaInfoVo.getKoalaAuthUrl(),orgKoalaInfoVo.getKoalaUserName(),orgKoalaInfoVo.getKoalaUserPwd());
			
			CloseableHttpClient   httpclient   = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
			HttpGet               request      = new HttpGet(orgKoalaInfoVo.getKoalaAuthUrl() + "/subject/" + facePlusUserId);
			CloseableHttpResponse response     = httpclient.execute(request);
			String                responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
			JSONObject            resp         = new JSONObject(responseBody);
			int                   result       = resp.optInt("code", -1);
			if (result != 0) {
				log.error("getSubject code:" + result + ",desc:" + resp.getString("desc"));
			} else {
				JSONObject userInfo = resp.getJSONObject("data");
				log.info("getSubject id:" + userInfo.getInt("id") + ",name:" + userInfo.getString("name"));
				return userInfo.toString();
			}
		} catch (JSONException jsonException) {
			log.error("getSubject error, jsonException:" + jsonException.getMessage());
		} catch (Exception e) {
			log.error("getSubject error, Exception:" + e.getMessage());
		}
		return null;
	}
	
	
	
	
	public static Integer getSubjectList(String extra_id, Map<String, Object> paramMap,OrgKoalaInfoVo orgKoalaInfoVo) throws Exception {
		log.info("调起获取用户信息接口  请求方式GET 获取用户接口 ...");
		
		Integer subjectId = 0;
		
		try {
			
			Integer  orgId = (Integer) paramMap.get("orgId");
			//OrgKoalaInfoVo orgKoalaInfoVo = getOrgKoalaInfoVoByOrgId(orgId);
			//因一个小时 token 会失效 不能用定时任务 要校验token 是否失效 不如每次登录
	        CookieStore cookieStore = authLogin(orgKoalaInfoVo.getKoalaAuthUrl(),orgKoalaInfoVo.getKoalaUserName(),orgKoalaInfoVo.getKoalaUserPwd());
			
			CloseableHttpClient   httpclient   = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
			HttpGet               request      = new HttpGet(orgKoalaInfoVo.getKoalaAuthUrl() + "/subject/list" + "?category=visitor&extra_id="+extra_id);
			CloseableHttpResponse response     = httpclient.execute(request);
			String                responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
			JSONObject            resp         = new JSONObject(responseBody);
			int                   result       = resp.optInt("code", -1);
			if (result != 0) {
				log.error("getSubject code:" + result + ",desc:" + resp.getString("desc"));
			} else {
				JSONArray subjectList = resp.getJSONArray("data");
				log.info("subjectList===>"+subjectList.toString());
				if(subjectList.length()>=1){
					subjectId = subjectList.getJSONObject(0).getInt("id");
				}
				return subjectId;
				 
			}
		} catch (JSONException jsonException) {
			log.error("getSubject error, jsonException:" + jsonException.getMessage());
		} catch (Exception e) {
			log.error("getSubject error, Exception:" + e.getMessage());
		}
		return subjectId;
	}
	

   /* public static OrgKoalaInfoVo getOrgKoalaInfoVoByOrgId(Integer orgId){

        OrgKoalaInfoVo orgKoalaInfoVo = new OrgKoalaInfoVo();
        String data = baseRedisService.get("User.id:"+ CodeConstants.RSA_REDIS_ORGKOALA_KEY + "_"+orgId);
        log.info("根据orgId:{}找到koala信息:{}",orgId,data);
        if(StringUtils.isNotEmpty(data)){
            orgKoalaInfoVo = JSON.parseObject(data, OrgKoalaInfoVo.class);
        }

        return orgKoalaInfoVo;
    }*/
	
	/**
	 * 修改用户信息接口
	 *
	 * @param photo_ids(face++图片ID集合),appUser(员工对象) 参数
	 * @return
	 * @throws Exception
	 */
	public static Integer updatesubject(AppUser appUser, List<Integer> photo_ids, CookieStore cookieStore) throws Exception {
		log.info("调起更新用户信息接口  请求方式post 创建用户 ...");
		try {
			CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
			HttpPut             request    = new HttpPut(Constants.KOALOA_PLUS_URL + "/subject/" + appUser.getFacePlusUserId());
			request.setHeader("Content-Type", "application/json");
			JSONObject json = new JSONObject();
			json.put("photo_ids", photo_ids);//识别头像列表
			json.put("name", appUser.getUserName());
			request.setEntity(new StringEntity(json.toString(), "UTF-8"));
			CloseableHttpResponse response     = httpclient.execute(request);
			String                responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
			// 解析JSON数据
			JSONObject resp   = new JSONObject(responseBody);
			int        result = resp.optInt("code", -1);
			if (result != 0) {
				log.error("code:" + result + ",desc:" + resp.getString("desc"));
			} else {
				log.info("id:" + resp.getJSONObject("data").getInt("id"));
				return resp.getJSONObject("data").getInt("id");
			}
		} catch (Exception e) {
			log.error("调起上传用户信息接口 错误：" + e.getMessage());
		}
		return null;
	}

	
	/**
	 * 
	 * @param photo_ids(face++图片ID集合),appUser(员工对象) 参数
	 * @return
	 * @throws Exception
	 */
	public static Integer updateKoalasubject(AppUser appUser, List<Integer> photo_ids, Map<String, Object> paramMap,OrgKoalaInfoVo orgKoalaInfoVo) throws Exception {
		log.info("调起更新用户信息接口  请求方式post 创建用户 ...");
		try {
			
			Integer  orgId = (Integer) paramMap.get("orgId");
			//OrgKoalaInfoVo orgKoalaInfoVo = getOrgKoalaInfoVoByOrgId(orgId);
			//因一个小时 token 会失效 不能用定时任务 要校验token 是否失效 不如每次登录
	        CookieStore cookieStore = authLogin(orgKoalaInfoVo.getKoalaAuthUrl(),orgKoalaInfoVo.getKoalaUserName(),orgKoalaInfoVo.getKoalaUserPwd());
			
			CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
			HttpPut             request    = new HttpPut(orgKoalaInfoVo.getKoalaAuthUrl() + "/subject/" + appUser.getFacePlusUserId());
			request.setHeader("Content-Type", "application/json");
			JSONObject json = new JSONObject();
			json.put("subject_type", 0);//必录
			
			
			 if(null!=photo_ids && photo_ids.size()>=0){//用就更新、没有就删除(解除用户和图片关系
	                json.put("photo_ids", photo_ids);//识别头像列表
			 }		 
			
			json.put("name", appUser.getUserName());
			request.setEntity(new StringEntity(json.toString(), "UTF-8"));
			CloseableHttpResponse response     = httpclient.execute(request);
			String                responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
			// 解析JSON数据
			JSONObject resp   = new JSONObject(responseBody);
			int        result = resp.optInt("code", -1);
			if (result != 0) {
				log.error("code:" + result + ",desc:" + resp.getString("desc"));
			} else {
				log.info("id:" + resp.getJSONObject("data").getInt("id"));
				return resp.getJSONObject("data").getInt("id");
			}
		} catch (Exception e) {
			log.error("调起上传用户信息接口 错误：" + e.getMessage());
		}
		return null;
	}
	

	/**
	 * 删除用户
	 *
	 * @param facePlusUserId 【facePlusUser唯一标识】
	 * @throws Exception
	 */
	public static boolean deleteSubject(Integer facePlusUserId, CookieStore cookieStore) throws Exception {
		log.info("调起删除用户信息接口 请求方式delete 删除用户");
		try {
			CloseableHttpClient   httpclient   = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
			HttpDelete            request      = new HttpDelete(Constants.KOALOA_PLUS_URL + "/subject/" + facePlusUserId);
			CloseableHttpResponse response     = httpclient.execute(request);
			String                responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
			//解析JSON
			JSONObject resp   = new JSONObject(responseBody);
			int        result = resp.optInt("code", -1);
			if (result != 0) {
				log.error("code:" + result + ",desc:" + resp.getString("desc"));
			} else {
				JSONObject userInfo = resp.getJSONObject("data");
				log.info("id:" + userInfo.getInt("id") + ",name:" + userInfo.getString("name"));
				return true;
			}
		} catch (JSONException jsonException) {
			log.error("deleteSubject error, jsonException:" + jsonException.getMessage());
		} catch (Exception e) {
			log.error("deleteSubject error, Exception:" + e.getMessage());
		}
		return false;
	}

	/**
	 * 上传识别底库
	 *
	 * @param paramMap[photo(完整的本地图片路径)]
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
	public static Integer photo(Map<String, Object> paramMap, CookieStore cookieStore,OrgKoalaInfoVo orgKoalaInfoVo) throws Exception {
		log.info("调起上传识别照片（/subject/photo）接口  请求方式post 上传识别照片 ...");
		try {
			// 自定义HttpClient 设置CookieStore
			CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
			HttpPost            request    = new HttpPost(orgKoalaInfoVo.getKoalaAuthUrl() + "/subject/photo");
			// 设置底库照片 并关联到用户
			MultipartEntity reqEntity = new MultipartEntity();
			String          photo     = paramMap.get("photo") + "";
			reqEntity.addPart("photo", new FileBody(new File(photo)));
			request.setEntity(reqEntity);
			CloseableHttpResponse response     = httpclient.execute(request);
			String                responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
			// 解析JSON数据
			JSONObject resp   = new JSONObject(responseBody);
			int        result = resp.optInt("code", -1);
			if (result != 0) {
				log.info("code:" + result + ",desc:" + resp.getString("desc"));
			} else {
				JSONObject data = resp.getJSONObject("data");
				return data.getInt("id");
			}
		} catch (HttpClientErrorException httpClientErrorException) {
			log.error("httpClientErrorException 异常，错误信息：" + httpClientErrorException.getMessage());
		} catch (Exception e) {
			log.error("Exception 异常，错误信息：" + e.getMessage());
		}
		return null;
	}

	/**
	 * 上传识别底库
	 *
	 * @param paramMap[photo(完整的本地图片路径)]
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
	public static Map<String, Object> photos(String photo, CookieStore cookieStore,OrgKoalaInfoVo orgKoalaInfoVo) throws Exception {
		log.info("调起上传识别照片（/subject/photo）接口  请求方式post 上传识别照片 ...");
		Map<String, Object> map = new HashMap<String, Object>();;
		map.put("code", 500);
		map.put("desc", "没有检测到人脸！");
		try {
			
			
			//Integer  orgId = (Integer) paramMap.get("orgId");
			//OrgKoalaInfoVo orgKoalaInfoVo = getOrgKoalaInfoVoByOrgId(orgId);
			//因一个小时 token 会失效 不能用定时任务 要校验token 是否失效 不如每次登录
	        //CookieStore cookieStore = authLogin(orgKoalaInfoVo.getKoalaAuthUrl(),orgKoalaInfoVo.getKoalaUserName(),orgKoalaInfoVo.getKoalaUserPwd());
			
			
			// 自定义HttpClient 设置CookieStore
			CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
			HttpPost            request    = new HttpPost(orgKoalaInfoVo.getKoalaAuthUrl() + "/subject/photo");
			// 设置底库照片 并关联到用户
			MultipartEntity reqEntity = new MultipartEntity();
			log.info("imageUrl=" + photo);
			reqEntity.addPart("photo", new FileBody(new File(photo)));
			request.setEntity(reqEntity);
			CloseableHttpResponse response     = httpclient.execute(request);
			String                responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
			log.info("responseBody:responseBody:responseBody=" + responseBody);
			// 解析JSON数据
			JSONObject resp   = new JSONObject(responseBody);
			int        result = resp.optInt("code", -1);
			if (result != 0) {
				log.info("===>上传koala图片返回 code:" + result + ",desc:" + resp.getString("desc"));
				
				map.put("code", 500);
				map.put("desc", resp.getString("desc"));
			} else {
				//map = new HashMap<String, Object>();
				JSONObject data = resp.getJSONObject("data");
				map.put("code", 200);
				map.put("id", data.getInt("id"));
				map.put("url", data.getString("url"));
				return map;
			}
		} catch (HttpClientErrorException httpClientErrorException) {
			log.error("httpClientErrorException 异常，错误信息：" + httpClientErrorException.getMessage());
		} catch (Exception e) {
			log.error("Exception 异常，错误信息：" + e.getMessage());
		}
		return null;
	}

	/**
	 * 验证图片是否是人脸
	 *
	 * @param imageUrl 图片完整路径
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 * @throws JSONException
	 */
	@SuppressWarnings("deprecation")
	public static boolean extract(String imageUrl) throws ParseException, IOException, JSONException {
		log.info("调起验证上传图片是否是人脸接口  (/extract) 请求方式post 调用验证图片 ...");
		try {
			CloseableHttpClient httpclient = HttpClients.createDefault();
			HttpPost            request    = new HttpPost(Constants.FACE_PLUS_CLIENT_IMAGE_URL + "extract");
			MultipartEntity     reqEntity  = new MultipartEntity();
			log.info("imageUrl=" + imageUrl);
			reqEntity.addPart("image", new FileBody(new File(imageUrl)));
			request.setEntity(reqEntity);
			CloseableHttpResponse response     = httpclient.execute(request);
			String                responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
			log.info("responseBody:responseBody:responseBody=" + responseBody);
			if (StringUtils.isBlank(responseBody)) {
				return false;
			} else {
				JSONObject resp = new JSONObject(responseBody);
				double     num  = resp.getDouble("quality");
				log.info("quality:=" + Double.valueOf(num));
				if (num < 0.5) {
					return false;
				}
				return true;
			}
		} catch (ParseException parseException) {
			log.error("ParseException 异常，错误信息：" + parseException.getMessage());

		} catch (IOException ioException) {
			log.error("IOException 异常，错误信息：" + ioException.getMessage());
		} catch (JSONException jsonException) {
			log.error("JSONException 异常，错误信息：" + jsonException.getMessage());
		}
		return false;
	}

	/**
	 * 更新门禁信息
	 *
	 * @param paramMap[ids[] 需要更新的访客用户ID数组,allow_visitor(boolean值 true为有效,false 为无效)]
	 * @return
	 * @throws JSONException
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static boolean screen(Map<String, Object> paramMap, CookieStore cookieStore) throws JSONException, ClientProtocolException, IOException {
		log.info("Start PUT /system/screen/[id] 更新门禁信息 ...");
		try {
			CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
			String              doorId     = paramMap.get("doorId") + "";
			HttpPut             request    = new HttpPut(Constants.FACE_PLUS_CLIENT_URL + "/system/screen/" + doorId);
			request.setHeader("Content-Type", "application/json");
			boolean    allowVisitor = (Boolean) paramMap.get("allowVisitor");
			int        ids[]        = (int[]) paramMap.get("ids");
			JSONObject json         = new JSONObject();
			json.put("allow_visitor", allowVisitor);
			json.put("allowed_subject_ids", ids);
			request.setEntity(new StringEntity(json.toString(), "UTF-8"));
			CloseableHttpResponse response     = httpclient.execute(request);
			String                responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
			//解析JSON数据
			JSONObject resp   = new JSONObject(responseBody);
			int        result = resp.optInt("code", -1);
			if (result != 0) {
				return false;
			} else {
				return true;
			}
		} catch (JSONException jsonException) {
			log.error("JSONException 异常，错误信息：" + jsonException.getMessage());
		} catch (ClientProtocolException clientProtocolException) {
			log.error("ClientProtocolException 异常，错误信息：" + clientProtocolException.getMessage());
		} catch (IOException ioException) {
			log.error("IOException 异常，错误信息：" + ioException.getMessage());
		}
		return false;
	}

	
	
	/**
	 * 历史记录遍历接口 
	 */
	public static JSONObject scan(Map<String, Object> paramMap, CookieStore cookieStore) throws JSONException, ClientProtocolException, IOException {
		log.info("Start PUT /event/scan 历史记录遍历接口 ...");
		JSONObject map = null;
		try {
			
			CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
			HttpPost             request    = new HttpPost(Constants.KOALOA_PLUS_URL + "/event/scan");
			request.setHeader("Content-Type", "application/json");
			JSONObject json         = new JSONObject();
			json.put("limit", 1000);
			if(null!=paramMap && paramMap.containsKey("cursor")){
				json.put("cursor", (String)paramMap.get("cursor"));
			}
			//json.put("cursor", "a29hbGFfLTFfLTFfMg==");
			request.setEntity(new StringEntity(json.toString(), "UTF-8"));
			CloseableHttpResponse response     = httpclient.execute(request);
			String                responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
			JSONObject resp   = new JSONObject(responseBody);
			int        result = resp.optInt("code", -1);
			if (result != 0) {
				log.info("code:" + result + ",desc:" + resp.getString("desc"));
			} else {
				JSONObject data = resp.getJSONObject("data");
				return data;
			}
		} catch (JSONException jsonException) {
			log.error("JSONException 异常，错误信息：" + jsonException.getMessage());
		} catch (ClientProtocolException clientProtocolException) {
			log.error("ClientProtocolException 异常，错误信息：" + clientProtocolException.getMessage());
		} catch (IOException ioException) {
			log.error("IOException 异常，错误信息：" + ioException.getMessage());
		}
		return map;
	}
	
	
	
	/**
     * 登录 获取cookie
     *
     * @return cookie
     */
    public static String checkAuthLogin(String koalaAuthUrl,String koalaUserName,String koalaUserPwd) {

        log.info("init 初始化 登录  Koala 连接:"+koalaAuthUrl+" Koala 账号：" + koalaUserName + "，密码：" + koalaUserPwd);

        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpPost request    = new HttpPost(koalaAuthUrl + "/auth/login");
            request.setHeader("User-Agent", "Koala Admin");
            request.setHeader("Content-Type", "application/json");
            JSONObject json = new JSONObject();
            json.put("username", koalaUserName);
            json.put("password", koalaUserPwd);
            request.setEntity(new StringEntity(json.toString(), "UTF-8"));
            HttpClientContext context      = HttpClientContext.create();
            CloseableHttpResponse response     = httpclient.execute(request, context);
            String                responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
            // 解析JSON数据
            JSONObject resp   = new JSONObject(responseBody);
            int        result = resp.optInt("code", -1);
            if (result != 0) {
                return resp.getString("desc");
            }
        } catch (Exception e) {
            log.error("Login error, code:" + e.getMessage());
            return "koala帐号错误";
        }
        return "";
    }
	
	public static void main(String[] args) throws Exception {
		
		
		String str = checkAuthLogin("http://skaola.superdesk.cn:8888 ","admin@megvii.com","3");
		System.out.println(str);
		
		/*CookieStore         cookieStore = authLogin("qingzhangyin@avic-s.com", "Ac123456");

		JSONObject map = scan(null,cookieStore);
		
		System.out.println(map.toString());
		JSONArray eventsJSONArray =  (JSONArray)map.get("events");
		for(int i=0;i<eventsJSONArray.length();i++){
			JSONObject obj = eventsJSONArray.getJSONObject(i);
			String name = obj.getString("name");
			String camera_position = obj.getString("camera_position");//设备名称
			String subject_type = obj.getString("subject_type");//subject_tpe: 人员类型: 0:员工，1:访客(此接口包含vip)，2:vip访客， 3:黄名单，100:陌生人		
		}*/
		
		
	}

}
