package com.zcloud.controller.aiwarnning;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zcloud.controller.base.BaseController;
import com.zcloud.entity.PageData;
import com.zcloud.service.bus.AIWarningService;
import com.zcloud.service.bus.ImgFilesService;
import com.zcloud.service.bus.VideoManagerService;
import com.zcloud.util.*;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.util.*;

/**
 * 说明：AI报警
 * 作者：luoxiaobao
 * 时间：2022-09-21
 * 官网：www.zcloudchina.com
 */
@Controller
@RequestMapping("/aiwarning")
public class AIWarningController extends BaseController {

	@Autowired
	private AIWarningService aiwarningService;
	@Autowired
	private VideoManagerService videoManagerService;
	@Autowired
	private Smb smb;
	/**新增
	 * @param
	 * @throws Exception
	 */

	@RequestMapping(value="/getAlarmInfo",headers = "content-type=multipart/form-data")
	@ResponseBody
	public Object getAlarmInfo(
			@RequestParam(value = "resultVideo", required = false) MultipartFile resultVideo, @RequestParam("resultMsg") String resultMsg) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		System.out.println(resultMsg);
		if(resultMsg!=null && !resultMsg.equals("")) {
			JSONObject json = JSONObject.parseObject(resultMsg);
			PageData pd = new PageData();
			pd.put("AIWARNING_ID", this.get32UUID());    //主键
			pd.put("CREATTIME", DateUtil.date2Str(new Date()));    //添加时间
			pd.put("OPERATTIME", DateUtil.date2Str(new Date()));    //修改时间
			pd.put("ISDELETE", 0);    //是否删除
//			pd.put("TYPE",Const.WARNING_TYPE_MAP.get(json.get("algType")));    //类型
			pd.put("WARNING_TIME", DateUtil.date2Str(new Date(Long.parseLong(json.getString("createTime").substring(0,json.getString("createTime").length()-3)))));    //报警时间
			PageData videoPd = new PageData();
			videoPd.put("CODE",  json.get("cameraCode"));
			videoPd = videoManagerService.findByCode(videoPd);
			pd.put("VIDEOMANAGER_ID", videoPd.get("VIDEOMANAGER_ID"));    //视频ID
			pd.put("VIDEOMANAGER_NAME", videoPd.get("VIDEONAME"));    //视频名称
			pd.put("CORPINFO_ID", videoPd.get("CORPINFO_ID"));    //重点工程id
			List<JSONObject> algResult = (List<JSONObject>) JSON.parse(json.get("algResult").toString());
			String resultLabel =algResult.get(0).getString("label");
			if(Const.WARNING_TYPERESULT_MAP.get(resultLabel) != null){
				pd.put("TYPE",Const.WARNING_TYPERESULT_MAP.get(resultLabel));    //类型详细
			}else{
				pd.put("TYPE",Const.WARNING_TYPE_MAP.get(json.get("algType")));    //类型
			}

			File img = base64ToFile(json.getString("sourceImgBase64"));
			MultipartFile file = getMultipartFile(img);
			String  ffile = DateUtil.getDays();
			String fileName = this.get32UUID() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
			smb.sshSftp(file, fileName, Const.FILEPATHFILE + "/" + ffile,videoPd.getString("CORPINFO_ID"));
			img.delete();
			pd.put("IMG_PATH", Const.FILEPATHFILE + "/" + ffile + "/" + fileName);

			if(resultVideo!=null){
				String  ffile1 = DateUtil.getDays();
				File video = File.createTempFile(resultVideo.getOriginalFilename(), ".mp4");
				resultVideo.transferTo(video);
				MultipartFile mvideo = getMultipartFile(video);
				String fileName1 = mvideo.getOriginalFilename();
				smb.sshSftp(mvideo, fileName1, Const.FILEPATHFILE + "/" + ffile1,videoPd.getString("CORPINFO_ID"));
				video.delete();
				pd.put("VIDEO_PATH", Const.FILEPATHFILE + "/" + ffile1 + "/" + fileName1);
			}

			pd.put("STATUS", 0);    //状态0未处置
			aiwarningService.save(pd);
			map.put("result", errInfo);
		}else{
			map.put("result", "faild");
			map.put("msg", "报警信息为空");
		}
		return map;
	}


	private File base64ToFile(String base64) throws IOException {
		if(base64.contains("data:image")){
			base64 = base64.substring(base64.indexOf(",")+1);
		}
		base64 = base64.toString().replace("\r\n", "");
		//创建文件目录
		String prefix=".jpg";
		File file = File.createTempFile(get32UUID(), prefix);
		BufferedOutputStream bos = null;
		FileOutputStream fos = null;
		try {
			byte[] bytes = Base64.getDecoder().decode(base64);
			fos = new FileOutputStream(file);
			bos = new BufferedOutputStream(fos);
			bos.write(bytes);
		}finally {
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return file;
	}

	public static MultipartFile getMultipartFile(File file) {
		DiskFileItem item = new DiskFileItem("file"
				, MediaType.MULTIPART_FORM_DATA_VALUE
				, true
				, file.getName()
				, (int)file.length()
				, file.getParentFile());
		try {
			OutputStream os = item.getOutputStream();
			os.write(FileUtils.readFileToByteArray(file));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new CommonsMultipartFile(item);
	}
}
