package com.palmnest.application.core.util;

import cn.superdesk.libs.common.json.JsonUtils;

import com.alibaba.fastjson.JSONObject;
import com.esotericsoftware.minlog.Log;
import com.mongodb.util.Hash;
import com.palmnest.application.dto.UserTokenDto;
import com.palmnest.model.lingling.LingLingDevice;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

import java.io.IOException;
import java.lang.reflect.Array;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author 黄笑天
 * @Description 令令开门 工具/常量 类
 * @Date 2018/12/10 19:06
 **/
public class LingLingUtil {

	private static Logger logger = LoggerFactory.getLogger(LingLingUtil.class);

	public static       String signature               = PropertiesKit.readPropertiesValue("lingling_signature", "wechat.properties");
	public static       String token                   = PropertiesKit.readPropertiesValue("lingling_token", "wechat.properties");
	public static       String openToken               = PropertiesKit.readPropertiesValue("lingling_openToken", "wechat.properties");
	public static       String preUrl                  = PropertiesKit.readPropertiesValue("lingling_url", "wechat.properties");
	
	public static       String newSignature               = PropertiesKit.readPropertiesValue("lingling_new_signature", "wechat.properties");
	public static       String newToken                   = PropertiesKit.readPropertiesValue("lingling_new_token", "wechat.properties");
	public static       String newOpenToken               = PropertiesKit.readPropertiesValue("lingling_new_openToken", "wechat.properties");
	public static       String newPreUrl                  = PropertiesKit.readPropertiesValue("lingling_new_url", "wechat.properties");
	
	public static       String lingOrgs                  = PropertiesKit.readPropertiesValue("lingling_orgs", "wechat.properties");
	
	public static       String uset_token               = PropertiesKit.readPropertiesValue("uset_token", "wechat.properties");
	public static       String uset_token_two               = PropertiesKit.readPropertiesValue("uset_token_two", "wechat.properties");
	
	public static final  String endTime="65535";
	/**
	 * 密钥（二维码加密用的 key，8 位 16 进制的字符串）
	 */
	public static final String STRKEY                  = "ABCD1234";
	
	/**
	 * 密钥（二维码加密用的 key，8 位 16 进制的字符串）
	 */
	public static final String NEWSTRKEY                  = "12341234";
	/**
	 * 业主二维码有效时间,默认1分钟
	 */
	public static final int    OWNER_QRCODE_FLUSH_TIME = 1;
	/**
	 * 二维码最大有效期 最大4095分钟
	 */
	public static final int    MAX_QECODE_ENDTIME      = 4095;
	/**
	 * 有效次数（取值 0、1；0 则不限次数，1 则只能开 1 次）
	 */
	public static final int    EFFEC_NUMBER_0          = 0;
	public static final int    EFFEC_NUMBER_1          = 1;
	/**
	 * 十次
	 */
	public static final int    EFFEC_NUMBER_10         = 10;

	/**
	 * 添加门禁卡设置最大时间
	 */
	public static final int MAX_TIME = 65535;

	/**
	 * 令令端日志回调方法名
	 */
	/**
	 * 业主二维码开门日志
	 */
	public static final String OWNER_QRCODE_OPEN   = "ownerQrcodeOpen";
	/**
	 * 访客二维码开门日志
	 */
	public static final String VISITOR_QRCODE_OPEN = "visitorQrcodeOpen";
	/**
	 * 新的业主、访客二维码开门日志
	 */
	public static final String USER_QRCODE_OPEN = "qrCodeCardLog";
	/**
	 * NFC(实体卡)开门日志
	 */
	public static final String NFC_OPEN            = "nfcOpen";
	/**
	 * 设备状态回调日志
	 */
	public static final String DEVICE_STATUS       = "deviceStatus";

	/**
	 * 日志类型业主二维码类型
	 */
	public static final int OWNER_LOG_TYPE   = 1;
	/**
	 * 日志类型访客二维码类型
	 */
	public static final int VISITOR_LOG_TYPE = 2;
	/**
	 * 日志类型NFC实体卡类型
	 */
	public static final int NFC_LOG_TYPE     = 3;
	/**
	 * 日志类型设备状态类型
	 */
	public static final int DEVICE_LOG_TYPE  = 4;

	/**
	 * 令令接口状态码
	 */
	public static final String SUCCESS           = "1";// 成功
	public static final String FAILURE           = "0";// 失败
	public static final String STATUS_CODE_10001 = "10001";// 参数不能为空
	public static final String STATUS_CODE_20002 = "20002";// 账户或密码不正确
	public static final String STATUS_CODE_90001 = "90001"; // 服务器链接出错
	
	public static final String STATUS_CODE_ERROR = "3";// 账号或密码错误
	public static final String STATUS_ACCOUNT_DEVICE_MISMATCHING = "4";// 账号和绑定的设备不匹配
	public static final String STATUS_DEVICE_NOT_Exist = "5";// 设备不存在

	/**
	 * 令令接口返回提示
	 */
	public static final String PARAM_ANALYSIS_ERROR   = "参数解析异常";
	public static final String PARAM_EMPTY_ERROR      = "参数为空";
	public static final String ACCOUNT_PASSWORD_ERROR = "账户或密码不正确";
	public static final String SERVER_ERROR           = "系统异常";
	public static final String UN_INITIALIZE_MACHINE  = "暂未初始化访客机";
	
	public static final String ACCOUNT_DEVICE_MISMATCHING  = "账号和绑定的设备不匹配";
	public static final String DEVICE_NOT_Exist  = "设备不存在";

	/**
	 * 访客机照片类型
	 */
	public static final String HEADIMG             = "headImg";// 身份证头像
	public static final String SNAPIMG             = "SnapImg";// 抓拍照片
	public static final String UPLOADPHOTO_SUCCESS = "uploadPhoto success";

	/**
	 * 处理令令请求参数信息
	 *
	 * @param map 请求参数的map
	 * @return 处理后的参数字符串
	 */
	public static String linglingParams(Map<String, ?> map,int methedType) {
		JSONObject params = new JSONObject();

		JSONObject requestParam = new JSONObject();

		if (null != map) {
			for (String str : map.keySet()) {
				requestParam.put(str, map.get(str));
			}
		}

		JSONObject header = new JSONObject();
		if(1==methedType){
			header.put("signature", signature);
			header.put("token", token);
		}else{
			header.put("signature", newSignature);
			header.put("token", newToken);
		}
		params.put("requestParam", requestParam);
		params.put("header", header);

		logger.info("LingLingUtil linglingParam =========>" + "MESSAGE=" + params.toJSONString());
		if (StringUtils.isAnyBlank(signature, token, openToken)) {
			return "";
		}

		return "MESSAGE=" + params.toJSONString();
	}
	
	/**
	 * 处理令令请求参数信息
	 *
	 * @param map 请求参数的map
	 * @return 处理后的参数字符串
	 */
	public static String linglingParam(Map<String, ?> map,String lingSignature,String lingToken,String lingOpenToken) {
		JSONObject params = new JSONObject();

		JSONObject requestParam = new JSONObject();

		if (null != map) {
			for (String str : map.keySet()) {
				requestParam.put(str, map.get(str));
			}
		}

		JSONObject header = new JSONObject();
		header.put("signature", lingSignature);
		header.put("token", lingToken);
		params.put("requestParam", requestParam);
		params.put("header", header);

		logger.info("LingLingUtil linglingParam =========>" + "MESSAGE=" + params.toJSONString());
		if (StringUtils.isAnyBlank(lingSignature, lingToken, lingOpenToken)) {
			return "";
		}

		return "MESSAGE=" + params.toJSONString();
	}


	/**
	 * 获取令令id
	 *
	 * @return
	 */
	public static String getLingLingId() {
		String url = preUrl + "/qrcode/getLingLingId/" + openToken;
		String params = LingLingUtil.linglingParams(null,1);
		if (StringUtils.isBlank(params)) {
			return "";
		}
		String result = HttpKit.HttpPost(params, url);
		logger.info("getLingLingId-result:"+result);
		if(StringUtils.isEmpty(result)){
			return "";
		}
		JSONObject object = JSONObject.parseObject(result);
		if ("1".equalsIgnoreCase((String) object.get("statusCode"))) {
			JSONObject responseResult = (JSONObject) object.get("responseResult");
			String lingLingId = responseResult.getString("lingLingId");
			return lingLingId;
		}
		return "";
	}
	
//	/**
//	 * 获取令令id
//	 *
//	 * @return
//	 */
//	public static String getLingLingId(String lingPerUrl,String lingSignature,String lingToken,String lingOpenToken) {
//		String url = lingPerUrl + "/qrcode/getLingLingId/" + lingOpenToken;
//		String params = LingLingUtil.linglingParam(null,lingSignature,lingToken,lingOpenToken);
//		if (StringUtils.isBlank(params)) {
//			return "";
//		}
//		String result = HttpKit.HttpPost(params, url);
//		JSONObject object = JSONObject.parseObject(result);
//		if ("1".equalsIgnoreCase((String) object.get("statusCode"))) {
//			JSONObject responseResult = (JSONObject) object.get("responseResult");
//			String lingLingId = responseResult.getString("lingLingId");
//			return lingLingId;
//		}
//		return "";
//	}
	
	/**
	 * 获取新的令令id
	 *
	 * @return
	 */
	public static String getNewLingLingId() {
		String lingLingId="";
		
		return lingLingId;
	}

	/**
	 * 生成开门密钥
	 */
	public static JSONObject makeSdkKey(String[] ids) {

		String url = preUrl + "/key/makeSdkKey/" + openToken;

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("deviceIds", ids);

		String params = linglingParams(map,1);

		if (StringUtils.isBlank(params)) {
			return null;
		}

		String result = HttpKit.HttpPost(params, url);
		if(StringUtils.isEmpty(result)){
			return null;
		}
		logger.info("makeSdkKey-result:"+result);
		JSONObject object = JSONObject.parseObject(result);
		if ("1".equalsIgnoreCase((String) object.get("statusCode"))) {
			JSONObject responseResult = (JSONObject) object.get("responseResult");
			return responseResult;
		}
		return null;
	}
	
//	/**
//	 * 生成开门密钥
//	 */
//	public static JSONObject makeSdkKey(String[] ids,String lingPerUrl,String lingSignature,String lingToken,String lingOpenToken) {
//
//		String url = lingPerUrl + "/key/makeSdkKey/" + lingOpenToken;
//
//		Map<String, Object> map = new HashMap<String, Object>();
//		map.put("deviceIds", ids);
//
//		String params = linglingParam(map,lingSignature,lingToken,lingOpenToken);
//
//		if (StringUtils.isBlank(params)) {
//			return null;
//		}
//
//		String result = HttpKit.HttpPost(params, url);
//		JSONObject object = JSONObject.parseObject(result);
//		if ("1".equalsIgnoreCase((String) object.get("statusCode"))) {
//			JSONObject responseResult = (JSONObject) object.get("responseResult");
//			return responseResult;
//		}
//		return null;
//	}

	/**
	 * 获取设备id字符串
	 *
	 * @param devices
	 * @return
	 */
	public static String handleDevice(Collection<LingLingDevice> devices) {

		String ids = "";
		if (devices != null && devices.size() > 0) {
			for (LingLingDevice device : devices) {
				if (device.getIsEnable() == 1) {
					ids += device.getDeviceId() + ",";
				}
			}
		}

		return ids;
	}

	/**
	 * 获取设备名称字符串
	 *
	 * @param devices
	 * @return
	 */
	public static String getDeviceNames(Collection<LingLingDevice> devices) {

		String names = "";
		if (devices != null && devices.size() > 0) {
			for (LingLingDevice device : devices) {
				if (device.getIsEnable() == 1) {
					names += device.getDeviceName() + ",";
				}
			}
		}

		return names;
	}

	/**
	 * 访客开始时间至到访结束时间当天晚上12点之间的时间(分钟)
	 * 获取访客有效期限
	 *
	 * @param endDate
	 * @return 分钟
	 */
	public static Integer getVisitorEndTime(Date startDate, Date endDate) {

		if (startDate == null || endDate == null) {
			return 0;
		}

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(endDate);
		calendar.set(Calendar.HOUR, 23);
		calendar.set(Calendar.MINUTE, 59);
		calendar.set(Calendar.SECOND, 59);
		endDate = calendar.getTime();

		Long startTime = startDate.getTime();
		Long endTime = endDate.getTime();
		Long time = (endTime - startTime) / (60 * 1000);

		if (time > MAX_QECODE_ENDTIME) {
			return MAX_QECODE_ENDTIME;
		}
		return time.intValue();
	}

	/**
	 * 处理令令端日志回调参数信息
	 *
	 * @param request
	 * @return
	 */
	public static JSONObject handleParam(HttpServletRequest request) {

		try {
			String noticeMsg = request.getParameter("noticeMsg");
			JSONObject jsonObject = JSONObject.parseObject(noticeMsg);
			logger.info("LingLingUtil handleParam 令令回调参数处理========>params:{}", noticeMsg);
			return jsonObject;
		} catch (Exception e) {
			logger.error("LingLingUtil handleParam 令令回调参数处理异常=====>" + e.getMessage());
		}
		return null;
	}

	/**
	 * 数组去重
	 *
	 * @param array
	 * @param <T>
	 * @return
	 */
	public static <T> T[] distinct(T[] array) {
		Set<T> set = new HashSet<T>();
		if (array == null || array.length < 1) {
			return null;
		}

		for (T t : array) {
			set.add(t);
		}

		T[] newInstance = (T[]) Array.newInstance(array[0].getClass(), set.size());
		T[] result = set.toArray(newInstance);
		return result;
	}


//	/**
//	 * 生成访客二维码
//	 *
//	 * @param lingLingId 令令 ID
//	 * @param sdkkeys    控制结束时间设备的 sdkKey
//	 * @param endTime    （单位：分钟；最大支持 4095分钟）
//	 * @param startTime  开始时间（时间戳【毫秒级】）
//	 * @return
//	 * @throws Exception
//	 */
//	public static Map<String, String> createVisitorQrCode(String lingLingId,
//														  String[] sdkkeys,
//														  Integer effecNumber,
//														  Integer endTime,
//														  Long startTime) throws Exception {
//
//		try {
//			
//			String url = LingLingUtil.preUrl + "/qrcode/addVisitorQrCode/" + LingLingUtil.openToken;
//			Map<String, Object> map = new HashMap<String, Object>();
//			map.put("lingLingId", lingLingId);
//			map.put("sdkKeys", sdkkeys);
//			map.put("endTime", endTime);// 有效时间
//			map.put("strKey", LingLingUtil.STRKEY);// 密钥（二维码加密用的 key，8 位 16 进制的字符串）
//			map.put("effecNumber", effecNumber == null ? LingLingUtil.EFFEC_NUMBER_10 : effecNumber);// 访客设置10次
//			map.put("startTime", startTime);// 来访时间
//
//			String params = LingLingUtil.linglingParam(map,1);
//			if (StringUtils.isBlank(params)) {
//				logger.error("createVisitorQrCode params is null");
//				return null;
//			}
//
//			String result = HttpKit.HttpPost(params, url);
//			logger.error("createVisitorQrCode result:{}", result);
//			JSONObject object = JSONObject.parseObject(result);
//			if ("1".equalsIgnoreCase((String) object.get("statusCode"))) {
//				Map<String, String> resultMap = new HashMap<String, String>();
//				JSONObject responseResult = (JSONObject) object.get("responseResult");
//				String codeId = responseResult.getString("codeId");
//				String qrcodeKey = responseResult.getString("qrcodeKey");
//				resultMap.put("codeId", codeId);
//				resultMap.put("qrcodeKey", qrcodeKey);
//				return resultMap;
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//			logger.error("createVisitorQrCode error===>:{}", e.getMessage());
//		}
//		return null;
//	}
	
	
	/**
	 * 生成访客二维码
	 *
	 * @param lingLingId 令令 ID
	 * @param sdkkeys    控制结束时间设备的 sdkKey
	 * @param endTime    （单位：分钟；最大支持 4095分钟）
	 * @param startTime  开始时间（时间戳【毫秒级】）
	 * @return
	 * @throws Exception
	 */
	public static Map<String, String> createVisitorQrCode(String lingLingId,
														  String[] sdkkeys,
														  Integer effecNumber,
														  Integer endTime,
														  Long startTime,String lingPerUrl,String lingSignature,String lingToken,String lingOpenToken,String lingStrKey) throws Exception {

		try {
			
			String url = lingPerUrl + "/qrcode/addVisitorQrCode/" + lingOpenToken;
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("lingLingId", lingLingId);
			map.put("sdkKeys", sdkkeys);
			map.put("endTime", endTime);// 有效时间
			map.put("strKey", lingStrKey);// 密钥（二维码加密用的 key，8 位 16 进制的字符串）
			map.put("effecNumber", effecNumber == null ? LingLingUtil.EFFEC_NUMBER_10 : effecNumber);// 访客设置10次
			map.put("startTime", startTime);// 来访时间

			String params = LingLingUtil.linglingParam(map,lingSignature,lingToken,lingOpenToken);
			if (StringUtils.isBlank(params)) {
				logger.error("createVisitorQrCode params is null");
				return null;
			}

			String result = HttpKit.HttpPost(params, url);
			logger.error("createVisitorQrCode result:{}", result);
			JSONObject object = JSONObject.parseObject(result);
			if ("1".equalsIgnoreCase((String) object.get("statusCode"))) {
				Map<String, String> resultMap = new HashMap<String, String>();
				JSONObject responseResult = (JSONObject) object.get("responseResult");
				String codeId = responseResult.getString("codeId");
				String qrcodeKey = responseResult.getString("qrcodeKey");
				resultMap.put("codeId", codeId);
				resultMap.put("qrcodeKey", qrcodeKey);
				return resultMap;
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("createVisitorQrCode error===>:{}", e.getMessage());
		}
		return null;
	}
	
	
	
//	/**
//	 * 生成访客二维码
//	 *
//	 * @param lingLingId 令令 ID
//	 * @param sdkkeys    控制结束时间设备的 sdkKey
//	 * @param endTime    （单位：分钟；最大支持 4095分钟）
//	 * @param startTime  开始时间（时间戳【毫秒级】）
//	 * @return
//	 * @throws Exception
//	 */
//	public static Map<String, String> createNewVisitorQrCode(String lingLingId,Long startTime,Long endTime,Integer effecNumber,List<String> devices) throws Exception {
//
//		try {
//			
//				Map param=new HashMap();
//				param.put("cardUids", lingLingId.split(","));
//				param.put("deviceIds", devices.toArray());
//				param.put("endTime", 1);
//				param.put("cardType", 2);
//				param.put("cardFlag", 1);
//				String res=LingLingUtil.addOpenDoorCard(param);
//				if(org.apache.commons.lang3.StringUtils.isNotBlank(res)){
//					return null;
//				}
//			
//			String url = LingLingUtil.newPreUrl + "/qrcode/addQrcodeCard/" + LingLingUtil.newOpenToken;
//			Map<String, Object> map = new HashMap<String, Object>();
//			map.put("funcFlag", 0);
//			map.put("userFlag", lingLingId);
//			map.put("userType", 1);
//			
//			
//			map.put("startTime",startTime);
//			map.put("endTime", endTime);
//			map.put("strKey", LingLingUtil.NEWSTRKEY);
//			map.put("effecNumber", effecNumber==null?LingLingUtil.EFFEC_NUMBER_10:effecNumber);
//
//			String params = LingLingUtil.linglingParam(map,2);
//			if (StringUtils.isBlank(params)) {
//				logger.error("createVisitorQrCode params is null");
//				return null;
//			}
//
//			String result = HttpKit.HttpPost(params, url);
//			logger.error("createVisitorQrCode result:{}", result);
//			JSONObject object = JSONObject.parseObject(result);
//			if ("1".equalsIgnoreCase((String) object.get("statusCode"))) {
//				Map<String, String> resultMap = new HashMap<String, String>();
//				JSONObject responseResult = (JSONObject) object.get("responseResult");
//				String codeId = responseResult.getString("codeId");
//				String qrcodeKey = responseResult.getString("qrcodeKey");
//				resultMap.put("codeId", codeId);
//				resultMap.put("qrcodeKey", qrcodeKey);
//				return resultMap;
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//			logger.error("createVisitorQrCode error===>:{}", e.getMessage());
//		}
//		return null;
//	}
	
	
	/**
	 * 生成访客二维码
	 *
	 * @param lingLingId 令令 ID
	 * @param sdkkeys    控制结束时间设备的 sdkKey
	 * @param endTime    （单位：分钟；最大支持 4095分钟）
	 * @param startTime  开始时间（时间戳【毫秒级】）
	 * @return
	 * @throws Exception
	 */
	public static Map<String, String> createNewVisitorQrCode(String lingLingId,Long startTime,Long endTime,Integer effecNumber,List<String> devices,String lingPerUrl,String lingSignature,String lingToken,String lingOpenToken,String lingStrKey) throws Exception {

		try {
			
				Map param=new HashMap();
				param.put("cardUids", lingLingId.split(","));
				param.put("deviceIds", devices.toArray());
				param.put("endTime", 1);
				param.put("cardType", 2);
				param.put("cardFlag", 1);
				String res=LingLingUtil.addOpenDoorCard(param,lingPerUrl,lingSignature,lingToken,lingOpenToken,lingStrKey,2);
				if(org.apache.commons.lang3.StringUtils.isNotBlank(res)){
					return null;
				}
			
			String url = lingPerUrl + "/qrcode/addQrcodeCard/" + lingOpenToken;
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("funcFlag", 0);
			map.put("userFlag", lingLingId);
			map.put("userType", 1);
			
			
			map.put("startTime",startTime);
			map.put("endTime", endTime);
			map.put("strKey", lingStrKey);
			map.put("effecNumber", effecNumber==null?LingLingUtil.EFFEC_NUMBER_10:effecNumber);

			String params = LingLingUtil.linglingParam(map,lingSignature,lingToken,lingOpenToken);
			if (StringUtils.isBlank(params)) {
				logger.error("createVisitorQrCode params is null");
				return null;
			}

			String result = HttpKit.HttpPost(params, url);
			logger.error("createVisitorQrCode result:{}", result);
			JSONObject object = JSONObject.parseObject(result);
			if ("1".equalsIgnoreCase((String) object.get("statusCode"))) {
				Map<String, String> resultMap = new HashMap<String, String>();
				JSONObject responseResult = (JSONObject) object.get("responseResult");
				String codeId = responseResult.getString("codeId");
				String qrcodeKey = responseResult.getString("qrcodeKey");
				resultMap.put("codeId", codeId);
				resultMap.put("qrcodeKey", qrcodeKey);
				return resultMap;
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("createVisitorQrCode error===>:{}", e.getMessage());
		}
		return null;
	}
	
	public static void main(String[] args) {
//		 Calendar nowTime = Calendar.getInstance();
//		 System.out.println("当前时间-"+nowTime.getTimeInMillis());
//		  nowTime.add(Calendar.SECOND, 5);
//		  System.out.println("当前时间+5s-"+nowTime.getTimeInMillis());
//		String userToken="0bd655779f39a7e01e5cf0198e7008dd";//userToken
//		Map<String,Object> map=new HashMap<String, Object>();
//		map.put("userToken", userToken);
//		String url="https://wx.palmnest.com/super_cloud/api/organisation/wechat/front/user/getTokenInfoByUserToken";
//		String params=HttpKit.getParamString(map);
//		try {
//			String     result = HttpKit.HttpPost2(params, url,2);
////			System.out.println(result);
//			JSONObject jsonObj=JSONObject.parseObject(result);
//			if(jsonObj.containsKey("code") && 200 == jsonObj.getInteger("code") && jsonObj.containsKey("data") && null != jsonObj.getObject("data", UserTokenDto.class)){
//				UserTokenDto dto=jsonObj.getObject("data", UserTokenDto.class);
//				Integer userId=dto.getUserId();
//				System.out.println(userId);
//			}
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		List<String> list=new ArrayList<String>();
		String [] arr={"73DA0E30","419E4832","52954D31","860FCF21","43EFEF30","86358D21","41CDAB32","8275C61E","734D4D30","73BC4F30","41714132","8651E621","52DFE831","72CB481E","864D7321","82CACE1E","7673FD21","7664FD21","41A5DA32","627CB531","62730F31","73DDD630","52CF1931","53D2A430","92D19B1E","82E2AB1E","921C831E","76B56121","52B20D31","5106DC32","B322F421","76EAC321","76FC4221","51210C32","76559E21","53096F30","76737C21"};
		System.out.println(arr.length);
		for(int i=0;i<arr.length;i++){
			if(list.contains(arr[i])){
				continue;
			}
			list.add(arr[i]);
		}
		System.out.println(JsonUtils.toJson(list));
		System.out.println(list.size());
		
	}
	
	

/**
 * 产生numSize位16进制随机数
 *
 * @param numSize
 * @return java.lang.String
 * @author zxzhang
 * @date 2019/11/9
 */
public static String getRandomValue(int numSize) {
    String str = "";
    for (int i = 0; i < numSize; i++) {
        char temp = 0;
        int key = (int) (Math.random() * 2);
        switch (key) {
            case 0:
                temp = (char) (Math.random() * 10 + 48);//产生随机数字
                break;
            case 1:
                temp = (char) (Math.random() * 6 + 'a');//产生a-f
                break;
            default:
                break;
        }
        str = str + temp;
    }
    return str.toUpperCase();
}

///**
// * 添加门禁卡
// * @param param
// * @return
// */
//	public static String addOpenDoorCard(Map param){
//			try {
//				String str=LingLingUtil.delOpenDoorCard(param);
//				if(StringUtils.isNotBlank(str)){
//					return str;
//				}
//				String url = LingLingUtil.newPreUrl + "/openDoorCard/addOpenDoorCard/" + LingLingUtil.newOpenToken;
//				logger.info("addOpenDoorCard url===>:{}",url);
//				String params = LingLingUtil.linglingParam(param,2);
//				if (StringUtils.isBlank(params)) {
//					logger.error("addOpenDoorCard params is null");
//					return "添加门禁卡失败:参数为空";
//				}
//				logger.info("addOpenDoorCard params:{}",JsonUtils.toJson(params));
//				String result = HttpKit.HttpPost(params, url);
//				logger.info("addOpenDoorCard result:{}", result);
//				JSONObject object = JSONObject.parseObject(result);
//				if ("1".equalsIgnoreCase((String) object.get("statusCode"))) {
//					return "";
//				}else{
////					JSONObject responseResult = (JSONObject) object.get("responseResult");
//					logger.error("addOpenDoorCard error===>:{}", JsonUtils.toJson(object.get("responseResult")));
//					return "添加门禁卡失败:"+JsonUtils.toJson(object.get("responseResult"));
//				}
//			} catch (Exception e) {
//				e.printStackTrace();
//				logger.error("addOpenDoorCard error===>:{}", e.getMessage());
//				return "添加门禁卡失败:"+e.getMessage();
//			}
//	}


	public static String updateOpenDoorCard(Map param,String lingPerUrl,String lingSignature,String lingToken,String lingOpenToken,String lingStrKey){
		try {
			logger.info("updateOpenDoorCard-param:{}",JsonUtils.toJson(param));
			logger.info("updateOpenDoorCard-lingPerUrl:{}",JsonUtils.toJson(lingPerUrl));
			logger.info("updateOpenDoorCard-lingSignature:{}",JsonUtils.toJson(lingSignature));
			logger.info("updateOpenDoorCard-lingToken:{}",JsonUtils.toJson(lingToken));
			logger.info("updateOpenDoorCard-lingOpenToken:{}",JsonUtils.toJson(lingOpenToken));
			logger.info("updateOpenDoorCard-lingStrKey:{}",JsonUtils.toJson(lingStrKey));
			String url = lingPerUrl + "/openDoorCard/updateOpenDoorCard/" + lingOpenToken;
			logger.info("updateOpenDoorCard url===>:{}",url);
			String params = LingLingUtil.linglingParam(param,lingSignature,lingToken,lingOpenToken);
			if (StringUtils.isBlank(params)) {
				logger.error("updateOpenDoorCard params is null");
				return "添加门禁卡失败:参数为空";
			}
			logger.info("updateOpenDoorCard params:{}",JsonUtils.toJson(params));
			String result = HttpKit.HttpPost(params, url);
			logger.info("updateOpenDoorCard result:{}", result);
			JSONObject object = JSONObject.parseObject(result);
			if ("1".equalsIgnoreCase((String) object.get("statusCode"))) {
				return "";
			}else{
//				JSONObject responseResult = (JSONObject) object.get("responseResult");
				logger.error("updateOpenDoorCard error===>:{}", JsonUtils.toJson(object.get("responseResult")));
				return "修改门禁卡失败:"+JsonUtils.toJson(object.get("responseResult"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("updateOpenDoorCard error===>:{}", e.getMessage());
			return "修改门禁卡失败:"+e.getMessage();
		}
	}
		

/**
 * 添加门禁卡
 * @param param
 * @return
 */
	public static String addOpenDoorCard(Map param,String lingPerUrl,String lingSignature,String lingToken,String lingOpenToken,String lingStrKey,int cardType){
		String res="";
			try {
				logger.info("addOpenDoorCard-param:{}",JsonUtils.toJson(param));
				logger.info("addOpenDoorCard-lingPerUrl:{}",JsonUtils.toJson(lingPerUrl));
				logger.info("addOpenDoorCard-lingSignature:{}",JsonUtils.toJson(lingSignature));
				logger.info("addOpenDoorCard-lingToken:{}",JsonUtils.toJson(lingToken));
				logger.info("addOpenDoorCard-lingOpenToken:{}",JsonUtils.toJson(lingOpenToken));
				logger.info("addOpenDoorCard-lingStrKey:{}",JsonUtils.toJson(lingStrKey));
				if(1 == cardType){
					//已有卡的权限操作
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("cardUids", param.get("cardUids"));
					map.put("newDeviceIds", param.get("deviceIds"));
					map.put("newEndTime",LingLingUtil.endTime);
					res=LingLingUtil.updateOpenDoorCard(map, lingPerUrl, lingSignature, lingToken, lingOpenToken, lingStrKey);
					if(StringUtils.isNotEmpty(res)){
						return res;
					}else{
						return "";
					}
				}else{
					res=LingLingUtil.delOpenDoorCard(param,lingPerUrl,lingSignature,lingToken,lingOpenToken,lingStrKey);
					if(StringUtils.isNotEmpty(res)){
						return res;
					}
					
					String url = lingPerUrl + "/openDoorCard/addOpenDoorCard/" + lingOpenToken;
					logger.info("addOpenDoorCard url===>:{}",url);
					String params = LingLingUtil.linglingParam(param,lingSignature,lingToken,lingOpenToken);
					if (StringUtils.isBlank(params)) {
						logger.error("addOpenDoorCard params is null");
						return "添加门禁卡失败:参数为空";
					}
					logger.info("addOpenDoorCard params:{}",JsonUtils.toJson(params));
					String result = HttpKit.HttpPost(params, url);
					logger.info("addOpenDoorCard result:{}", result);
					JSONObject object = JSONObject.parseObject(result);
					if ("1".equalsIgnoreCase((String) object.get("statusCode"))) {
						return "";
					}else{
//						JSONObject responseResult = (JSONObject) object.get("responseResult");
						logger.error("addOpenDoorCard error===>:{}", JsonUtils.toJson(object.get("responseResult")));
						return "添加门禁卡失败:"+JsonUtils.toJson(object.get("responseResult"));
					}
				}
				
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("addOpenDoorCard error===>:{}", e.getMessage());
				return "添加门禁卡失败:"+e.getMessage();
			}
	}
	
	
	
//	public static String delOpenDoorCard(Map param){
//			try {
//				String url = LingLingUtil.newPreUrl + "/openDoorCard/delOpenDoorCard/" + LingLingUtil.newOpenToken;
//				logger.info("delOpenDoorCard url===>:{}",url);
//				String params = LingLingUtil.linglingParam(param,2);
//				if (StringUtils.isBlank(params)) {
//					logger.error("delOpenDoorCard params is null");
//					return "删除门禁卡失败:参数为空";
//				}
//
//				String result = HttpKit.HttpPost(params, url);
//				logger.error("delOpenDoorCard result:{}", result);
//				JSONObject object = JSONObject.parseObject(result);
//				if ("1".equalsIgnoreCase((String) object.get("statusCode"))) {
//					return "";
//				}else{
////					JSONObject responseResult = (JSONObject) object.get("responseResult");
//					logger.error("delOpenDoorCard error===>:{}", JsonUtils.toJson(object.get("responseResult")));
//					return "删除门禁卡失败:"+JsonUtils.toJson(object.get("responseResult"));
//				}
//			} catch (Exception e) {
//				e.printStackTrace();
//				logger.error("delOpenDoorCard error===>:{}", e.getMessage());
//				return "删除门禁卡失败:"+e.getMessage();
//			}
//	}
	
	
	public static String delOpenDoorCard(Map param,String lingPerUrl,String lingSignature,String lingToken,String lingOpenToken,String lingStrKey){
		try {
			String url = lingPerUrl + "/openDoorCard/delOpenDoorCard/" + lingOpenToken;
			logger.info("delOpenDoorCard url===>:{}",url);
			String params = LingLingUtil.linglingParam(param,lingSignature,lingToken,lingOpenToken);
			if (StringUtils.isBlank(params)) {
				logger.error("delOpenDoorCard params is null");
				return "删除门禁卡失败:参数为空";
			}

			String result = HttpKit.HttpPost(params, url);
			logger.error("delOpenDoorCard result:{}", result);
			JSONObject object = JSONObject.parseObject(result);
			if ("1".equalsIgnoreCase((String) object.get("statusCode"))) {
				return "";
			}else{
//				JSONObject responseResult = (JSONObject) object.get("responseResult");
				logger.error("delOpenDoorCard error===>:{}", JsonUtils.toJson(object.get("responseResult")));
				return "删除门禁卡失败:"+JsonUtils.toJson(object.get("responseResult"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("delOpenDoorCard error===>:{}", e.getMessage());
			return "删除门禁卡失败:"+e.getMessage();
		}
}
}
