package com.weaver.seconddev.chapanda.qunjie.util;

import com.alibaba.fastjson.JSONObject;
import com.weaver.seconddev.chapanda.qunjie.constant.Constants;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


@Component
public class Esb2QunjieTokenUtil {
    private final static Logger log = LoggerFactory.getLogger(Esb2QunjieTokenUtil.class);

    public String getAccessToken() {

        String accessToken = "";
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");

        try {
            RequestBody body = RequestBody.create(mediaType, "restname="+Constants.restname+"&password="+Constants.password);
            Request request = new Request.Builder()
                    .url(Constants.qunjieHost+Constants.tokenUrl)
                    .method("POST", body)
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .build();
            Response response = client.newCall(request).execute();

            int code = response.code();
            String msg = response.body().string();

            log.error("code:{}",code);
            log.error("msg:{}",msg);

            if(code == 200){
                if(StringUtils.isNotBlank(msg)){
                    JSONObject returnJson = JSONObject.parseObject(msg);
                    if(returnJson.containsKey("status")){
                        String status = returnJson.getString("status");
                        if("0".equals(status)){
                            if(returnJson.containsKey("data")){
                                JSONObject dataJson = returnJson.getJSONObject("data");
                                if(dataJson.containsKey("token")){
                                    accessToken = dataJson.getString("token");
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("e:{}",e.getMessage());
            e.printStackTrace();
        }
        return accessToken;
    }

}
