package org.springblade.openinterface.facedevice.jvt.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.community.accessrecord.entity.AccessRecord;
import org.springblade.community.accessrecord.service.IAccessRecordService;
import org.springblade.community.agency.entity.Agency;
import org.springblade.community.agency.service.IAgencyService;
import org.springblade.community.houseuser.entity.Houseuser;
import org.springblade.community.houseuser.service.IHouseuserService;
import org.springblade.community.residential.entity.Residential;
import org.springblade.community.residential.service.IResidentialService;
import org.springblade.community.staff.entity.EnterpriseStaff;
import org.springblade.community.staff.service.IEnterpriseStaffService;
import org.springblade.core.tool.jackson.JsonUtil;
import org.springblade.mq.entity.MqConf;
import org.springblade.smartapplication.facedevice.entity.FaceDevice;
import org.springblade.smartapplication.facedevice.service.IFaceDeviceService;
import org.springblade.system.tenanttype.entity.TenantType;
import org.springblade.system.tenanttype.service.ITenantTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequiredArgsConstructor
@Api(value = "巨龙门禁设备开放接口", tags = "开放接口")
public class DeviceController {

	@Autowired
	private MqConf mqConf;
	private IFaceDeviceService faceDeviceService;
	private IAgencyService agencyService;
	private ITenantTypeService tenantTypeService;
	private IHouseuserService houseuserService;
	private IEnterpriseStaffService enterpriseStaffService;
	private IResidentialService residentialService;
	private IAccessRecordService accessRecordService;

	/**
	 * 设备心跳接口
	 * @param jvtDevice
	 * @return
	 */
	@PostMapping(value = "/device/heartbeat/check")
	public Map<String, Object> heartbeat(@RequestBody Map<String, Object> jvtDevice){
		Date today = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String format = sdf.format(today);
		Map<String, Object> result = new HashMap<>();
		result.put("code", "200");
		result.put("meg", "success");
		result.put("data", format);
		return result;
	}

	/**
	 * 功能描述: 设备开机
	 * @param jvtDevice { serialNumber : 设备序列号,必填 }
	 * @return ResultBean<Device> 设备信息及队列服务器信息
	 *
	 *
	 */
	@PostMapping(value = "/device/status/start")
	public Map<String, Object> getConnection(@RequestBody Map<String, Object> jvtDevice){
		String json = JsonUtil.toJson(jvtDevice);
		JSONObject jsonObject = JSON.parseObject(json);
		String serialNumber = jsonObject.getString("serialNumber");
		String deviceModelNumber = jsonObject.getString("deviceModelNumber");
		String versionNumber = jsonObject.getString("versionNumber");
		if(StringUtils.isEmpty(serialNumber)){
			Map<String, Object> result = new HashMap<>();
			result.put("code", "400");
			result.put("msg", "序列号不能为null");
			return result;
		}else{
			Map<String, Object> result = new HashMap<>();
			Map<String, Object> device = new HashMap<>();
			result.put("code", "200");
			result.put("msg", "success");
			//  默认不启用时间策列
			device.put("timeStrategyIsEnable", 2);
			//  默认开门密码
			device.put("openDoorPwd", "000000");
			//  默认人脸识别度
			device.put("faceResolution", 75);
			device.put("serialNumber", serialNumber);
			device.put("deviceFactory", "JVT");
			device.put("deviceModelNumber", deviceModelNumber);
			device.put("versionNumber", versionNumber);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			device.put("createDate", sdf.format(new Date()));
			device.put("mqId", 1);
			Map<String, Object> mqConfig = new HashMap<>();
			mqConfig.put("host", mqConf.getHost());
			mqConfig.put("port", mqConf.getPort());
			mqConfig.put("virtual", mqConf.getVirtualHost());
			mqConfig.put("user", mqConf.getUsername());
			mqConfig.put("password", mqConf.getPassword());
			device.put("mqConf", mqConfig);
			result.put("data", device);
			return result;
		}
	}

	@PostMapping(value = "/device/instruct/callback")
	public Map<String, Object> instructCallBack(@RequestBody Map<String, Object> publishLog){
		String s = JsonUtil.toJson(publishLog);
		Map<String, Object> result = new HashMap<>();
		result.put("code", "200");
		result.put("msg","success");
		return  result;
	}

	@PostMapping(value = "/device/instruct/biz/callback")
	public Map<String, Object> instructBizCallBack(@RequestBody Map<String, Object> publishLog){
		String s = JsonUtil.toJson(publishLog);
		Map<String, Object> result = new HashMap<>();
		result.put("code", "200");
		result.put("msg","success");
		return  result;
	}

	@PostMapping(value = "/device/instruct/handle/callback")
	public Map<String, Object> instructHandleCallBack(@RequestBody Map<String, Object> publishLog){
		String s = JsonUtil.toJson(publishLog);
		Map<String, Object> result = new HashMap<>();
		result.put("code", "200");
		result.put("msg","success");
		return  result;
	}

	/**
	 * 开门记录上传
	 * @param publishLog
	 * @return
	 */
	@PostMapping(value = "/estate/open/door/log")
	public Map<String, Object> jvtOpenDoorLog(@RequestBody Map<String, Object> publishLog){
		String json = JsonUtil.toJson(publishLog);
		JSONObject jsonObject = JSON.parseObject(json);
		String serialNumber = jsonObject.getString("serialNumber");
		String userId = jsonObject.getString("userId");
		String snapshoUri = jsonObject.getString("snapshoUri");
		String openDoorType = jsonObject.getString("openDoorType");
		String accessDate = jsonObject.getString("accessDate");
		String compareUrl = jsonObject.getString("compareUrl");
		String contrast = jsonObject.getString("contrast");
		String temperature = jsonObject.getString("temperature");
		switch (openDoorType){
			case "0":
				openDoorType = "1";
				break;
			case "3":
				openDoorType = "2";
		}
		createOpenRecord(serialNumber, userId, accessDate, null, openDoorType, snapshoUri);
		Map<String, Object> result = new HashMap<>();
		result.put("code", "200");
		result.put("msg","success");
		return  result;
	}

	private void createOpenRecord(String serialNumber, String userIdStr, String accessDate, String temperature, String openType, String faceUrl){
		Long userId = Long.parseLong(userIdStr);
		FaceDevice faceDevice = this.faceDeviceService.selectByMacAddress(serialNumber);
		Long agencyId = faceDevice.getAgencyId();
		Agency agency = this.agencyService.getById(agencyId);
		TenantType tenantType = tenantTypeService.getByTenantId(agency.getTenantId());
		Integer type = tenantType.getTenantType();
		String agencyName = agency.getAgencyName();
		Long residentialId = null;
		String residentialName = null;
		Houseuser houseuser = null;
		EnterpriseStaff staff = null;
		String userName = null;
		Integer agencyType = null;
		AccessRecord accessRecord = new AccessRecord();
		if(type == 0){ //社区出入记录
			if(userId == null){
				return ;
			}else{
				houseuser = this.houseuserService.getByOldId(userId.toString().substring(3));
				userId = houseuser.getId();
			}
		}else{ //园区出入记录
			staff = this.enterpriseStaffService.getById(userId);
		}
		if(houseuser != null || staff != null){
			if(houseuser != null){
				residentialId = houseuser.getResidentialId();
				userName = houseuser.getName();
				accessRecord.setUserName(houseuser.getName());
				agencyType = 0;
			}else{
				residentialId = staff.getResidentialId();
				userName = staff.getRealName();
				agencyType = 1;
				accessRecord.setEnterpriseId(staff.getEnterpriseId());
				accessRecord.setEnterpriseName(staff.getEnterpriseName());
			}
			Residential residential = this.residentialService.getById(residentialId);
			residentialName = residential.getName();
			accessRecord.setAgencyId(agencyId);
			accessRecord.setAgencyName(agencyName);
			accessRecord.setResidentialId(residentialId);
			accessRecord.setResidentialName(residentialName);
			accessRecord.setAgencyType(agencyType);
			accessRecord.setUserId(userId);
			accessRecord.setUserName(userName);
			accessRecord.setDeviceId(faceDevice.getId());
			accessRecord.setDeviceMac(faceDevice.getMacAddress());
			accessRecord.setDeviceAddress(faceDevice.getAddress());
			accessRecord.setOpenTime(accessDate);
			accessRecord.setOpenType(openType);
			accessRecord.setTemperature(temperature);
			accessRecord.setFaceUrl(faceUrl);
			accessRecord.setOrgPosition(residential.getOrgPosition());
			accessRecord.setTenantId(residential.getTenantId());
			accessRecord.setBaseUrl(houseuser.getImageUri());
			this.accessRecordService.save(accessRecord);
		}
	}
}
