package im.zksy.yjmqserver.system.controller;

import im.zksy.yjmqserver.system.model.Params;
import im.zksy.yjmqserver.system.model.ResultInfo;
import im.zksy.yjmqserver.system.service.AlarmService;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.net.www.protocol.ftp.FtpURLConnection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

@RestController
@RequestMapping("/alarm")
public class AlarmController {
    @Autowired
    private AlarmService alarmService;
    @Value("${ftp.ftppathurl}")
    String ftppath;



    @RequestMapping("/getAlarm")
    public ResultInfo getAlarm(@RequestBody Params params){
        try {
            ResultInfo resultInfo = alarmService.getAlarm(params);
            return resultInfo;
        }catch (Exception ex){

            return null;
        }

    }
    @RequestMapping("/api/alg/files/{year}/{month}/{day}/{picpath}")
    protected void fielagent(@PathVariable(value="year") String year,
                             @PathVariable(value="month") String month,
                             @PathVariable(value="day") String day,
                             @PathVariable(value="picpath") String picpath,
                             HttpServletRequest request, HttpServletResponse response) {
        String ftpPath="ftp://"+ftppath+"/"+year+"/"+month+"/"+day+"/"+picpath;

        FileInputStream hFile = null;
        OutputStream toClient = null;
        InputStream inputStream = null;
        BufferedInputStream bis = null;
        try {
            response.reset();
            response.setHeader("Expires", "Sat, 10 May 2059 12:00:00 GMT");
            response.setHeader("Cache-Control", "max-age=315360000");

            if (StringUtils.isNotBlank(ftpPath)) {
                if (ftpPath.endsWith(".jpg") || ftpPath.endsWith(".JPG") || ftpPath.endsWith(".png") || ftpPath.endsWith(".PNG") || ftpPath.endsWith(".gif") || ftpPath.endsWith(".GIF")) {
                    response.setContentType("image/" + ftpPath.substring(ftpPath.lastIndexOf(".") + 1) + "; charset=utf-8");
                } else if (ftpPath.endsWith(".mp4") || ftpPath.endsWith(".MP4")) {
                    response.setContentType("video/mpeg4; charset=utf-8");
                    String mp4file = ftpPath.substring(ftpPath.lastIndexOf("/") + 1);
                    response.setHeader("Content-Disposition", "attachment;fileName=" + mp4file);
                }

                String destUrl = ftpPath;
                destUrl = new String(destUrl.getBytes("ISO8859-1"), "GBK");
                String[] arr = destUrl.split(";");
                FtpURLConnection ftpUrl = null;
                HttpURLConnection httpUrl = null;
                for (int i = 0; i < arr.length; i++) {
                    try {
                        URL url = new URL(arr[i]);
                        if (arr[i].toUpperCase().indexOf("FTP") != -1) { // ftp
                            ftpUrl = (FtpURLConnection) url.openConnection();
                            ftpUrl.setConnectTimeout(30000);
                            ftpUrl.setReadTimeout(30000);
                            bis = new BufferedInputStream(ftpUrl.getInputStream());
                            response.setContentLength(ftpUrl.getContentLength());
                        } else { // http
                            httpUrl = (HttpURLConnection) url.openConnection();
                            httpUrl.setConnectTimeout(30000);
                            httpUrl.setReadTimeout(30000);
                            bis = new BufferedInputStream(httpUrl.getInputStream());
                            response.setContentLength(httpUrl.getContentLength());
                        }
                        toClient = response.getOutputStream();
                        IOUtils.copy(bis, toClient);
                    } catch (Exception e) {
                        response.setContentType("text/html;charset=GBK");
                        response.setCharacterEncoding("GBK");
                        PrintWriter out = response.getWriter();
                        out.write("无法打开图片!");
                        out.flush();
                    } finally {
                        if (bis != null) {
                            bis.close();
                        }
                        if (bis != null) {
                            bis.close();
                        }
                        if (httpUrl != null) {
                            httpUrl.disconnect();
                        }
                        if (ftpUrl != null) {
                            ftpUrl.close();
                        }
                        if (toClient != null) {
                            toClient.close();
                        }
                    }
                }
                return;
            }

        } catch (Exception e) {
        } finally {
            IOUtils.closeQuietly(bis);
            IOUtils.closeQuietly(toClient);
            IOUtils.closeQuietly(hFile);
            IOUtils.closeQuietly(inputStream);
        }

    }

}
