package org.dromara.app.handler;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.app.domain.AppSchedulingDevice;
import org.dromara.app.domain.bo.AppDeviceBo;
import org.dromara.app.domain.bo.AppWateringLogBo;
import org.dromara.app.domain.vo.AppDeviceVo;
import org.dromara.app.mapper.AppSchedulingDeviceMapper;
import org.dromara.app.mqtt.MqttTopicHandler;
import org.dromara.app.service.IAppDeviceService;
import org.dromara.app.service.IAppWateringLogService;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.json.utils.JsonUtils;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 按键浇水完成处理器，匹配 /{deviceNo}/publish/finish/key。
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class KeyFinishHandler implements MqttTopicHandler {

    private static final Pattern PATTERN = Pattern.compile("^/([^/]+)/publish/finish/key$");

    private final IAppWateringLogService appWateringLogService;
    private final IAppDeviceService appDeviceService;
    private final AppSchedulingDeviceMapper schedulingDeviceMapper;
    private final DeviceIdentityResolver deviceIdentityResolver;

    @Override
    public Pattern topicPattern() {
        return PATTERN;
    }

    @Override
    public void handle(String deviceIdentity, String payload) {
        String deviceNo = null;
        try {
            deviceNo = deviceIdentityResolver.resolveDeviceNo(deviceIdentity);
            if (deviceNo == null) {
                log.warn("[MQTT] 按键浇水完成上报未找到设备 时间={} 设备标识={} 消息体={}",
                    HandlerLogTime.now(), deviceIdentity, payload);
                return;
            }
            Map<String, Object> dto = JsonUtils.parseObject(payload, Map.class);
            AppWateringLogBo logBo = buildWateringLog(deviceNo, dto);
            appWateringLogService.confirmScheduleLog(logBo);
            updateDeviceWorkStatusIdle(deviceNo);
            log.info("[MQTT] 按键浇水完成上报已保存 时间={} 设备编号={} 消息体={}", HandlerLogTime.now(), deviceNo, payload);
        } catch (Exception e) {
            log.error("[MQTT] 按键浇水完成上报处理失败 时间={} 设备标识={} 设备编号={} 消息体={}",
                HandlerLogTime.now(), deviceIdentity, deviceNo, payload, e);
        }
    }

    private AppWateringLogBo buildWateringLog(String topicDeviceNo, Map<String, Object> dto) {
        String payloadDeviceNo = valueAsString(dto.get("deviceNo"));
        if (StringUtils.isNotBlank(payloadDeviceNo) && !topicDeviceNo.equals(payloadDeviceNo)) {
            log.warn("[MQTT] 按键浇水完成上报设备编号不一致 时间={} 主题设备编号={} 消息体设备编号={}", HandlerLogTime.now(), topicDeviceNo, payloadDeviceNo);
        }

        Date receivedAt = new Date();
        Date startTime = parseStartTime(valueAsString(dto.get("startTime")));
        Date plannedEndTime = resolvePlannedEndTime(
            startTime,
            parseOptionalTime(valueAsString(dto.get("endTime"))),
            valueAsInteger(dto.get("durationMin"))
        );
        Date endTime = resolveActualEndTime(receivedAt, plannedEndTime);
        Integer durationMin = calculateDurationMin(startTime, endTime);

        AppWateringLogBo logBo = new AppWateringLogBo();
        logBo.setDeviceNo(topicDeviceNo);
        logBo.setCommandId(valueAsString(dto.get("commandId")));
        logBo.setUserId(queryUserId(topicDeviceNo));
        logBo.setScheduleId(0L);
        logBo.setStartTime(startTime);
        logBo.setDurationMin(durationMin == null ? null : String.valueOf(durationMin));
        logBo.setTriggerType("1");
        logBo.setStatus("0");
        if ("schedule".equals(valueAsString(dto.get("triggerON")))){
            logBo.setTriggerType("0");
            logBo.setScheduleId(queryScheduleId(topicDeviceNo));
        }
        logBo.setCreateTime(receivedAt);
        logBo.setEndTime(endTime);
        logBo.setRemark("0".equals(logBo.getTriggerType()) ? "设备上报排程浇水完成" : "设备按键完成浇水");
        return logBo;
    }

    private void updateDeviceWorkStatusIdle(String deviceNo) {
        AppDeviceBo deviceBo = new AppDeviceBo();
        deviceBo.setDeviceNo(deviceNo);
        deviceBo.setWorkStatus("0");
        appDeviceService.updateByBo(deviceBo);
    }

    private Long queryUserId(String deviceNo) {
        AppDeviceVo device = appDeviceService.queryById(deviceNo);
        return device == null ? null : device.getUserId();
    }

    private Long queryScheduleId(String deviceNo) {
        List<AppSchedulingDevice> schedulingDevices = schedulingDeviceMapper.selectList(
            Wrappers.<AppSchedulingDevice>lambdaQuery()
                .eq(AppSchedulingDevice::getDeviceNo, deviceNo)
        );
        if (schedulingDevices == null || schedulingDevices.isEmpty()) {
            log.warn("[MQTT] 按键浇水完成上报未找到设备绑定的排程 时间={} 设备编号={}", HandlerLogTime.now(), deviceNo);
            return 0L;
        }
        if (schedulingDevices.size() > 1) {
            log.warn("[MQTT] 按键浇水完成上报匹配到多个排程 时间={} 设备编号={} 数量={}", HandlerLogTime.now(), deviceNo, schedulingDevices.size());
        }
        return schedulingDevices.get(0).getScheduleId();
    }

    private Date parseStartTime(String startTime) {
        if (StringUtils.isBlank(startTime)) {
            return new Date();
        }
        for (String pattern : new String[]{"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm"}) {
            try {
                SimpleDateFormat format = new SimpleDateFormat(pattern);
                format.setLenient(false);
                return format.parse(startTime);
            } catch (ParseException ignored) {
                // Try the next supported format.
            }
        }
        throw new IllegalArgumentException("Unsupported startTime format: " + startTime);
    }

    private Date parseOptionalTime(String time) {
        if (StringUtils.isBlank(time)) {
            return null;
        }
        return parseStartTime(time);
    }

    private Date resolvePlannedEndTime(Date startTime, Date payloadEndTime, Integer durationMin) {
        if (startTime != null && durationMin != null && durationMin > 0) {
            return new Date(startTime.getTime() + durationMin * 60000L);
        }
        return payloadEndTime;
    }

    private Date resolveActualEndTime(Date receivedAt, Date plannedEndTime) {
        if (plannedEndTime == null) {
            return receivedAt;
        }
        return receivedAt.before(plannedEndTime) ? receivedAt : plannedEndTime;
    }

    private Integer calculateDurationMin(Date startTime, Date endTime) {
        if (startTime == null || endTime == null) {
            return null;
        }
        long diffMillis = endTime.getTime() - startTime.getTime();
        if (diffMillis < 0) {
            log.warn("[MQTT] 按键浇水完成上报结束时间早于开始时间 时间={} 开始时间={} 结束时间={}", HandlerLogTime.now(), startTime, endTime);
            return 0;
        }
        return (int) (diffMillis / 60000L);
    }

    private String valueAsString(Object value) {
        return value == null ? null : String.valueOf(value);
    }

    private Integer valueAsInteger(Object value) {
        if (value == null) {
            return null;
        }
        if (value instanceof Number number) {
            return number.intValue();
        }
        String text = String.valueOf(value);
        return StringUtils.isBlank(text) ? null : Integer.valueOf(text);
    }
}
