package org.springblade.openinterface.nrtms.handler;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.enterprise.entity.Enterprise;
import org.springblade.community.enterprise.service.IEnterpriseService;
import org.springblade.community.houseuser.entity.Houseuser;
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.oss.model.BladeFile;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.estate.guest.entity.Guest;
import org.springblade.estate.guest.service.IGuestService;
import org.springblade.openinterface.nrtms.beans.FaceCompareInfo;
import org.springblade.smartapplication.facedevice.entity.FaceDevice;
import org.springblade.smartapplication.facedevice.service.IFaceDeviceService;
import org.springblade.smartapplication.smartmonitor.entity.SmartVideoMonitor;
import org.springblade.smartapplication.smartmonitor.entity.SmartVideoMonitorRecord;
import org.springblade.smartapplication.smartmonitor.entity.SmartVideoMonitorStat;
import org.springblade.smartapplication.smartmonitor.service.ISmartVideoMonitorRecordService;
import org.springblade.smartapplication.smartmonitor.service.ISmartVideoMonitorService;
import org.springblade.smartapplication.smartmonitor.service.ISmartVideoMonitorStatService;
import org.springblade.system.tenanttype.entity.TenantType;
import org.springblade.system.tenanttype.service.ITenantTypeService;
import org.springblade.utils.UploadController1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
public class NrtmsEventHandler {

	@Autowired
	private ISmartVideoMonitorRecordService smartVideoMonitorRecordService;
	@Autowired
	private ISmartVideoMonitorStatService smartVideoMonitorStatService;
	@Autowired
	private ISmartVideoMonitorService smartVideoMonitorService;
	@Autowired
	private UploadController1 uploadController;
	@Autowired
	private IFaceDeviceService faceDeviceService;
	@Autowired
	private IAgencyService agencyService;
	@Autowired
	private IResidentialService residentialService;
	@Autowired
	private ITenantTypeService tenantTypeService;
	@Autowired
	private IGuestService guestService;
	@Autowired
	private IEnterpriseStaffService enterpriseStaffService;
	@Autowired
	private IAccessRecordService accessRecordService;
	@Autowired
	private IEnterpriseService enterpriseService;

	public void handleEvent(Map<String, Object> eventMap, List<MultipartFile> file){
		JSONObject eventInfo = JSONUtil.parseObj(eventMap);
		String eventType = eventInfo.getStr("EventType");
		switch (eventType){
			case "CounterWire":
				counterWireStat(eventInfo);
			case "FaceCompare":
				faceCompare(eventInfo, file);
		}
	}

	public R handleOpenDoorRecord(String serialNum, Integer commandSeq, com.alibaba.fastjson.JSONObject requestData){
		AccessRecord accessRecord = accessRecordService.getByCommandSeq(serialNum, String.valueOf(commandSeq));
		if(accessRecord != null){
			com.alibaba.fastjson.JSONObject data = requestData.getJSONObject("Data");
			Integer result = data.getInteger("Result");
			if(result != null){
				if(result == 0){
					accessRecord.setOpenSuccess(1);
				}else{
					accessRecord.setOpenSuccess(-1);
//				accessRecord.setFailReason(resultMsg);
				}
				boolean update = accessRecordService.updateById(accessRecord);
			}
			return R.status(true);
		}else{
			return R.status(true);
		}
	}

	/*{
		"LocalTime": "20210902T203715+08",
		"EventType": "CounterWire",
		"DevType": "IPC",
		"Channel": 1,
		"OverallImgInfo": {
		"h": 1080,
			"w": 1920,
			"ImgName": "BackGroundImage.jpg"
	},
		"SerialNum": "02f401237486655f21c8",
		"CounterWireInfo": {
		"List": [{
			"DetectInfo": {
				"EnterCnt": 1,
					"LeaveCnt": 0
			},
			"TotalInfo": {
				"Count": 6,
					"Enable": 1,
					"AlarmNum": 50
			},
			"RealRateInfo": {
				"Count": 1,
					"Enable": 1,
					"AlarmNum": 5
			},
			"RegionId": 0
		}]
	}
	}*/
	//目标计数统计
	private void counterWireStat(JSONObject jsonObject){
		String serialNum = jsonObject.getStr("SerialNum");
		String img = jsonObject.getStr("img");
		if(StringUtil.isBlank(img)){
			return;
		}
		LambdaQueryWrapper<SmartVideoMonitor> monitorLambda = new LambdaQueryWrapper<>();
		monitorLambda.eq(SmartVideoMonitor::getSerialNum, serialNum);
		SmartVideoMonitor monitor = smartVideoMonitorService.getOne(monitorLambda);
		if(monitor == null){
			return;
		}
		JSONObject counterWireInfo = jsonObject.getJSONObject("CounterWireInfo");
		JSONArray list = counterWireInfo.getJSONArray("List");
		JSONObject info = list.getJSONObject(0);
		JSONObject detectInfo = info.getJSONObject("DetectInfo");
		JSONObject totalInfo = info.getJSONObject("TotalInfo");
		Integer enterCnt = detectInfo.getInt("EnterCnt");
		Integer leaveCnt = detectInfo.getInt("LeaveCnt");
		Integer totalCnt = totalInfo.getInt("Count");
		SmartVideoMonitorRecord record = new SmartVideoMonitorRecord();
		record.setSerialNum(serialNum);
		record.setEnterCnt(enterCnt);
		record.setLeaveCnt(leaveCnt);
		record.setImg(img);
		smartVideoMonitorRecordService.save(record);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String format = sdf.format(new Date());
		LambdaQueryWrapper<SmartVideoMonitorStat> lambda = new LambdaQueryWrapper<>();
		lambda.eq(SmartVideoMonitorStat::getSerialNum, serialNum);
		lambda.eq(SmartVideoMonitorStat::getStatDate, format);
		SmartVideoMonitorStat dbStat = smartVideoMonitorStatService.getOne(lambda);
		if(dbStat == null){
			SmartVideoMonitorStat stat = new SmartVideoMonitorStat();
			stat.setSerialNum(serialNum);
			stat.setEnterCnt(enterCnt);
			stat.setLeaveCnt(leaveCnt);
			stat.setTotalCnt(totalCnt);
			stat.setOrgPosition(monitor.getOrgPosition());
			stat.setTenantId(monitor.getTenantId());
			stat.setStatDate(new Date());
			smartVideoMonitorStatService.save(stat);
		}else{
			dbStat.setEnterCnt(dbStat.getEnterCnt() + enterCnt);
			dbStat.setLeaveCnt(dbStat.getLeaveCnt() + leaveCnt);
			dbStat.setTotalCnt(totalCnt);
			dbStat.setOrgPosition(monitor.getOrgPosition());
			dbStat.setTenantId(monitor.getTenantId());
			smartVideoMonitorStatService.updateById(dbStat);
		}

	}

	private void faceCompare(JSONObject eventInfo, List<MultipartFile> file){
		if(file != null && file.size() > 0){
			for(MultipartFile multipartFile : file){
				if(multipartFile.getOriginalFilename().startsWith("bg_")) { //比对图
					R<String> uploadR = uploadController.putFile(multipartFile);
					eventInfo.set("img", uploadR.getData());
					break;
				}
			}
		}
		String serialNum = eventInfo.getStr("SerialNum");
		if(eventInfo.getJSONObject("FaceCompareInfo") == null){
			return;
		}
		String faceCompareInfoStr = eventInfo.getJSONObject("FaceCompareInfo").toString();
		FaceCompareInfo faceCompareInfo = com.alibaba.fastjson.JSONObject.parseObject(faceCompareInfoStr, FaceCompareInfo.class);
		FaceCompareInfo.SnapObj snapObj = faceCompareInfo.getSnap().get(0);
		FaceCompareInfo.MatchOfSnapObj match = snapObj.getMatch();
		FaceCompareInfo.TemperatureOfSnapObj temperatureOfSnapObj = snapObj.getTemperature();
		String userId = match.getId();
		String userName = match.getName();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd'T'HHmmss+08");
		Date openDate = null;
		String openDateStr = null;
		try {
			openDate = sdf.parse(eventInfo.getStr("LocalTime"));
			sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			openDateStr = sdf.format(openDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		this.createAccessRecord(serialNum, openDateStr, Long.parseLong(userId), userName, eventInfo.getStr("img"), temperatureOfSnapObj.getTemp());
	}

	private R createAccessRecord(String serialNum, String openDateStr, Long userId, String userName, String faceUrl, String temperature){
		FaceDevice faceDevice = this.faceDeviceService.selectByMacAddress(serialNum);
		Long agencyId = faceDevice.getAgencyId();
		Agency agency = this.agencyService.getById(agencyId);
		Long residentialId = faceDevice.getResidentialId();
		Long enterpriseId = null;
		String enterpriseName = null;
		Residential residential = this.residentialService.getById(residentialId);
		String residentialName = residential.getName();
		TenantType tenantType = tenantTypeService.getByTenantId(agency.getTenantId());
		Integer type = tenantType.getTenantType();
		String agencyName = agency.getAgencyName();
		EnterpriseStaff staff = null;
		Guest guest = null;
		Integer agencyType = null;

		if(type == 1){ //园区出入记录
			staff = this.enterpriseStaffService.getById(userId);
			if(staff == null){
				guest = this.guestService.getByTel(agencyId, residentialId, userId.toString().substring(3), tenantType.getTenantId());
				if(guest == null){
					return R.fail(String.format("开门纪录，访客【%s】不存在", userName));
				}else{
					userId = guest.getId();
				}
			}else{
				Enterprise enterprise = enterpriseService.getById(staff.getEnterpriseId());
				enterpriseId = enterprise.getId();
				enterpriseName = enterprise.getEnterpriseName();
			}
		}
		AccessRecord accessRecord = new AccessRecord();
		accessRecord.setAgencyId(agencyId);
		accessRecord.setAgencyName(agencyName);
		accessRecord.setResidentialId(residentialId);
		accessRecord.setResidentialName(residentialName);
		accessRecord.setEnterpriseId(enterpriseId);
		accessRecord.setEnterpriseName(enterpriseName);
		accessRecord.setAgencyType(agencyType);
		accessRecord.setUserId(userId);
		accessRecord.setUserName(userName);
		accessRecord.setDeviceId(faceDevice.getId());
		accessRecord.setDeviceMac(faceDevice.getMacAddress());
		accessRecord.setDeviceAddress(faceDevice.getAddress());
		accessRecord.setOpenTime(openDateStr);
		accessRecord.setOpenType("1");
		accessRecord.setTemperature(StringUtil.isNoneBlank(temperature) ? new BigDecimal(temperature).compareTo(BigDecimal.ZERO) == 1 ? temperature : null : null);
		accessRecord.setFaceUrl(faceUrl);
		accessRecord.setOrgPosition(residential.getOrgPosition());
		accessRecord.setTenantId(residential.getTenantId());
		accessRecord.setUserId(userId);
		this.accessRecordService.save(accessRecord);
		return R.status(true);
	}


}
