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

import com.alibaba.fastjson.JSONArray;
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;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


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

    @Autowired
    Esb2FeishuTokenUtil esb2FeishuTokenUtil;

    public String createCalendarEvents(String calendar_id,String summary,String description,
                                      String start_date,String end_date,String location_name,
                                      String location_address) {

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

            JSONObject bodyJson = new JSONObject();
            bodyJson.put("summary",summary);
            bodyJson.put("description",description);
            bodyJson.put("need_notification",Constants.need_notification);

            if(StringUtils.isNotBlank(start_date)){
                long startTime = convertTimeStamp(start_date);
                JSONObject startJson = new JSONObject();
                startJson.put("timestamp",String.valueOf(startTime));
                bodyJson.put("start_time",startJson);
            }

            if(StringUtils.isNotBlank(end_date)){
                long endTime = convertTimeStamp(end_date);
                JSONObject endJson = new JSONObject();
                endJson.put("timestamp",String.valueOf(endTime));
                bodyJson.put("end_time",endJson);
            }

            bodyJson.put("visibility",Constants.visibility);
            bodyJson.put("attendee_ability",Constants.attendee_ability);
            bodyJson.put("free_busy_status",Constants.free_busy_status);


            if(StringUtils.isNotBlank(location_name) && StringUtils.isNotBlank(location_address)){
                JSONObject locationJson = new JSONObject();
                locationJson.put("name",location_name);
                locationJson.put("address",location_address);
                bodyJson.put("location",locationJson);
            }


            bodyJson.put("color",Constants.color);
            JSONArray remindersArray = new JSONArray();
            JSONObject remindersJson = new JSONObject();
            remindersJson.put("minutes",Constants.minutes);
            remindersArray.add(remindersJson);
            bodyJson.put("reminders",remindersArray);

            String uuid  = UUID.randomUUID().toString();
            // https://open.feishu.cn/open-apis/calendar/v4/calendars/feishu.cn_fTzelMMvbKeK8koiHl3uFf@group.calendar.feishu.cn/events?idempotency_key=42a0f05f7c274e07bec07a47841968f5&user_id_type=open_id
            String calendarEventsUrl = String.format(Constants.calendarEventsUrl, calendar_id,uuid);
            log.error("calendarEventsUrl:{}",calendarEventsUrl);
            log.error("bodyJson:{}",bodyJson.toJSONString());

            String message = doHttpPost(bodyJson.toJSONString(),token,calendarEventsUrl);
            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");
                        JSONObject eventJson = dataJson.getJSONObject("event");
                        if(eventJson.containsKey("event_id")){
                            event_id = eventJson.getString("event_id");
                        }
                    }
                }
            }
        }
        return event_id;
    }

    public String doHttpPost(String bodyData,String token,String calendarEventsUrl){
        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.feishuHost+calendarEventsUrl)
                    .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());
        Esb2FeishuCalendarEventsUtil Esb2FeishuCalendarEventsUtil = new Esb2FeishuCalendarEventsUtil();
        Esb2FeishuCalendarEventsUtil.convertTimeStamp(date);
    }

}
