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

import cn.hutool.core.util.StrUtil;
import com.github.wxiaoqi.security.admin.entity.AppUserLogin;
import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.admin.feign.rest.UserRestInterface;
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.github.wxiaoqi.security.common.util.MD5;
import com.upyuns.platform.rs.datacenter.entity.RscpAreaInfo;
import com.upyuns.platform.rs.gtdata.GdLoginVO;
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.*;

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

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

    @Autowired
    UserFeign userFeign;

    @Override
    public UserFeign getUserFeign() {
        return userFeign;
    }

    public static final String uploadP = "/rscloudmart/bg/upload/";

    @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)+ System.currentTimeMillis();
        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;
    }

    @RequestMapping(value = "/download/**", method = RequestMethod.GET)
    public ObjectRestResponse userDownload() throws Exception  {
        return download();
    }

    @RequestMapping(value = "/app/unauth/download/**", method = RequestMethod.GET)
    @IgnoreUserToken
    public ObjectRestResponse download() throws Exception  {
        String url = request.getRequestURI();
        String fileName = url.substring(url.lastIndexOf("/web/gtdata/app/unauth/download/")+32);

        GdLoginVO gdLoginVO = gtDataRestClient.rsignUserlogin(getAppUser().getUserid()+"", getAppUser().getGtdataPass());
        return ObjectRestResponse.succ(gtDataRestClient.openUrl(uploadP+ fileName, gdLoginVO.getSign(), gdLoginVO.getTime(), getAppUser().getUserid()+ ""));
    }

    @RequestMapping(value = "/app/unauth/register", method = RequestMethod.GET)
    @IgnoreUserToken
    public ObjectRestResponse dataRegister(AppUserLogin appUserLogin) throws Exception  {
        String gtdataPass = MD5.GetMD5StringLower(appUserLogin.getId().toString());
        Map<String, Object> result = gtDataRestClient.register(appUserLogin.getId()+"", MD5.GetMD5StringLower(gtdataPass), (1024L* 1024L* 1024L* 100)+ "");
        result.put("gtdataPass", gtdataPass);
        return ObjectRestResponse.succ(result);
    }

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

}
