package com.zc.business.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.system.service.ISysConfigService;
import com.zc.common.core.httpclient.OkHttp;
import com.zc.common.core.httpclient.exception.HttpException;
import com.zc.common.core.httpclient.request.RequestParams;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.annotation.Repeatable;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import static com.ruoyi.common.constant.Constants.TOKEN;

/**
 *
 */
@Api(tags = "边坡数据接口")
@RestController
@Component
@RequestMapping("/sideSlope")
public class SideSlopeController extends BaseController {
    @Resource
    private RedisCache redisCache;
    public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
    @Autowired
    private ISysConfigService configService;

    @ApiOperation("获取token")
    @PostMapping("/authenticate")
    public JSONObject authenticate() throws IOException {
        OkHttpClient client = new OkHttpClient();

        // 构造请求体
        Map<String, String> map = new LinkedHashMap<>();
        map.put("UserNameOrEmailAddress", configService.selectConfigByKey("UserNameOrEmailAddress"));//用户名
        map.put("Password", configService.selectConfigByKey("Password"));//登录密码
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonInput = objectMapper.writeValueAsString(map);
        RequestBody requestBody = RequestBody.create(JSON, jsonInput);

        // 创建请求
        Request request = new Request.Builder()
                .url(configService.selectConfigByKey("accessTokenApi"))
                .post(requestBody)
                .build();

        // 发送请求并处理响应
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            // 正确解析响应体中的JSON数据
            String responseBody = response.body().string();
            JSONObject jsonResult = JSONObject.parseObject(responseBody);
            return jsonResult;
        }
    }

    /**
     * 获取测点列表
     * @return
     * @throws IOException
     * @throws HttpException
     */
    @ApiOperation("获取边坡测点列表")

    @GetMapping("/GetMeasurePointList")
    public AjaxResult GetMeasurePointList() throws IOException, HttpException {
    JSONObject jsonResult = null;
    OkHttp okHttp = new OkHttp();

    RequestParams requestParams = new RequestParams();
    requestParams.put("proCode", configService.selectConfigByKey("proCode"));
    requestParams.put("unitCode", configService.selectConfigByKey("unitCode"));

    Object accessToken = redisCache.getCacheObject("accessToken");
    if (accessToken==null){
        JSONObject authenticate = authenticate();
        accessToken = authenticate.getJSONObject("result").getString("accessToken");
        redisCache.setCacheObject("accessToken",accessToken);
        redisCache.expire("accessToken", 3 * 24 * 3600);//设置过期时间s秒
    }

   // http://jsgl.sdgsbim.com:8616/api/RoadMajorPlatform/GetMeasurePointList?proCode=JHGKJ&unitCode=60-01.0002.00.00
    Map<String, String> header = new HashMap<>();
    header.put("Authorization", "Bearer "+accessToken.toString());
    Response response // 请求响应
            = okHttp
            .headers(header)
            .url(configService.selectConfigByKey("GetMeasurePointListAPI")) // 请求地址
            .data(requestParams) // 请求参数
            .get(); // 请求方法

    if (response.body() != null) {
        jsonResult = JSONObject.parseObject(response.body().string());
    }
            // 正确解析响应体中的JSON数据
            return AjaxResult.success(jsonResult) ;
    }

    /**
     * 获取长历史数据
     * @return
     * @throws IOException
     * @throws HttpException
     */
 @ApiOperation("获取边坡历史数据")
    @GetMapping("/GetPointDataListAsync")
    public AjaxResult GetPointDataListAsync(
            @ApiParam(value = "测点编号", name = "meaPointNum", required = true) String meaPointNum,
            @ApiParam(value = "开始时间(时间戳)", name = "starttime", required = true) long starttime,
            @ApiParam(value = "结束时间(时间戳)", name = "endtime", required = true) long endtime

            ) throws IOException, HttpException {

    JSONObject jsonResult = null;
        JSONArray jsonArray = null;
    OkHttp okHttp = new OkHttp();

    RequestParams requestParams = new RequestParams();
    requestParams.put("projCode",configService.selectConfigByKey("proCode"));//项目编号 如 JHGKJ
    requestParams.put("unitCode", configService.selectConfigByKey("unitCode"));//项目单位工程编号 如 60-01.0002.00.00
    requestParams.put("meaPointNum", meaPointNum);//测点编号如 PR-YLJ01-067441-05/05
    requestParams.put("starttime", starttime);//开始时间如 1713369599000
    requestParams.put("endtime", endtime);//结束时间 如 1713887999000

    Object accessToken = redisCache.getCacheObject("accessToken");
    if (accessToken==null){
        System.out.println("null+++++++++++++++++++++++");
        JSONObject authenticate = authenticate();
        accessToken = authenticate.getJSONObject("result").getString("accessToken");
        redisCache.setCacheObject("accessToken",accessToken);
        redisCache.expire("accessToken", 3 * 24 * 3600);//设置过期时间s秒
    }

   // http://jsgl.sdgsbim.com:8616/api/RoadMajorPlatform/GetMeasurePointList?proCode=JHGKJ&unitCode=60-01.0002.00.00
    Map<String, String> header = new HashMap<>();
    header.put("Authorization", "Bearer "+accessToken.toString());
    Response response // 请求响应
            = okHttp
            .headers(header)
            .url(configService.selectConfigByKey("GetPointDataListAsyncAPI")) // 请求地址
            .data(requestParams) // 请求参数
            .get(); // 请求方法

    if (response.body() != null) {
        jsonResult = JSONObject.parseObject(response.body().string());
        String jsonObjec =jsonResult.getString("result").replace("\r\n", "");
        jsonArray = extracted(jsonObjec);
    }
            // 正确解析响应体中的JSON数据
            return AjaxResult.success(jsonArray);
    }
    /**
     *   Base64解码
     */
    private JSONArray  extracted(String base64EncodedCompressedData) throws IOException {
        // Base64解码
        byte[] compressedData = Base64.getDecoder().decode(base64EncodedCompressedData);
        StringBuilder output = new StringBuilder();
        // 解压缩
        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(compressedData);
             GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream);
             InputStreamReader inputStreamReader = new InputStreamReader(gzipInputStream, StandardCharsets.UTF_8);
             BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                output.append(line);
            }
        }
        // 将StringBuilder转换为字符串
        String jsonString = output.toString();
// 将字符串转换为JSONObject
        JSONArray jsonObject = JSONArray.parseArray(jsonString);
        return  jsonObject;
    }
}