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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weaver.seconddev.chapanda.beisen.constant.Constants;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;


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

    @Autowired
    Token2BeiSenUtil token2BeiSenUtil ;

    public String queryBeisenDeptIdByCode(String code){
        String deptid = "";
        if(StringUtils.isNotEmpty(code)) {
            String token = token2BeiSenUtil.getToken();
            if (StringUtils.isNotBlank(token)) {
                deptid = queryDeptIdByCode(token, code);
            }
        }
        return deptid;
    }

    /***
     *
     * @param token
     * @param deptcode
     * @return
     */
    private String queryDeptIdByCode(String token,String deptcode){
        String deptid = "";
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");

        RequestBody body = RequestBody.create(mediaType, "{\"codes\":[\""+deptcode+"\"]}");

        try {
            Request request = new Request.Builder()
                    .url(Constants.beishenHost+Constants.queryDeptIdByCodeUrl)
                    .method("POST", body)
                    .addHeader("Authorization", "Bearer "+token)
                    .addHeader("Content-Type", "application/json")
                    .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 bodyJson = JSONObject.parseObject(msg);
                    if(bodyJson.containsKey("data")){
                        JSONArray dataArray = bodyJson.getJSONArray("data");
                        if(dataArray.size() > 0){
                            JSONObject itemJson = dataArray.getJSONObject(0);
                            if(itemJson.containsKey("oId")){
                                deptid = itemJson.getString("oId");
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            log.error("e:{}",e);
        }
        log.error("deptid:{}",deptid);
        return deptid;
    }




}
