package com.fuyuanshen.global.mqtt.rule.bjq;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSONObject;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.core.domain.model.LoginUser;
import com.fuyuanshen.common.core.utils.StringUtils;
import com.fuyuanshen.common.core.utils.date.DurationUtils;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.common.satoken.utils.LoginHelper;
import com.fuyuanshen.equipment.domain.Device;
import com.fuyuanshen.equipment.domain.bo.DeviceAlarmBo;
import com.fuyuanshen.equipment.domain.vo.DeviceAlarmVo;
import com.fuyuanshen.equipment.service.DeviceService;
import com.fuyuanshen.equipment.service.IDeviceAlarmService;
import com.fuyuanshen.global.mqtt.base.MqttMessageRule;
import com.fuyuanshen.global.mqtt.base.MqttRuleContext;
import com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants;
import com.fuyuanshen.global.mqtt.constants.LightingCommandTypeConstants;
import com.fuyuanshen.global.mqtt.listener.domain.FunctionAccessStatus;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.Date;
import java.util.concurrent.CompletableFuture;

import static com.fuyuanshen.common.core.constant.GlobalConstants.FUNCTION_ACCESS_KEY;
import static com.fuyuanshen.common.core.constant.GlobalConstants.GLOBAL_REDIS_KEY;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.*;

/**
 * 灯光模式订阅设备回传消息
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class BjqAlarmRule implements MqttMessageRule {

    private final IDeviceAlarmService deviceAlarmService;
    private final DeviceService deviceService;


    @Override
    public String getCommandType() {
        return LightingCommandTypeConstants.ALARM_MESSAGE;
    }

    @Override
    public void execute(MqttRuleContext context) {
        String functionAccess = FUNCTION_ACCESS_KEY + context.getDeviceImei();
        try {
            Object[] convertArr = context.getConvertArr();

            String convertValue = convertArr[1].toString();
            if (StringUtils.isNotBlank(convertValue)) {
                // 将设备状态信息存储到Redis中
                String deviceRedisKey = GlobalConstants.GLOBAL_REDIS_KEY + DeviceRedisKeyConstants.DEVICE_KEY_PREFIX + context.getDeviceImei() + DEVICE_ALARM_KEY_PREFIX;
                String sendMessageIng = GLOBAL_REDIS_KEY+ DEVICE_KEY_PREFIX + context.getDeviceImei() + ":messageSending";
                if ("1".equals(convertValue)) {
                    RedisUtils.setCacheObject(sendMessageIng, "1", Duration.ofDays(1));
                    // 存储到Redis
                    RedisUtils.setCacheObject(deviceRedisKey, "1");
                }else if ("0".equals(convertValue)){
                    RedisUtils.deleteObject(sendMessageIng);
                    RedisUtils.deleteObject(deviceRedisKey);
                }
            }
            RedisUtils.setCacheObject(functionAccess, FunctionAccessStatus.OK.getCode(), Duration.ofSeconds(20));
            //  保存告警信息
            String deviceImei = context.getDeviceImei();
            // 设备告警状态 0:解除告警 1:报警产生
            Byte state = (Byte) convertArr[1];
            savaAlarm(deviceImei, state);

        } catch (Exception e) {
            log.error("处理告警命令时出错", e);
            RedisUtils.setCacheObject(functionAccess, FunctionAccessStatus.FAILED.getCode(), Duration.ofSeconds(20));
        }
    }


    public void savaAlarm(String deviceImei, Byte state) {
        DeviceAlarmVo deviceAlarmVo = deviceAlarmService.queryLatestByDeviceImei(deviceImei);
        DeviceAlarmBo deviceAlarmBo = new DeviceAlarmBo();

        // 解除告警
        if (state == 0) {
            if (deviceAlarmVo != null) {
                if (deviceAlarmVo.getFinishTime() == null) {
                    BeanUtil.copyProperties(deviceAlarmVo, deviceAlarmBo);
                    deviceAlarmBo.setFinishTime(new Date());
                    String durationBetween = DurationUtils.getDurationBetween(deviceAlarmVo.getStartTime(), deviceAlarmBo.getFinishTime());
                    deviceAlarmBo.setDurationTime(durationBetween);
                    // 0已处理，1未处理
                    deviceAlarmBo.setTreatmentState(0);
                    // 告警状态，0 解除告警， 1 告警中
                    deviceAlarmBo.setAlarmState(0);
                    deviceAlarmService.updateByBo(deviceAlarmBo);
                }
            }
        }

        // 报警产生
        if (state == 1) {
            if (deviceAlarmVo == null || deviceAlarmVo.getFinishTime() != null) {

                Device device = deviceService.selectDeviceByImei(deviceImei);
                deviceAlarmBo.setDeviceId(device.getId());
                deviceAlarmBo.setDeviceImei(deviceImei);
                //  0-强制报警，1-撞击闯入，2-自动报警，3-电子围栏告警
                deviceAlarmBo.setDeviceAction(0);
                deviceAlarmBo.setStartTime(new Date());
                // 0已处理，1未处理
                deviceAlarmBo.setTreatmentState(1);
                // 告警状态，0 解除告警， 1 告警中
                deviceAlarmBo.setAlarmState(1);

                // LoginUser loginUser = LoginHelper.getLoginUser();
                // deviceAlarmBo.setCreateBy(loginUser.getUserId());
                deviceAlarmBo.setTenantId(device.getTenantId());

                String location = RedisUtils.getCacheObject(GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX + deviceImei + DEVICE_LOCATION_KEY_PREFIX);
                if (StringUtils.isNotBlank(location)) {
                    JSONObject jsonObject = JSONObject.parseObject(location);
                    deviceAlarmBo.setLocation(jsonObject.getString("address"));
                }
                deviceAlarmService.insertByBo(deviceAlarmBo);
            }
        }

    }

}
