package com.bcxin.autodownloadupload.controller;


import com.alibaba.fastjson.JSONObject;
import com.bcxin.autodownloadupload.common.utils.HttpUtil;
import com.bcxin.autodownloadupload.dtos.BoundaryResult;
import com.bcxin.autodownloadupload.dtos.BoundaryResultData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
public class BoundaryController {

    @Value("${boundary-server.opposite-url:unknown}")
    private String oppositeUrl;

    /**
     * 发送文件或数据接口
     */
    @PostMapping("/ferry_file/send")
    public BoundaryResult conferenceCreate(HttpServletRequest request) {
        log.info("=======================发送文件或数据接口=========================");
        String bodyAsString = readBodyAsString(request);
        JSONObject body = JSONObject.parseObject(bodyAsString);
        log.info("=======================接口：{}=========================", body.getString("ferry_accept_url"));
        HttpUtil.post(oppositeUrl.concat(body.getString("ferry_accept_url")), bodyAsString);
        log.info("==========================================================");
        List<BoundaryResultData> data = new ArrayList<>();
        BoundaryResultData d = new BoundaryResultData();
        d.setTask_id("111122223333");
        data.add(d);
        BoundaryResult result = new BoundaryResult();
        result.setStatus_code("0");
        result.setMsg("成功");
        result.setData(data);
        return result;
    }


    private static String readBodyAsString(HttpServletRequest request) {
        InputStream is = null;
        StringBuilder sb = new StringBuilder();
        try {
            is = request.getInputStream();

            byte[] b = new byte[4096];
            for (int n; (n = is.read(b)) != -1; ) {
                sb.append(new String(b, 0, n));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }
}
