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

import com.alibaba.fastjson.JSONObject;
import com.weaver.seconddev.chapanda.feishu.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 Esb2FeishuCancelCalendarUtil {
    private final static Logger log = LoggerFactory.getLogger(Esb2FeishuCancelCalendarUtil.class);

    @Autowired
    Esb2FeishuTokenUtil esb2FeishuTokenUtil;

    public String cancelCalendarEvents(String calendar_id,String event_id) {
        log.error("Esb2FeishuGetCalendarPrimaryUtil start");
        String code = "";
        String token = esb2FeishuTokenUtil.getToken();
        log.error("token:"+token);
        if(StringUtils.isNotBlank(token)){

            boolean needNotification = Constants.cancelNeedNotification;
            String cancelCalendarUrl = String.format(Constants.cancelCalendarUrl, calendar_id,event_id) +"?need_notification="+needNotification;
            log.error("cancelCalendarUrl:{}",cancelCalendarUrl);

            String message = doHttpPost(token,cancelCalendarUrl);
            if(StringUtils.isNotBlank(message)){
                JSONObject returnData = JSONObject.parseObject(message);
                if(returnData.containsKey("code")){
                    code = returnData.getString("code");
                }
            }
        }
        return code;
    }

    public String doHttpPost(String token,String cancelCalendarUrl){
        String msg = "";
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
//        "/open-apis/calendar/v4/calendars/feishu.cn_CyZB7DD34hJrcBwosRTtDf@group.calendar.feishu.cn/events/e4bf3b18-0b6d-7037-0ae3-0ad7604b30da_0?need_notification=true"
        RequestBody body = RequestBody.create(mediaType, "");
        try {
            Request request = new Request.Builder()
                    .url(Constants.feishuHost+cancelCalendarUrl)
                    .method("DELETE", body)
                    .addHeader("Authorization", "Bearer "+token)
                    .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;
    }
}
