package com.fs.wxcid.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.fs.common.core.redis.RedisCacheT;
import com.fs.common.exception.base.BaseException;
import com.fs.common.utils.StringUtils;
import com.fs.wxcid.dto.admin.GenAuthKey3Request;
import com.fs.wxcid.dto.common.ApiResponseCommon;
import com.fs.wxcid.service.AdminLicenseService;
import com.fs.wxwork.utils.WxWorkHttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class AdminLicenseServiceImpl implements AdminLicenseService {

    // 接口地址 这个后续优化为从数据库中获取
    private static final String BASE_URL = "http://114.117.215.244:7006";
    private static final String KEY = "df704bd7012548049e68db25aff0507f";
    private static final String TOKEN_KEY = "wx:pad:authKey:";
    @Autowired
    private RedisCacheT<String> redisCache;

    @Override
    public List<String> genAuthKey3(String key, GenAuthKey3Request request) {
        String url = BASE_URL + "/admin/GenAuthKey3" + "?key=" + key;
        ApiResponseCommon<List<String>> listApiResponseCommon = WxWorkHttpUtil.postWithType(
                url,
                request,
                new TypeReference<ApiResponseCommon<List<String>>>() {
                }
        );
        log.info("获取授权码结果列表: {}", listApiResponseCommon.getData());
        if(listApiResponseCommon.getCode() == 200){
            return listApiResponseCommon.getData();
        }else{
            throw new BaseException("授权码生成失败：" +  listApiResponseCommon.getText());
        }
    }

    @Override
    public String getToken(Long accountId) {
        String key = TOKEN_KEY + accountId;
        String token = redisCache.getCacheObject(key);
        if(StringUtils.isNotEmpty(token)){
            return token;
        }
        List<String> list = genAuthKey3(KEY, GenAuthKey3Request.builder().Count(1).Type(30000).build());
        token = list.get(0);
        redisCache.setCacheObject(key, token);
        return token;
    }
}