package com.example.iot_controlhost.utils.timer;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

import com.blankj.utilcode.util.TimeUtils;
import com.example.iot_controlhost.MyApp;
import com.example.iot_controlhost.model.MyTask;
import com.example.iot_controlhost.receiver.UvTaskReceiver;
import com.example.iot_controlhost.utils.MMKVUtil;
import com.example.iot_controlhost.utils.global.RoomController;
import com.example.iot_controlhost.utils.log.MyLog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 消毒灯定时任务工具类
 */
public class UVTaskUtil {
    /**
     * 消毒任务
     */
    public static final String UV_TASK = "UV_TASK";

    public static boolean addUvTask(MyTask task) {
        String json = MMKVUtil.get(UV_TASK, "[]");
        List<MyTask> temp = new Gson().fromJson(json, new TypeToken<List<MyTask>>() {
        }.getType());
        for (MyTask t : getUvTask()) {
            if (hasConflict(task.getStartTimeHour(), task.getStartTimeMinute(), task.getEndTimeHour(), task.getEndTimeMinute(),
                    t.getStartTimeHour(), t.getStartTimeMinute(), t.getEndTimeHour(), t.getEndTimeMinute())) {
                return false;
            }
        }
        temp.add(task);
        MMKVUtil.put(UV_TASK, new Gson().toJson(temp));
        startTask(task);
        return true;
    }

    public static boolean hasConflict(int startHour1, int startMinute1, int endHour1, int endMinute1,
                                      int startHour2, int startMinute2, int endHour2, int endMinute2) {
        // 计算第一个时间段的开始时间和结束时间的总分钟数
        int startTime1InMinutes = startHour1 * 60 + startMinute1;
        int endTime1InMinutes = endHour1 * 60 + endMinute1;

        // 计算第二个时间段的开始时间和结束时间的总分钟数
        int startTime2InMinutes = startHour2 * 60 + startMinute2;
        int endTime2InMinutes = endHour2 * 60 + endMinute2;

        // 检查是否存在冲突
        boolean conflict = (startTime1InMinutes >= startTime2InMinutes && startTime1InMinutes < endTime2InMinutes) ||
                (endTime1InMinutes > startTime2InMinutes && endTime1InMinutes <= endTime2InMinutes) ||
                (startTime2InMinutes >= startTime1InMinutes && startTime2InMinutes < endTime1InMinutes) ||
                (endTime2InMinutes > startTime1InMinutes && endTime2InMinutes <= endTime1InMinutes);

        return conflict;
    }

    /**
     * 更新定时任务
     *
     * @param myTask 定时任务
     */
    public static void updateUvTask(MyTask myTask) {
        String json = MMKVUtil.get(UV_TASK, "[]");
        List<MyTask> temp = new Gson().fromJson(json, new TypeToken<List<MyTask>>() {
        }.getType());
        for (int i = 0; i < temp.size(); i++) {
            if (temp.get(i).getId() == myTask.getId()) {
                temp.set(i, myTask);
                break;
            }
        }
        MMKVUtil.put(UV_TASK, new Gson().toJson(temp));
    }

    public static List<MyTask> getUvTask() {
        String json = MMKVUtil.get(UV_TASK, "[]");
        List<MyTask> temp = new Gson().fromJson(json, new TypeToken<List<MyTask>>() {
        }.getType());
        return temp;
    }

    public static void removeUvTask(MyTask myTask) {
        String json = MMKVUtil.get(UV_TASK, "[]");
        List<MyTask> temp = new Gson().fromJson(json, new TypeToken<List<MyTask>>() {
        }.getType());
        temp.remove(myTask);
        MMKVUtil.put(UV_TASK, new Gson().toJson(temp));
        //关闭定时器
        stopTask(myTask);
    }

    public static void removeAllUvTask() {
        MMKVUtil.put(UV_TASK, "[]");
    }

    /**
     * 开始定时任务
     *
     * @param task
     */
    public static void startTask(MyTask task) {
        if (!RoomController.uvLight.isAvailable()) {
            MyLog.auto("消毒灯定时任务：消毒灯不可用，消毒任务启用无效");
            return;
        }
        Context context = MyApp.getAppContext();
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, UvTaskReceiver.class);

        // 设置开启灯的时间
        Calendar openCalendar = Calendar.getInstance();
        openCalendar.set(Calendar.HOUR_OF_DAY, task.getStartTimeHour());
        openCalendar.set(Calendar.MINUTE, task.getStartTimeMinute());
        openCalendar.set(Calendar.SECOND, 0);
        // 如果开启时间在当前时间之前，将开启时间设定为明天的同一时间
        if (openCalendar.before(Calendar.getInstance())) {
            openCalendar.add(Calendar.DAY_OF_YEAR, 1);
        }
        long openTimeInMillis = openCalendar.getTimeInMillis();
        MyLog.auto("定时任务：" + TimeUtils.date2String(new Date(openTimeInMillis)) + "时开启消毒灯");
        intent.setAction(UvTaskReceiver.OPEN_LIGHT);
        PendingIntent openPendingIntent = PendingIntent.getBroadcast(context, task.getId() * 3, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, openTimeInMillis, AlarmManager.INTERVAL_DAY, openPendingIntent);
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, openTimeInMillis, openPendingIntent);
        // 设置关闭灯的时间
        Calendar closeCalendar = Calendar.getInstance();
        closeCalendar.set(Calendar.HOUR_OF_DAY, task.getEndTimeHour());
        closeCalendar.set(Calendar.MINUTE, task.getEndTimeMinute());
        closeCalendar.set(Calendar.SECOND, 0);
        // 如果关闭时间在当前时间之前，将关闭时间设定为明天的同一时间
        if (closeCalendar.before(Calendar.getInstance())) {
            closeCalendar.add(Calendar.DAY_OF_YEAR, 1);
        }
        long closeTimeInMillis = closeCalendar.getTimeInMillis();
        MyLog.auto("定时任务：" + TimeUtils.date2String(new Date(closeTimeInMillis)) + "时关闭消毒灯");
        intent.setAction(UvTaskReceiver.CLOSE_LIGHT);
        PendingIntent closePendingIntent = PendingIntent.getBroadcast(context, task.getId() * 3 + 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, closeTimeInMillis, AlarmManager.INTERVAL_DAY, closePendingIntent);
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, closeTimeInMillis, closePendingIntent);

    }

    /**
     * 关闭定时任务
     *
     * @param myTask
     */
    public static void stopTask(MyTask myTask) {
        Context context = MyApp.getAppContext();
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, UvTaskReceiver.class);

        PendingIntent openPendingIntent = PendingIntent.getBroadcast(context, myTask.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
        PendingIntent closePendingIntent = PendingIntent.getBroadcast(context, -myTask.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT);

        alarmManager.cancel(openPendingIntent);
        alarmManager.cancel(closePendingIntent);
    }

    public static void restartTask() {
        List<MyTask> tasks = getUvTask();
        for (MyTask task : tasks) {
            startTask(task);
        }
    }
}
