package com.zcloud.controller.video;

import com.alibaba.fastjson.JSONObject;
import com.zcloud.controller.base.BaseController;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.service.video.AIWarningService;
import com.zcloud.service.video.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.RequestBody;
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报警
 */
@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";
		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)))));    //报警时间

			File img = base64ToFile(json.getString("resultImg"));
			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);
			img.delete();
			pd.put("IMG_PATH", Const.FILEPATHFILE + "/" + ffile + "/" + fileName);

			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);
			video.delete();
			pd.put("VIDEO_PATH", Const.FILEPATHFILE + "/" + ffile1 + "/" + fileName1);

			PageData videoPd = new PageData();
			videoPd.put("CODE",  json.get("cameraCode"));
			videoPd = videoManagerService.findByCode(videoPd);
			if(videoPd != null){
				pd.put("VIDEOMANAGER_ID", videoPd.get("VIDEOMANAGER_ID"));    //视频ID
				pd.put("VIDEOMANAGER_NAME", videoPd.get("VIDEONAME"));    //视频名称
				pd.put("OUTSOURCED_ID", videoPd.get("OUTSOURCED_ID"));    //重点工程id
				pd.put("CORPINFO_ID", videoPd.get("CORPINFO_ID"));    //重点工程id
				pd.put("CHECK_NO", videoPd.get("CHECK_NO"));    //重点工程id
			}
			pd.put("STATUS", 0);    //状态0未处置
			pd.put("ISTRUE", 3);    //状态3未审核
			aiwarningService.save(pd);
			map.put("result", errInfo);
		}else{
			map.put("result", "faild");
			map.put("msg", "报警信息为空");
		}
		return map;
	}

	@RequestMapping(value="/getAlarmInfo2",headers = "content-type=multipart/form-data")
	@ResponseBody
	public Object getAlarmInfo2(
			@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)))));    //报警时间

			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);
			img.delete();
			pd.put("IMG_PATH", Const.FILEPATHFILE + "/" + ffile + "/" + fileName);

			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);
			video.delete();
			pd.put("VIDEO_PATH", Const.FILEPATHFILE + "/" + ffile1 + "/" + fileName1);

			PageData videoPd = new PageData();
			videoPd.put("CODE",  json.get("cameraCode"));
			videoPd = videoManagerService.findByCode(videoPd);
			if(videoPd != null){
				pd.put("VIDEOMANAGER_ID", videoPd.get("VIDEOMANAGER_ID"));    //视频ID
				pd.put("VIDEOMANAGER_NAME", videoPd.get("VIDEONAME"));    //视频名称
				pd.put("OUTSOURCED_ID", videoPd.get("OUTSOURCED_ID"));    //重点工程id
			}
			pd.put("STATUS", 0);    //状态0未处置
			pd.put("ISTRUE", 3);    //状态3未审核

			aiwarningService.save(pd);
			map.put("result", errInfo);
		}else{
			map.put("result", "faild");
			map.put("msg", "报警信息为空");
		}
		return map;
	}

	@RequestMapping(value="/getAlarmInfo3")
	@ResponseBody
	public Object getAlarmInfo3(@RequestBody String resultMsg) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		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)))));    //报警时间

			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);
			img.delete();
			pd.put("IMG_PATH", Const.FILEPATHFILE + "/" + ffile + "/" + fileName);

			PageData videoPd = new PageData();
			videoPd.put("CODE",  json.get("cameraCode"));
			videoPd = videoManagerService.findByCode(videoPd);
			if(videoPd != null){
				pd.put("VIDEOMANAGER_ID", videoPd.get("VIDEOMANAGER_ID"));    //视频ID
				pd.put("VIDEOMANAGER_NAME", videoPd.get("VIDEONAME"));    //视频名称
				pd.put("OUTSOURCED_ID", videoPd.get("OUTSOURCED_ID"));    //重点工程id
			}
			pd.put("STATUS", 0);    //状态0未处置
			pd.put("ISTRUE", 3);    //状态3未审核

			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);
	}


	/**列表
	 * @param page
	 * @throws Exception
	 */
	@RequestMapping(value="/list")
	@ResponseBody
	public Object list(Page page) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		String KEYWORDS = pd.getString("KEYWORDS");						//关键词检索条件
		if(Tools.notEmpty(KEYWORDS))pd.put("KEYWORDS", KEYWORDS.trim());
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
		page.setPd(pd);
		List<PageData> varList = aiwarningService.list(page);	//列出AIWarning列表
		map.put("varList", varList);
		map.put("page", page);
		map.put("result", errInfo);
		return map;
	}

	 /**去修改页面获取数据
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/goEdit")
	@ResponseBody
	public Object goEdit() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd = aiwarningService.findById(pd);	//根据ID读取
		map.put("pd", pd);
		map.put("result", errInfo);
		return map;
	}
	/**
	 * @Description: 修改
	 * @Author: dearLin
	 * @Date: 2024/1/26/026 15:27
	 * @Param: [] []
	 * @Return: java.lang.Object
	 */
	@RequestMapping(value="/edit")
	@ResponseBody
	public Object edit() throws Exception{
		PageData pd =  this.getPageData();
		pd.put("OPERATOR",Jurisdiction.getUSER_ID());
		pd.put("OPERATTIME",DateUtil.date2Str(new Date()));
		aiwarningService.edit(pd);	//根据ID读取
		return ReturnMap.ok();
	}
	/**
	 * @Description: 批量删除
	 * @Author: dearLin
	 * @Date: 2024/1/26/026 15:27
	 * @Param: [] []
	 * @Return: java.lang.Object
	 */
	@RequestMapping(value="/removeByIds")
	@ResponseBody
	public Object removeByIds() throws Exception{
		PageData pd =  this.getPageData();
		String[] aiwarningIds = pd.getString("AIWARNING_IDS").split(",");
		aiwarningService.deleteAll(aiwarningIds);	//根据ID读取
		return ReturnMap.ok();
	}
}
