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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;


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

    @Autowired
    private Esb2QunjieTokenUtil esb2QunjieTokenUtil;

    public String finshApplyRquest(String applyId) {
        log.error("senCardMessage start");
        String timestamp = "";
        String token = esb2QunjieTokenUtil.getAccessToken();
        log.error("token:"+token);
        if(StringUtils.isNotBlank(token)){

            JSONObject bodyJson = new JSONObject();
            bodyJson.put("applyId",applyId);
//            String[] sealIdList = new String[]{sealId};
//            bodyJson.put("sealIdList",sealIdList);

            System.out.println("bodyJson:"+bodyJson.toJSONString());

            String message= doPostReqeustByOkHttp(bodyJson.toJSONString(),token);
            if(StringUtils.isNotBlank(message)){
                JSONObject returnData = JSONObject.parseObject(message);
                if(returnData.containsKey("status")){
                    String status = returnData.getString("status");
                    if("0".equals(status)){
                        timestamp = returnData.getString("timestamp");
                    }
                }
            }
        }
        return timestamp;
    }

    public String doPostReqeustByOkHttp(String bodyData,String token){
        String msg = "";

        log.error("bodyData:{}",bodyData);

        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, bodyData);

        try {
            Request request = new Request.Builder()
                    .url(Constants.qunjieHost+Constants.finishUrl)
                    .method("POST", body)
                    .addHeader("Authorization", "Bearer "+ token)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            int code = response.code();
            log.error("code:{}",code);
            msg = response.body().string();
            log.error("msg:"+msg);
        } catch (IOException e) {
            log.error("e:"+e);
            throw new RuntimeException(e);
        }
        return msg;
    }
}
