package org.springblade.third.doordevice.provider.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springblade.common.constant.CommonConstant;
import org.springblade.community.feign.*;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.device.entity.DoorDevice;
import org.springblade.estate.feign.IAuthorizeRecordsClient;
import org.springblade.third.constants.ZHConstant;
import org.springblade.third.doordevice.dto.UserDeviceDTO;
import org.springblade.third.doordevice.provider.IDoorDeviceService;
import org.springblade.third.dto.DeviceDTO;
import org.springblade.utils.OssUtil;
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.Service;
import org.springframework.util.StringUtils;

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

/**
 * @author lidexi
 * @date 2021/5/24 17:28
 */
@Service
public class ZHProvider implements IDoorDeviceService {

	@Autowired
	private OssUtil ossUtil;
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	private final static String ZH_DEVICE_INSTRUCT_COMMAND_SEQ = "zh:device:instruct:commonSeq";
	@Autowired
	private IAuthorizeRecordsClient authorizeRecordsClient;

	@Override
	public R addDevice(DoorDevice doorDevice) {
		return null;
	}

	@Override
	public R deleteDevice(DoorDevice doorDevice) {
		return null;
	}

	@Override
	public R pushUserToDevices(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();
		JSONArray list = new JSONArray();
		JSONObject listData = new JSONObject();
		listData.put("Name", userDeviceDTO.getUserName());
		listData.put("FaceId", userDeviceDTO.getUserType() + userDeviceDTO.getUserId());
		listData.put("Enable", 1);
		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();
			String base64 = ossUtil.getImagesBase64(inputStream);
			listData.put("FaceData", base64);
		} catch (Exception e) {
			e.printStackTrace();
			return R.fail(e.getMessage());
		}
		if(userDeviceDTO.getTargetType().intValue() == 1){ //白名单
			data.put("TargetName", "defaultwhitelist");
		}else if(userDeviceDTO.getTargetType().intValue() == 2){ //访客名单
			data.put("TargetName", "defaultvisitlist");
			listData.put("StartTime", userDeviceDTO.getStartTime());
			listData.put("EndTime", userDeviceDTO.getEndTime());
		}else if(userDeviceDTO.getTargetType().intValue() == 3){ //黑名单
			data.put("TargetName", "defaultblacklist");
		}
		list.add(listData);
		data.put("List", list);
		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());
		authorizeRecordsClient.generateAuthRecord(serialNum, userDeviceDTO.getUserId(), userDeviceDTO.getUserName(), userDeviceDTO.getUserType(), num, ZHConstant.I8H.add_user_face.getDesc(),
			JSONObject.toJSONString(userDeviceDTO), CommonConstant.SmartDeviceType.DOOR_DEVICE.getValue(), null, userDeviceDTO.getTenantId());
		return R.status(true);
	}

	public R pushUpdateUserToDevices(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();
		JSONArray list = new JSONArray();
		JSONObject listData = new JSONObject();
		listData.put("Name", userDeviceDTO.getUserName());
		listData.put("SrcFaceId", userDeviceDTO.getUserType() + userDeviceDTO.getUserId());
		listData.put("FaceId", userDeviceDTO.getUserType() + userDeviceDTO.getUserId());
		listData.put("NeedModifyFacePic", 1); //1表示允许修改图片，0表示不修改图片
		listData.put("Enable", 1);
		try {
			URL url = null;
			url = new URL(userDeviceDTO.getUserFaceUrl());
			URLConnection connection = url.openConnection();
			InputStream inputStream = connection.getInputStream();
			String base64 = ossUtil.getImagesBase64(inputStream);
			listData.put("FaceData", base64);
		} catch (Exception e) {
			e.printStackTrace();
			return R.fail(e.getMessage());
		}
		if(userDeviceDTO.getTargetType().intValue() == 1){ //白名单
			data.put("TargetName", "defaultwhitelist");
		}else if(userDeviceDTO.getTargetType().intValue() == 2){ //访客名单
			data.put("TargetName", "defaultvisitlist");
			listData.put("StartTime", userDeviceDTO.getStartTime());
			listData.put("EndTime", userDeviceDTO.getEndTime());
		}else if(userDeviceDTO.getTargetType().intValue() == 3){ //访客名单
			data.put("TargetName", "defaultblacklist");
		}
		list.add(listData);
		data.put("List", list);
		request.put("Data", data);
		request.put("Type", ZHConstant.I8H.update_user_face.getType());
		request.put("Command", ZHConstant.I8H.update_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());
		authorizeRecordsClient.generateAuthRecord(serialNum, userDeviceDTO.getUserId(), userDeviceDTO.getUserName(), userDeviceDTO.getUserType(), num, ZHConstant.I8H.update_user_face.getDesc(),
			JSONObject.toJSONString(userDeviceDTO), CommonConstant.SmartDeviceType.DOOR_DEVICE.getValue(), null, userDeviceDTO.getTenantId());
		return R.status(true);
	}

	@Override
	public R deleteUserToDevices(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.getUserType() + 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());
		authorizeRecordsClient.generateAuthRecord(serialNum, userDeviceDTO.getUserId(), userDeviceDTO.getUserName(), userDeviceDTO.getUserType(), num, ZHConstant.I8H.delete_user_face.getDesc(),
			JSONObject.toJSONString(userDeviceDTO), CommonConstant.SmartDeviceType.DOOR_DEVICE.getValue(), null, userDeviceDTO.getTenantId());
		return R.status(true);
	}

	@Override
	public R remoteOpenDoor(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);
		//设备指令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);
	}
}
