package com.upyuns.platform.rs.datacenter.rest;

import cn.hutool.core.util.StrUtil;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.github.wxiaoqi.security.common.rest.CommonBaseController;
import com.upyuns.platform.rs.datacenter.entity.RscpAreaInfo;
import com.upyuns.platform.rs.gtdata.GtDataRestClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
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.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

@RestController
@Slf4j
@RequestMapping("/web/gtdata/")
public class GtdataController extends CommonBaseController {
    @Autowired
    GtDataRestClient gtDataRestClient;

    @RequestMapping(value = "/app/unauth/image/**", method = RequestMethod.GET)
    @IgnoreUserToken
    public void queryAreaInfoByAreaId() throws Exception  {
        String url = request.getRequestURI();
        String fileName = url.substring(url.lastIndexOf("/")+1);
        String filePath = "https://box.bdimg.com/static/fisp_static/common/img/searchbox/logo_news_276_88_1f9876a.png";
//        String filePath = "/obt/thumbnail/"+ url.substring(url.lastIndexOf("/app/unauth/image/")+18);
//        String filePath = "/obt/thumbnail/data/VDM2/20200613/VDM2_20200525232637_0015_L1_MSS_CMOS5/VDM2_20200525232637_0015_L1_MSS_CMOS5_98_98.jpg";
//        filePath = gtDataRestClient.openUrl(filePath);
        downloadVideoById(fileName, filePath, getResponse());
        return;
    }

    public void downloadVideoById(String fileName, String filePath, HttpServletResponse response) throws Exception {
        log.info("下载请求start>>");
        try {
            if (StrUtil.isEmpty(fileName) || StrUtil.isEmpty(filePath)) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().print("参数错误，请联系管理员!");
                response.flushBuffer();
                return;
            }

            URL pathUrl = new URL(filePath);
            HttpURLConnection urlcon = (HttpURLConnection) pathUrl.openConnection();
            if(urlcon.getResponseCode()>=400){
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().print("文件不存在，请联系管理员!");
                response.flushBuffer();
                return;
            }
            //获取输入流对象（用于读文件） 网络流
            InputStream inputStream = new URL(filePath).openStream();
            //本地流文件
            // FileInputStream fis = new FileInputStream(new File(filePath));
            //动态设置响应类型，根据前台传递文件类型设置响应类型
            response.setContentType("image/" + fileName.substring(fileName.lastIndexOf(".")+1));
            //设置响应头,attachment表示以附件的形式下载，inline表示在线打开
            response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));//下载时浏览器显示的名称
            //获取输出流对象（用于写文件）
            ServletOutputStream os = response.getOutputStream();
            //下载文件,使用spring框架中的FileCopyUtils工具
            FileCopyUtils.copy(inputStream, os);

        } catch (Exception e) {
            log.error("下载失败 start >>",e);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().print("下载失败，请联系管理员!");
            response.flushBuffer();
        }
    }

}
