package org.springblade.third.zongheng.handler;

import com.alibaba.fastjson.JSONObject;
import org.springblade.core.oss.model.BladeFile;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.SpringUtil;
import org.springblade.estate.dto.SnapRecordDTO;
import org.springblade.estate.entity.SnapRecord;
import org.springblade.estate.feign.IAccessRecordClient;
import org.springblade.estate.feign.ISnapRecordClient;
import org.springblade.third.zongheng.beans.FaceCaptureInfo;
import org.springblade.third.zongheng.beans.FaceCompareInfo;
import org.springblade.utils.OssUtil;
import org.springframework.web.multipart.MultipartFile;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class FaceCaptureEventHandler implements IDeviceEndEventHandler{

	public static OssUtil ossUtil;
	public static ISnapRecordClient snapRecordClient;

	static {
		ossUtil = SpringUtil.getBean(OssUtil.class);
		snapRecordClient = SpringUtil.getBean(ISnapRecordClient.class);
	}

	@Override
	public R handle(JSONObject eventInfo, List<MultipartFile> file) {
		for(MultipartFile multipartFile : file){
			if(multipartFile.getOriginalFilename().startsWith("bg_")) { //抓拍图
				R<BladeFile> bladeFileR = ossUtil.uploadFile(multipartFile);
				eventInfo.put("img", bladeFileR.getData().getName());
				break;
			}
		}
		String serialNum = eventInfo.getString("SerialNum");
		String faceCaptureInfoStr = eventInfo.getJSONObject("FaceCaptureInfo").toJSONString();
		FaceCaptureInfo faceCaptureInfo = JSONObject.parseObject(faceCaptureInfoStr, FaceCaptureInfo.class);
		FaceCaptureInfo.SnapObj snapObj = faceCaptureInfo.getSnap().get(0);
		Integer score = snapObj.getScore();
		FaceCaptureInfo.TemperatureOfSnapObj temperatureOfSnapObj = snapObj.getTemperature();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd'T'HHmmss+08");
		Date snapDate = null;
		try {
			snapDate = sdf.parse(eventInfo.getString("LocalTime"));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		this.createSnapRecord(serialNum, snapDate, score.toString(), temperatureOfSnapObj.getTemp(), eventInfo.getString("img"));
		return R.status(true);
	}

	private void createSnapRecord(String serialNum, Date snapDate, String score, String temperature, String snapUrl){
		SnapRecordDTO snapRecord = new SnapRecordDTO();
		snapRecord.setSerialNum(serialNum);
		snapRecord.setScore(score);
		snapRecord.setFaceUrl(snapUrl);
		snapRecord.setTemperature(temperature);
		snapRecord.setCreateTime(snapDate);
		snapRecordClient.generateSnapRecord(snapRecord);
	}
}
