package com.video.controller;

import com.google.gson.Gson;
import com.video.annotation.UserLoginCheck;
import com.video.api.PlaybackRecordControllerAPI;


import com.video.model.pojo.resultData;
import lombok.AllArgsConstructor;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

/**
 * @Author: binguo
 * @Date: 2023/3/23 星期四 15:55
 * @Description: com.video.controller
 * @Version: 1.0
 */

@RestController
@AllArgsConstructor
public class PlaybackRecordController implements PlaybackRecordControllerAPI {

//    @Autowired
//    private PlaybackRecordService playbackRecordService;
//
//    private final NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler;
//
//    @Override
//    public CommonResult<Integer> InsertPlaybackRecord(@RequestBody PlaybackRecord pb){
//        CommonResult<Integer> result = playbackRecordService.insertPlaybackRecord(pb); // 帮我们自动生成id
//        return result;
//    }
//
//    @Override
//    public CommonResult<List<PlaybackRecord>> QueryPlaybackRecords(HttpServletRequest request) {
//        CommonResult<List<PlaybackRecord>> result = playbackRecordService.getPlaybackRecords();
//        String ipAddress = null;
//        try {
//            ipAddress = request.getHeader("x-forwarded-for");
//            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
//                ipAddress = request.getHeader("Proxy-Client-IP");
//            }
//            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
//                ipAddress = request.getHeader("WL-Proxy-Client-IP");
//            }
//            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
//                ipAddress = request.getRemoteAddr();
//                if (ipAddress.equals("127.0.0.1")) {
//                    // 根据网卡取本机配置的IP
//                    InetAddress inet = null;
//                    inet = InetAddress.getLocalHost();
//                    ipAddress = inet.getHostAddress();
//                }
//            }
//
//            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
//            if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
//                // = 15
//                if (ipAddress.indexOf(",") > 0) {
//                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
//                }
//            }
//        } catch (Exception e) {
//            ipAddress = "";
//        }
//        // ipAddress = this.getRequest().getRemoteAddr();
//
//        String s = ipAddress;
//
//        return result;
//    }
//



    @UserLoginCheck
    public String tests(HttpServletRequest request) throws Exception {

        String sss = "";
        int a = 1;
        int b = 2;
        int c = a + b;
        System.out.println("测试切面接口");
        return "测试切面接口";
//        BufferedReader br = request.getReader();
//
//        String str, wholeStr = "";
//        while((str = br.readLine()) != null){
//
//            wholeStr += str.replace("vgdecoderesult=","").replace("&&otherparams=","");
//        }
//        System.out.println("原生:"+wholeStr);
//
//        int d =wholeStr.indexOf("&&devicenumber=");
//        String deviceNumber = wholeStr.substring(wholeStr.indexOf("&&devicenumber=")).replace("&&devicenumber=","");
//
//        if(!(wholeStr.indexOf("id=") < 0)){
//            wholeStr = wholeStr.replace("id=","id="+deviceNumber).substring(0,d+1);
//        }else{
//            wholeStr = wholeStr.substring(0,d);
//
//            wholeStr = wholeStr.indexOf("&") < 0 ? wholeStr : wholeStr.substring(0,wholeStr.length()-1);
//            wholeStr = "id="+ deviceNumber + "&qr=" + wholeStr;
//        }
//
//
//        System.out.println(wholeStr);
//
//        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
//        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
//
//        HttpPost httpPost = new HttpPost("http://cbai.natapp1.cc/carBook/userupcar.action");//发送请求
//        JSONObject json = new JSONObject();
//        json.put("code",wholeStr);
//
//        // 将参数放到Post中
//        // 通过new StringEntity()，可将Content-Type设置为text/plain类型
//        httpPost.setEntity(new StringEntity(json.toString(),"UTF-8"));
//        CloseableHttpResponse response = httpClient.execute(httpPost);
//        System.out.println(response);//接收返回
//
//        // 取响应的结果
//        int statusCode = response.getStatusLine().getStatusCode();
//        // 打印响应结果
//        if (statusCode == HttpStatus.SC_OK) {
//            String resp = EntityUtils.toString(response.getEntity(), "utf-8");
//            System.out.println("status:" + statusCode);
//            System.out.println("result:" + resp);
//
//            Gson jsons = new Gson();
//            resultData data = jsons.fromJson(resp.replace("result:",""), resultData.class);
//            if(data != null){
//                System.out.println("code:" + data.code);
//                return data.code == 200 ? "code=0000" : "code=1111";
//            }
//            else{
//                System.out.println("data:" + data);
//                return "code=1111";
//            }
//        }
//        return "code=0000";//"code=0000&&desc=tes";//code=xxxx——xxx 表示服务器处理结果代码，0000 表示成功，其它表示错误
    }

    @Override
    public String test(HttpServletRequest request) throws Exception {
        BufferedReader br = request.getReader();

        String str, wholeStr = "";
        while((str = br.readLine()) != null){

            wholeStr += str.replace("vgdecoderesult=","").replace("&&otherparams=","");
        }
        System.out.println("原生:"+wholeStr);
        return "code=0000";
    }

//    public String upcar(){
//        JSONObject resultjson = new JSONObject();
//        Gson gson=new Gson();
//        com.alibaba.fastjson.JSONObject json = GetHttpParam.getHttpParam(request);
//        System.out.println(json);
//        if (json == null){
//            resultjson.put("code", 500);
//            resultjson.put("message", "请传入参数");
//            ResUtil.writeJson(ServletActionContext.getResponse(), resultjson.toString());
//            return null;
//        }



//
//    @Override
//    public void videoPreview(HttpServletRequest request, HttpServletResponse response) throws Exception {
//    //假如我把视频1.mp4放在了static下的video文件夹里面
//        //sourcePath 是获取resources文件夹的绝对地址
//        //realPath 即是视频所在的磁盘地址
//        String sourcePath = "D:/";//ClassUtils.getDefaultClassLoader().getResource("").getPath().substring(1);
//        String realPath = sourcePath +"video/movie.mp4";
//
//
//        Path filePath = Paths.get(realPath );
//        if (Files.exists(filePath)) {
//            String mimeType = Files.probeContentType(filePath);
//            if (!StringUtils.isEmpty(mimeType)) {
//                response.setContentType(mimeType);
//            }
//            request.setAttribute(NonStaticResourceHttpRequestHandler.ATTR_FILE, filePath);
//            nonStaticResourceHttpRequestHandler.handleRequest(request, response);
//        } else {
//            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
//            response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
//        }
//    }
//
//    @Override
//    public void videoOther(HttpServletRequest request, HttpServletResponse response) throws Exception {
//        File mp4File = new File("D:\\video\\movie.mp4");
//
//        ServletOutputStream outputStream = response.getOutputStream();
//        RandomAccessFile targetFile = new RandomAccessFile(mp4File, "r");
//
//        Long offset = 0L; // 偏移量
//        Long returnLength = mp4File.length(); // 最终返回的数据量大小
//
//        String rangeHeader = request.getHeader(HttpHeaders.RANGE); // 格式：Range: bytes=start-end
//        if (isEmptyOrNull(rangeHeader)) {
//            rangeHeader = "";
//            // 分段返回从新计算偏移量和数据大小
//            offset = Long.valueOf(rangeHeader.substring(rangeHeader.indexOf("=") + 1, rangeHeader.indexOf("-")));
//            returnLength = mp4File.length() - offset;
//            String end = rangeHeader.substring(rangeHeader.indexOf("-") + 1);
//            if (isEmptyOrNull(end)) {
//                returnLength = Long.valueOf(end) - offset + 1;
//            }
//
//            // 设置响应头
//            long endIndex = (offset + returnLength - 1) > mp4File.length() ? mp4File.length() : (offset + returnLength - 1);
//            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 断点续传设置206状态码
//            response.setContentType("video/mp4");
//            response.setHeader(HttpHeaders.CONTENT_RANGE, String.format(Locale.ROOT, "bytes %d-%d/%d", offset, endIndex, mp4File.length()));
//            response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes");
//            response.setHeader(HttpHeaders.CONTENT_LENGTH, returnLength + "");
//        } else {
//            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + mp4File.getName());
//            response.setHeader("Content-Length", String.valueOf(mp4File.length())); //设置文件长度
//            response.setHeader("Content-Type", "application/octet-stream");
//        }
//
//        targetFile.seek(offset); //设定文件读取开始位置（以字节为单位）
//
//        // 根据范围获取文件
//        byte[] cache = new byte[1024 * 1024 * 10];
//        int length;
//        long countByte = 0L;
//        boolean isBreak = false;
//        while (!isBreak && (length = targetFile.read(cache)) != -1) {
//            countByte += length;
//            if (countByte > returnLength) {
//                length = (int) (length - (countByte - returnLength));
//                isBreak = true;
//                cache = Arrays.copyOfRange(cache, 0, length);
//            }
//            outputStream.write(cache, 0, length);
//        }
//    }
//
//    @PassToken
//    @Override
//    public void download(HttpServletResponse response) throws UnsupportedEncodingException {
//        String filename = URLEncoder.encode("最新测试.xls", "UTF-8");
//
//        response.setContentType("application/x-download");
//        response.setHeader("Content-Disposition", "attachment;filename=" + filename);//浏览器上提示下载时默认的文件名
//
//        try (ServletOutputStream out = response.getOutputStream();
//             InputStream stream = new FileInputStream("D:\\最新测试.xls")){//读取服务器上的文件
//
//            byte buff[] = new byte[1024];
//            int length = 0;
//            while ((length = stream.read(buff)) > 0) {
//                out.write(buff,0,length);
//            }
//            stream.close();
//            out.close();
//            out.flush();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

}
