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;
import java.text.ParseException;
import java.text.SimpleDateFormat;


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

    @Autowired
    Esb2FeishuTokenUtil esb2FeishuTokenUtil;

    public String createCalendarTimeOff(String user_open_id,String summary,String description,
                                      String start_date,String end_date,String type) {

        String timeoff_event_id = "";
        log.error("Esb2FeishuCalendarEventsUtil start");
        String token = esb2FeishuTokenUtil.getToken();
        log.error("token:"+token);
        if(StringUtils.isNotBlank(token)){

            JSONObject bodyJson = new JSONObject();
            bodyJson.put("user_id",user_open_id);
            bodyJson.put("title",summary);
            bodyJson.put("description",description);
            bodyJson.put("timezone",Constants.timeZone);
            if("timestamp".equals(type)){
                long startTime = convertTimeStamp(start_date);
                long endTime = convertTimeStamp(end_date);
                bodyJson.put("start_time",String.valueOf(startTime));
                bodyJson.put("end_time",String.valueOf(endTime));
            }else{
                bodyJson.put("start_time",start_date);
                bodyJson.put("end_time",end_date);
            }

            String message = doHttpPost(bodyJson.toJSONString(),token);
            if(StringUtils.isNotBlank(message)){
                JSONObject returnData = JSONObject.parseObject(message);
                if(returnData.containsKey("code")){
                    String code = returnData.getString("code");
                    if("0".equals(code)){
                        JSONObject dataJson = returnData.getJSONObject("data");
                        if(dataJson.containsKey("timeoff_event_id")){
                            timeoff_event_id = dataJson.getString("timeoff_event_id");
                        }
                    }
                }
            }
        }
        return timeoff_event_id;
    }


    public String doHttpPost(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);

//        RequestBody body = RequestBody.create(mediaType, "{\n    \"user_id\":\"ou_8ff7816cfa8cda57643cac2a06fbdc7e\",\n    \"timezone\":\"Asia/Shanghai\",\n    \"start_time\":\"2026-07-26\",\n    \"end_time\":\"2026-07-27\",\n    \"title\":\"石磊请假流程-2026-06-19\",\n    \"description\":\"石磊请假流程\"\n}");

        try {

            Request request = new Request.Builder()
                    .url(Constants.feishuHost+Constants.createTimeoffUrl)
                    .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;
    }


    public long convertTimeStamp(String date) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long timestamp = 0L;
        if(StringUtils.isNotBlank(date)){
            System.out.println(date.length());
            if(date.length() == 10){
                date = date + " 00:00:00";
            }else if(date.length() == 16){
                date = date + ":00";
            }

            System.out.println(date);
            System.out.println(date.length());

            if(date.length() == 19){
                try {
                    timestamp = sdf.parse(date).getTime() / 1000 ;
                } catch (ParseException e) {
                    log.error("e:{}",e);
                    throw new RuntimeException(e);
                }
            }
            System.out.println(timestamp);
        }
        return timestamp;
    }

    public static void main(String[] args) {
        String date = "2025-07-18 09:00";
        System.out.println(date.length());
        Esb2FeishuCreateCalendarTimeoffUtil Esb2FeishuCalendarEventsUtil = new Esb2FeishuCreateCalendarTimeoffUtil();
        Esb2FeishuCalendarEventsUtil.convertTimeStamp(date);
    }

}
