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;

import static com.upyuns.platform.rs.datacenter.constant.DataConstant.THUMBNAIL_PATH;

@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 fileUrl = url.substring(url.lastIndexOf("/image/")+6);
        String fileName = url.substring(url.lastIndexOf("/")+1);
        String filePath = "";
        if(fileUrl.contains("SN8")) {
            fileUrl = fileUrl.replace(".jpg", ".jpeg");
            filePath = THUMBNAIL_PATH+ fileUrl;
        }else {
            if(fileName.lastIndexOf(".png") > 0) {
                filePath = "/rscloudmart/bg/upload/2021-01-05/1609838996306.png";
            }else if(fileName.lastIndexOf("98_98") > 0) {
                filePath = "/rscloudmart/bg/upload/2021-01-07/1609990102713.jpeg";
            }else {
                filePath = "/rscloudmart/bg/upload/2021-01-07/1609987144037.jpeg";
            }
        }
        //String filePath = "https://w173.obtdata.com/image//data/HEM2/2019/11/18/HEM2_20191118235223_0010_L1B_CMOS1/HEM2_20191118235223_0010_L1B_CMOS1_800_800.png?op=OPEN";
        //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";
//        downloadVideoById(fileName, filePath, getResponse());

        OutputStream out = null;
        try {
            Map<String, Object> result = gtDataRestClient.open(filePath);
            byte[] content = (byte[]) result.get("file");
            getResponse().setContentLength(content.length);
//			response.setContentType("image/jpeg");
//        if(isdownload){
//            response.setContentType("application/octet-stream");
//            String savedName = request.getParameter("savedName");
//            if (savedName!=null && savedName.length()>0) {
//                savedName = URLEncoder.encode(savedName,"UTF-8");
//                response.addHeader("Content-Disposition","attachment;filename=" + savedName);
//            }
//        }
            // 得到想客服端输出的输出流
            out = getResponse().getOutputStream();
            out.write(content);
        }finally {
            out.close();
        }
        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());
        String resultUrl = gtDataRestClient.openUrl(fileName, gdLoginVO.getSign(), gdLoginVO.getTime(), getAppUser().getUserid()+ "");
        resultUrl = resultUrl.replace(gtDataRestClient.getBaseUrl(), gtDataRestClient.getOutUrl());
        return ObjectRestResponse.succ(resultUrl);
    }

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

}
