package org.springblade.openinterface.facedevice.qinlin.util;

import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springblade.community.accessrecord.service.IAccessRecordService;
import org.springblade.core.tool.api.R;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.smartapplication.smartmonitor.constant.ZHConstant;
import org.springblade.third.doordevice.dto.DeviceDTO;
import org.springblade.third.doordevice.dto.UserDeviceDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.concurrent.TimeUnit;


/**
 * @author zwx
 * @create 2020/12/16 1:52
 */
@Slf4j
@Component
public class ZHHttpUtil {

	@Autowired
	private RedisTemplate<String,String> redisTemplate;
	private final static String ZH_DEVICE_INSTRUCT_COMMAND_SEQ = "zh:device:instruct:commonSeq";
	@Autowired
	private IAccessRecordService accessRecordService;

    /**
     *  新增用户
     *   新增用户
     * @return
     */
    public R addUser(UserDeviceDTO userDeviceDTO){
		List<DeviceDTO> deviceList = userDeviceDTO.getDeviceList();
		log.info("===============下发的设备序列号=========================");
		log.info(JSONUtil.toJsonStr(deviceList));
		for (DeviceDTO deviceDTO : deviceList){
			log.info("===============正在下发的设备序列号=========================");
			log.info(deviceDTO.getSerialNum());
			String serialNum = deviceDTO.getSerialNum();
			HashOperations<String, String, String> hashOperations = this.redisTemplate.opsForHash();
			String num = hashOperations.get(ZH_DEVICE_INSTRUCT_COMMAND_SEQ, serialNum);
			Integer commonSeq = 10;
			if(StringUtil.hasText(num)){
				commonSeq = Integer.parseInt(num) + 1;
				num = commonSeq + "";
			}else{
				num = "10"; //设备指令的commonSeq从10开始
			}
			JSONObject request = new JSONObject();
			JSONObject data = new JSONObject();
			JSONArray list = new JSONArray();
			JSONObject listData = new JSONObject();
			listData.put("Name", userDeviceDTO.getUserName());
			listData.put("FaceId", userDeviceDTO.getUserId());
			listData.put("Enable", 1);
			listData.put("StartTime", userDeviceDTO.getStartTime());
			listData.put("EndTime", userDeviceDTO.getEndTime());
			listData.put("ScheduleType", 0);
			listData.put("WiegandAssignType", 0);
			try {
				URL url = null;
				url = new URL(userDeviceDTO.getUserFaceUrl());
				URLConnection connection = url.openConnection();
				InputStream inputStream = connection.getInputStream();
				byte[] imageBytes = IoUtil.readBytes(inputStream);
				String base64 = Base64Utils.encodeToString(imageBytes);
				listData.put("FaceData", base64);
			} catch (Exception e) {
				e.printStackTrace();
				return R.fail(e.getMessage());
			}
			list.add(listData);
			data.put("List", list);
			data.put("TargetName", "defaultwhitelist");
			request.put("Data", data);
			request.put("Type", ZHConstant.I8H.add_user_face.getType());
			request.put("Command", ZHConstant.I8H.add_user_face.getCommand());
			request.put("CommandSeq", commonSeq);
			//设备指令commonSeq计数更新
			this.redisTemplate.opsForHash().put(ZH_DEVICE_INSTRUCT_COMMAND_SEQ, serialNum, num);
			//设备指令Data更新
			String listName = serialNum + "_list";
			this.redisTemplate.opsForList().leftPush(listName, request.toJSONString());
		}
		return R.status(true);
    }

	/**
	 * 远程开门
	 * @param serialNum
	 * @param isOpen
	 * @return
	 */
	public R remoteOpenDoor(Long userId, Integer userType, String serialNum, boolean isOpen){
		HashOperations<String, String, String> hashOperations = this.redisTemplate.opsForHash();
		String num = hashOperations.get(ZH_DEVICE_INSTRUCT_COMMAND_SEQ, serialNum);
		Integer commonSeq = 10;
		if(StringUtil.hasText(num)){
			commonSeq = Integer.parseInt(num) + 1;
			num = commonSeq + "";
		}else{
			num = "10"; //设备指令的commonSeq从10开始
		}
		JSONObject request = new JSONObject();
		JSONObject data = new JSONObject();
		if(isOpen){
			data.put("WorkState", 0);
		}else{
			data.put("WorkState", 1);
		}
		request.put("Command", ZHConstant.I8H.open_door.getCommand());
		request.put("CommandSeq", commonSeq);
		request.put("Type", ZHConstant.I8H.open_door.getType());
		request.put("Data", data);
		accessRecordService.generateAccessRecord(serialNum, userId, null, userType, 2, 1, null, String.valueOf(commonSeq), null, new Date());
		//设备指令commonSeq计数更新
		this.redisTemplate.opsForHash().put(ZH_DEVICE_INSTRUCT_COMMAND_SEQ, serialNum, num);
		//设备指令Data更新
		String listName = serialNum + "_openDoor";
		this.redisTemplate.opsForList().leftPush(listName, request.toJSONString());
		this.redisTemplate.expire(listName, 1L, TimeUnit.MINUTES);
		return R.status(true);
	}

	public R deleteUser(UserDeviceDTO userDeviceDTO, String serialNum) {
		HashOperations<String, String, String> hashOperations = this.redisTemplate.opsForHash();
		String num = hashOperations.get(ZH_DEVICE_INSTRUCT_COMMAND_SEQ, serialNum);
		Integer commonSeq = 10;
		if(StringUtil.hasText(num)){
			commonSeq = Integer.parseInt(num) + 1;
			num = commonSeq + "";
		}else{
			num = "10"; //设备指令的commonSeq从10开始
		}
		JSONObject request = new JSONObject();
		JSONObject data = new JSONObject();
		data.put("FaceId", userDeviceDTO.getUserId());
		request.put("Data", data);
		request.put("Type", ZHConstant.I8H.delete_user_face.getType());
		request.put("Command", ZHConstant.I8H.delete_user_face.getCommand());
		request.put("CommandSeq", commonSeq);
		//设备指令commonSeq计数更新
		this.redisTemplate.opsForHash().put(ZH_DEVICE_INSTRUCT_COMMAND_SEQ, serialNum, num);
		//设备指令Data更新
		String listName = serialNum + "_list";
		this.redisTemplate.opsForList().leftPush(listName, request.toJSONString());
		return R.status(true);
	}

}
