package com.jpsoft.shinestar.modules.common.utils;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.jpsoft.shinestar.modules.common.service.impl.RedisServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 墨鱼_mo
 * @date 2019-8-6 9:43
 */
@Component
public class ApiUtil {

    @Value("${doorApi.apiId}")
    private String apiId;

    @Value("${doorApi.apiKey}")
    private String apiKey;

    @Value("${doorApi.referer}")
    private String referer;

    @Autowired
    private RedisServiceImpl redisService;


    public String getApiToken(){
        HashMap map = new HashMap();

        map.put("apiid",apiId);
        map.put("apikey", apiKey);

        Map<String,String> heardMap = new HashMap<>();
        heardMap.put("referer",referer);


        String body = HttpRequest.post("https://api.parkline.cc/api/token").addHeaders(heardMap).form(map).execute().body();
        JSONObject jsonbody = JSONObject.parseObject(body);
        String apiToken = jsonbody.getString("access_token");

        if (StringUtils.isNotBlank(apiToken)){

            redisService.put("apiToken","apiToken",apiToken,7200L);

            return apiToken;


        }
        else {
            return "";
        }





    }


    public JSONObject httpRequest(String url, String token,String typeid,String devid,String lockid,String tel,String filedata){
        HashMap map = new HashMap();

        map.put("token",token);
        map.put("typeid", typeid);
        map.put("devid",devid);
        map.put("lockid",lockid);
        map.put("tel",tel);
        map.put("filedata",filedata);



        String body = HttpRequest.post(url).header("referer",referer).form(map).execute().body();
        JSONObject jsonbody = JSONObject.parseObject(body);
        return jsonbody;


    }

    public Boolean testApiToken(String apiToken,String devid){
        if (StringUtils.isBlank(apiToken)){
            return false;
        }

        JSONObject resultJSON = httpRequest("https://api.parkline.cc/api/statuscgi",apiToken,"",devid,"","","");
        if (resultJSON.getString("code").equals("402")){
            return false;
        }
        else {
            return true;
        }
    }

}
