package com.zehong.web.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.zehong.common.core.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class OutUtil {
    @Autowired
    private RedisCache redisCache;

    @Value("${zhengfu.appId}")
    private String appId;

    @Value("${zhengfu.appSecret}")
    private String appSecret;

    @Value("${zhengfu.tokenUrl}")
    private String tokenUrl;

    @Value("${zhengfu.apiUrl}")
    private String apiUrl;

    /**
     * 获取token
     * @return
     * @throws Exception
     */
    public String getToken()throws Exception
    {
        String token = (String)redisCache.getCacheObject("apiToken");
        if(token!=null){
            token = getNewToken();
        }
        return token;
    }

    /**
     * 获取接口参数
     * @return
     * @throws Exception
     */
    public JSONObject getInfo(String domain, String methodType, Map<String,Object> map)throws Exception
    {
        String token = (String)redisCache.getCacheObject("apiToken");
        if(token==null){
            token = getNewToken();
        }
        JSONObject json = new JSONObject();
        json.put("domain", domain);
        json.put("method", methodType);
        json.put("condition", map);
        JSONObject jobct = (JSONObject) HttpClient.sendPostJson(apiUrl,json,token);
        return jobct;
    }

    /**
     * 上传数据
     * @param methodType
     * @param list
     * @return
     * @throws Exception
     */
    public JSONObject setInfo(String domain, String methodType, List list)throws Exception
    {
        String token = (String)redisCache.getCacheObject("apiToken");
        if(token==null){
            token = getNewToken();
        }
        JSONObject json = new JSONObject();
        json.put("domain", domain);
        json.put("method", methodType);
        json.put("data", list);
        JSONObject jobct = (JSONObject) HttpClient.sendPostJson(apiUrl,json,token);
        return jobct;
    }

    public String getNewToken()throws Exception{
        JSONObject json = new JSONObject();
        json.put("appId", appId);
        json.put("appSecret", appSecret);
        JSONObject jobct = (JSONObject) HttpClient.sendPostJson(tokenUrl,json,null);
        redisCache.setCacheObject("apiToken",(String)((Map<String,Object>)jobct.get("data")).get("accessToken"),7000, TimeUnit.SECONDS);
        return (String)((Map<String,Object>)jobct.get("data")).get("accessToken");
    }
}
