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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.CommonBaseController;
import com.github.wxiaoqi.security.common.util.result.JsonResultUtil;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

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

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

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

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ObjectRestResponse uploads2(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "prefix",defaultValue = "admin")String prefix
    )throws Exception {
        return uploads(file, prefix);
    }

    @RequestMapping(value = "/app/unauth/upload", method = RequestMethod.POST)
    @IgnoreUserToken
    public ObjectRestResponse uploads(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "prefix",defaultValue = "admin")String prefix
    )throws Exception {
        String contentType = file.getContentType();   //图片文件类型
        if(StrUtil.isBlank(contentType)) {
            contentType = "jpg";
        }else {
            String[] types = file.getContentType().split("/");
            if(types.length > 1) {
                contentType = file.getContentType().split("/")[1];
            }
        }
        String path = uploadP+ DateUtil.date().toDateStr()+ "/";
        String fileName = path+ System.currentTimeMillis()+ "."+ contentType;
        Map<String, Object> existMap = gtDataRestClient.isExist(path);
        if(existMap.get("HttpStatusCode") == null || !"200".equals(existMap.get("HttpStatusCode"))){
            gtDataRestClient.mkdirs(path);
        }
        gtDataRestClient.createMultipartFile(file, fileName);
        //获取文件信息
        Map<String, Object> map = gtDataRestClient.showFileInfo(fileName);
        return ObjectRestResponse.succ(map);
    }

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

}
