package com.zksy.lamp.controller;

import com.zksy.common.core.domain.Result;
import com.zksy.lamp.server.ExecutionServer;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.Instant;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 * @version 1.0
 * @project dh-server-micro
 * @description 路灯服务
 * @date 2025/2/10 15:00:46
 */
@RequestMapping("/execution")
@RestController
public class ExecutionController {
    @Autowired
    private ExecutionServer server;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("/firstRelay")
    @ApiOperation(value = "第一路继电器闭合、断开", notes = "第一路继电器闭合、断开")
    public Result<?> firstRelay(@ApiParam(value = "第一路继电器（0-断开，1-闭合）", required = true)
                                @RequestParam(value = "value") Integer value) {
        String data = "AT+STACH1=" + value + "\r\n";
        String msg = server.ExecutionData(data);
        return Result.ok(msg);
    }

    @GetMapping("/secondRelay")
    @ApiOperation(value = "第二路继电器闭合、断开", notes = "第二路继电器闭合、断开")
    public Result<?> secondRelay(@ApiParam(value = "第二路继电器（0-断开，1-闭合）", required = true)
                                 @RequestParam(value = "value") Integer value) {
        String data = "AT+STACH2=" + value + "\r\n";
        String msg = server.ExecutionData(data);
        return Result.ok(msg);
    }

    @GetMapping("/timingOn")
    @ApiOperation(value = "定时开启", notes = "定时开启")
    public Result<?> timingOn(@ApiParam(value = "定时开启时间，时：分：秒，示例：17:00:00", required = true)
                              @RequestParam(value = "value") String value) {
        if (!isValidTime(value)) {
            return Result.error(400, "无效的时间格式，请使用 HH:mm:ss 格式");
        }

        if (Boolean.TRUE.equals(redisTemplate.hasKey("lock:on"))) {
            Instant now = Instant.now();
            long currentTime = now.toEpochMilli();
            String lockTimeStr = redisTemplate.opsForValue().get("lock:on");
            if (lockTimeStr != null) {
                try {
                    long lockTime = Long.parseLong(lockTimeStr);
                    long remainingTime = (lockTime - currentTime) / 1000;
                    return Result.error(429, "一小时只能发布一次还剩" + remainingTime + "秒");
                } catch (NumberFormatException e) {
                    return Result.error(500, "内部服务器错误");
                }
            }
        }

        long t = Instant.now().toEpochMilli();
        long lockTime = 3600000; // 3600000 毫秒 = 1 小时
        String data = "AT+AUTOCONT=8,task1,[CYC:1],[T:3,0|1|2|3|4|5|6," + value + "],[DO:0,1,1,100000,100000,1000000],[N:1,0]\r\n";
        String msg = server.ExecutionData(data);
        redisTemplate.opsForValue().set("lock:on", String.valueOf(t + lockTime), lockTime, TimeUnit.MILLISECONDS);
        return Result.ok(msg);
    }

    @GetMapping("/timedShutdown")
    @ApiOperation(value = "定时关闭", notes = "定时关闭")
    public Result<?> timedShutdown(@ApiParam(value = "定时关闭时间，时：分：秒，示例：06:00:00", required = true)
                                   @RequestParam(value = "value") String value) {
        if (!isValidTime(value)) {
            return Result.error(400, "无效的时间格式，请使用 HH:mm:ss 格式");
        }

        if (Boolean.TRUE.equals(redisTemplate.hasKey("lock:off"))) {
            Instant now = Instant.now();
            long currentTime = now.toEpochMilli();
            String lockTimeStr = redisTemplate.opsForValue().get("lock:off");
            if (lockTimeStr != null) {
                try {
                    long lockTime = Long.parseLong(lockTimeStr);
                    long remainingTime = (lockTime - currentTime) / 1000;
                    return Result.error(429, "一小时只能发布一次还剩" + remainingTime + "秒");
                } catch (NumberFormatException e) {
                    return Result.error(500, "内部服务器错误");
                }
            }
        }

        long t = Instant.now().toEpochMilli();
        long lockTime = 3600000; // 3600000 毫秒 = 1 小时
        String data = "AT+AUTOCONT=8,task2,[CYC:1],[T:3,0|1|2|3|4|5|6," + value + "],[DO:0,1,0,100000,100000,1000000],[N:1,0]\r\n";
        String msg = server.ExecutionData(data);
        redisTemplate.opsForValue().set("lock:off", String.valueOf(t + lockTime), lockTime, TimeUnit.MILLISECONDS);
        return Result.ok(msg);
    }

    private boolean isValidTime(String time) {
        try {
            LocalTime.parse(time, DateTimeFormatter.ofPattern("HH:mm:ss"));
            return true;
        } catch (DateTimeParseException e) {
            return false;
        }
    }


    @GetMapping("/queryScheduledTasks")
    @ApiOperation(value = "查询定时", notes = "查询定时")
    public Result<?> queryScheduledTasks() {
        String data = "AT+AUTOCONT=0\r\n";
        String msg = server.ExecutionData(data);
        return Result.ok(msg);
    }
}
