package com.persagy.cameractl.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestBody;

import com.persagy.cameractl.conf.MyParamConfig;
import com.persagy.cameractl.utils.ResultTools;
import com.persagy.cameractl.utils.StringTools;
import com.persagy.cameractl.utils.OtherTools;
import com.persagy.cameractl.service.PtzMain;
import com.persagy.cameractl.utils.Camera;
import com.persagy.cameractl.utils.ResultClass;
import com.persagy.cameractl.service.DahCameraExecuteApi;

@Controller
@CrossOrigin
public class CameraController {

    @Autowired
    private MyParamConfig myParamConfig;


    Logger logger = LoggerFactory.getLogger(CameraController.class);


    @RequestMapping(value = "/hello", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public @ResponseBody
    String hello() {
        System.out.println(myParamConfig);
        return ResultTools.successResult();
    }

    @RequestMapping(value = "/hello/{name}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public @ResponseBody
    String helloName(@PathVariable("name") String name) {

        return ResultTools.errorResult(name);
    }

    /*
     * 摄像头操作接口(底层调用SDK)，包括：摄像头控制、回放。客户端回放流程为：客户端先调用该接口，成功后再调用vplayf接口播放MP4
     * opertype为control时，参数：command、cameraIp、cameraPort、userName、password、channel、speed
     *
     * opertype为playback时，参数：cameraIp、cameraPort、userName、password、channel、startDateStr、endDateStr
     */
    @RequestMapping(value = "/sdk/{opertype}", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public @ResponseBody
    String ptzOperation(@PathVariable("opertype") String operType, @RequestBody Camera _camera) {
        PtzMain pcControlMain = new PtzMain();
        ResultClass result = pcControlMain.ptzOper(_camera, operType);
        switch (String.valueOf(result.name)) {
            // 调用成功
            case "true":
                return ResultTools.dataResult(result.resultData);
            // 调用失败
            default:
                return ResultTools.errorResult(result.reason);
        }
    }

    /*
     * 请求视频文件接口
     */
    @RequestMapping(value = "/vplayf/{token}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public @ResponseBody
    void vplay(@PathVariable("token") String token, HttpServletResponse response) {
//		String filePath = OtherTools.getVideoFilePathByT(token);
//		File mp4File = new File(filePath);
//		if (!mp4File.exists())
//			return ResultTools.errorResult("文件不存在");
//		Map<String, String> dataMap = new HashMap<String, String>();
//		dataMap.put("path", filePath);
//		return ResultTools.dataResult(dataMap);

        System.out.println("----------111111111111");
        String filePath = OtherTools.getVideoFilePathByT(token);
        if (filePath.equals(""))
            return;
        try {
            System.out.println("----------filePath:" + filePath);
            File mp4File = new File(filePath);
            if (!mp4File.exists())
                return;
            System.out.println("----------222222222");
            FileInputStream inputStream = new FileInputStream(filePath);
            byte[] data = new byte[inputStream.available()];
            inputStream.read(data);
            String diskfilename = "_.mp4";
            response.setContentType("video/mp4");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + diskfilename + "\"");
//			             System.out.println("data.length " + data.length);
            response.setContentLength(data.length);
            response.setHeader("Content-Range", "" + Integer.valueOf(data.length - 1));
            response.setHeader("Accept-Ranges", "bytes");
            response.setHeader("Etag", "W/\"" + StringTools.getUUID() + "\"");
            OutputStream os = response.getOutputStream();

            os.write(data);
            // 先声明的流后关掉！
            os.flush();
            os.close();
            inputStream.close();

        } catch (Exception e) {
            System.out.println("----------33333333333");
        }
    }

    /*
     * 摄像头视频实时播放接口
     */
    @RequestMapping(value = "/realplay", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public @ResponseBody
    String realPlay(@RequestBody Camera _camera) {
        PtzMain pcControlMain = new PtzMain();
        ResultClass playResult = pcControlMain.realPlay(_camera);
        switch (String.valueOf(playResult.name)) {
            // 调用成功
            case "true":
                return ResultTools.successResult();
            // 调用失败
            default:
                return ResultTools.errorResult(playResult.reason);
        }
    }

    /*
     * 调用软件平台接口，根据摄像头监控点位获取预览流url、回放流url、云台控制
     * operType: preview 预览	playback 回放	control 云台控制	other 支持传入接口名称和参数，方便调试	tvwall 获取视频墙列表
     * 		tvwalllayout 获取某个视频墙的布局	toup 投屏，即上墙操作	exittoup 退出投屏
     * 		kaichuang 在电视墙屏幕上进行开窗  setwinsource 设置窗口视频源
     * 	预览参数：
     * 		cameraIndexCode(视频通道编码,例1000000$1$0$0)、streamType(码流类型，可不传，不传时默认1； 0:主码流 1:子码流 2:第三码流)、levelNo(级联号，没有时不传)
     *	回放参数：
     *		cameraIndexCode(视频通道编码,例1000000$1$0$0)、streamType(码流类型，可不传，不传时默认1； 0:主码流 1:子码流 2:第三码流)、levelNo(级联号，没有时不传)
     *		startDateStr(开始时间,2021-04-01 11:12:13)、endDateStr(结束时间,2021-04-01 11:12:13)
     *	云台控制参数：
     *		cameraIndexCode(视频通道编码,例1000000$1$0$0)、command(控制命令)、speed(速度，值范围1~8，默认8)
     *
     *	other 根据传入接口名称来调用对应的大华软件平台接口，参数：
     *		url 调用的大华软件平台接口名称，例：admin/rest/api
     *		paramStr 自定义参数，格式：{_type:"get | post",interfaceId:"可为空",isToken:"1 url上需要拼接token | 0 url上不需要拼接token"}
     *		jsonParam 传给大华软件平台的接口参数；例："{\"param\":{\"category\":1}}"
     *
     *	获取视频墙列表参数
     *		无
     *	获取某个视频墙的布局参数
     *		tvWallId 视频墙ID
     *	投屏参数
     *		layoutCode	one(只有一个窗口)、left-up-one(六个窗口，左上角是大窗口)、right-down-one(六个窗口，右下角是大窗口)、right-up-one(六个窗口，右上角是大窗口)、left-down-one(六个窗口，左下角是大窗口)、multi-one(九宫格窗口)
     *		cameraIndexArr 视频墙数据源数组，每一项均为cameraIndexCode，数组的顺序和窗口顺序保持一致
     */
    @RequestMapping(value = "/vision/{opertype}", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public @ResponseBody
    String hikvisionOper(@PathVariable("opertype") String operType, @RequestBody Camera camera) {

        logger.info("调用大华平台接口开始，入参" + operType + "camera :" + camera);
        long start = System.currentTimeMillis();

        DahCameraExecuteApi dahCameraExecuteApi = new DahCameraExecuteApi();
        // @formatter:off
        ResultClass executeResult = operType.equals("preview") ? dahCameraExecuteApi.GetCameraPreviewURL(camera)
                : operType.equals("control") ? dahCameraExecuteApi.ptzControl(camera)
                : operType.equals("playback") ? dahCameraExecuteApi.GetCameraPlaybackURL(camera, false)
                : operType.equals("playbackUrl") ? dahCameraExecuteApi.GetCameraPlaybackURL(camera, true)
                : operType.equals("tvwall") ? dahCameraExecuteApi.GetTvWallList(camera)
                : operType.equals("tvwalllayout") ? dahCameraExecuteApi.GetTvWallLayoutList(camera)
                : operType.equals("other") ? dahCameraExecuteApi.requestAll(camera)
                : operType.equals("toup") ? dahCameraExecuteApi.touP(camera)
                : operType.equals("exittoup") ? dahCameraExecuteApi.exitTouP(camera)
                : operType.equals("daplx") ? dahCameraExecuteApi.dapLx(camera)
                : operType.equals("kaichuang") ? dahCameraExecuteApi.kaichuang(camera)
                : operType.equals("setwinsource") ? dahCameraExecuteApi.setWindowSource(camera)
                : operType.equals("getgroup") ? dahCameraExecuteApi.getGroupTree(camera)
                : new ResultClass(false, "非法请求");

        // @formatter:on
        switch (String.valueOf(executeResult.name)) {
            // 调用成功
            case "true":
                logger.info("调用大华平台接口success，入参=" + operType
                        + "camera :" + camera.toString()
                        + "、返回值 = " + ResultTools.dataResult(executeResult.resultData)
                        + "、耗时 = " + (System.currentTimeMillis() - start) + "ms");

                return ResultTools.dataResult(executeResult.resultData);
            // 调用失败
            default:
				logger.error("调用大华平台接口error，入参=" + operType
						+ "camera :" + camera.toString()
						+ "、返回值 = " + ResultTools.errorResult(executeResult.reason)
						+ "、耗时 = " + (System.currentTimeMillis() - start) + "ms");
                return ResultTools.errorResult(executeResult.reason);
        }
    }
}
