package com.fastbee.deviceData.api.yingshiyun.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Service
public class YingshiyunService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //获取鉴权
    public  String getAuth(){
        if(Boolean.TRUE.equals(stringRedisTemplate.hasKey("yingshiyun:user:accessToken"))){
            return stringRedisTemplate.opsForValue().get("yingshiyun:user:accessToken");
        }
        // 鉴权请求
        String AUTH_URL = "https://open.ys7.com/api/lapp/token/get";
        String appKey = "b21f910dc7044d668e7625a3c0392e62";
        String appSecret  = "b4beff5f8f6694dd6993c8c5b618417b";
        // 构建请求体参数
        String body = StrUtil.format("appKey={}&appSecret={}", appKey, appSecret);
        HttpResponse response = HttpRequest.post(AUTH_URL)
                .body(body).execute();
        JSONObject jsonObject = JSONUtil.parseObj(response.body());
        String accessToken = JSONUtil.parseObj(jsonObject.get("data")).get("accessToken").toString();
        stringRedisTemplate.opsForValue().set("yingshiyun:user:accessToken",accessToken, 60*60*24*6);
        return accessToken;
    }

    //获取视频播放地址
    public String getVideoPlayUrl(String deviceSerial){
        String accessToken = getAuth();
        String VIDEO_PLAY_URL = "https://open.ys7.com/api/lapp/v2/live/address/get";
        String body = StrUtil.format("accessToken={}&deviceSerial={}",accessToken ,deviceSerial );
        HttpResponse response = HttpRequest.post(VIDEO_PLAY_URL)
                .form(body).execute();
        JSONObject jsonObject = JSONUtil.parseObj(response.body());
        String videoPlayUrl = JSONUtil.parseObj(jsonObject.get("data")).get("url").toString();
        String expireTime = JSONUtil.parseObj(jsonObject.get("data")).get("expireTime").toString();
       Map<String, Object> resp= new HashMap<>();
       resp.put("videoPlayUrl",videoPlayUrl);
       resp.put("expireTime",expireTime);
       resp.put("deviceSerial",deviceSerial);
        return videoPlayUrl;
    }









    public static void main(String[] args) {
        YingshiyunService yingshiyunService = new YingshiyunService();
        yingshiyunService.getAuth();
        long timeStamp = 1731571309231L;
        Date date = new Date(timeStamp);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        sdf.setTimeZone(java.util.TimeZone.getTimeZone("Asia/Shanghai"));
        String formattedDate = sdf.format(date);
        System.out.println(formattedDate);
    }
}
