package com.izouma.wenlvju.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.kevinsawicki.http.HttpRequest;
import com.izouma.wenlvju.domain.EzvizToken;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.EzvizTokenRepo;
import com.izouma.wenlvju.utils.JpaUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Slf4j
@Service
@AllArgsConstructor
public class EzvizTokenService {

    private final EzvizTokenRepo ezvizTokenRepo;
    private final Environment    env;

    public Page<EzvizToken> all(PageQuery pageQuery) {
        return ezvizTokenRepo.findAll(JpaUtils.toSpecification(pageQuery, EzvizToken.class), JpaUtils.toPageRequest(pageQuery));
    }

    public String getToken() {
        LocalDateTime now = LocalDateTime.now();
        EzvizToken ezvizToken = ezvizTokenRepo.findFirstByExpiredAtAfter(now);
        if (ObjectUtil.isNotNull(ezvizToken)) {
            return ezvizToken.getToken();
        }
        String uri = "https://open.ys7.com/api/lapp/token/get";
        String send = "appKey=" + env.getProperty("ezviz.app_id") + "&appSecret=" + env.getProperty("ezviz.app_secret");
        log.info("萤石获取token--->" + send);

        String body = HttpRequest.post(uri).send(send).body();
        log.info("萤石获取token返回--->" + body);

        JSONObject json = JSONObject.parseObject(body);
        if (!"200".equals(json.getString("code"))) {
            throw new BusinessException("获取accessToken失败，请稍后再试");
        }

        JSONObject data = json.getJSONObject("data");
        String token = data.getString("accessToken");
        //过期时间
        LocalDateTime expireTime = Convert.toLocalDateTime(data.getLong("expireTime"));
        ezvizTokenRepo.save(EzvizToken.builder()
                .token(token)
                .expiredAt(expireTime)
                .build());
        return token;
    }
}
