package com.fuyuanshen.web.controller.device;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.alibaba.fastjson.JSON;
import com.fuyuanshen.app.domain.bo.AppPersonnelInfoBo;
import com.fuyuanshen.app.domain.dto.AppDeviceLogoUploadDto;
import com.fuyuanshen.app.domain.dto.DeviceInstructDto;
import com.fuyuanshen.app.domain.vo.AppDeviceDetailVo;
import com.fuyuanshen.common.core.domain.R;
import com.fuyuanshen.common.core.utils.StringUtils;
import com.fuyuanshen.common.core.validate.AddGroup;
import com.fuyuanshen.common.ratelimiter.annotation.FunctionAccessAnnotation;
import com.fuyuanshen.common.ratelimiter.annotation.FunctionAccessBatcAnnotation;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.common.web.core.BaseController;
import com.fuyuanshen.equipment.domain.dto.AppDeviceSendMsgBo;
import com.fuyuanshen.web.domain.Dto.DeviceXinghanInstructDto;
import com.fuyuanshen.web.domain.Dto.SystemVersionDto;
import com.fuyuanshen.web.domain.vo.DeviceXinghanDetailVo;
import com.fuyuanshen.web.service.device.DeviceXinghanBizService;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.Duration;
import java.util.List;

import static com.fuyuanshen.common.core.constant.GlobalConstants.GLOBAL_REDIS_KEY;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_ALARM_MESSAGE_KEY_PREFIX;
import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_KEY_PREFIX;

/**
 * 设备控制类  HBY670
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/xinghan/device")
public class DeviceXinghanController extends BaseController {

    private final DeviceXinghanBizService deviceXinghanBizService;


    /**
     * 获取设备详细信息
     *
     * @param id 主键
     */
    @GetMapping("/{id}")
    public R<DeviceXinghanDetailVo> getInfo(@NotNull(message = "主键不能为空")
                                        @PathVariable Long id) {
        return R.ok(deviceXinghanBizService.getInfo(id));
    }

    /**
     * 人员信息登记
     */
    @PostMapping(value = "/registerPersonInfo")
//    @FunctionAccessAnnotation("registerPersonInfo")
    public R<Void> registerPersonInfo(@Validated(AddGroup.class) @RequestBody AppPersonnelInfoBo bo) {
        return toAjax(deviceXinghanBizService.registerPersonInfo(bo));
    }

    /**
     * 发送紧急通知
     */
    @PostMapping(value = "/sendAlarmMessage")
    @FunctionAccessBatcAnnotation(value = "sendAlarmMessage", timeOut = 5, batchMaxTimeOut = 10)
    public R<Void> sendAlarmMessage(@RequestBody AppDeviceSendMsgBo bo) {
        return toAjax(deviceXinghanBizService.sendAlarmMessage(bo));
    }

    /**
     * 上传设备logo图片
     */
    @PostMapping("/uploadLogo")
    @FunctionAccessAnnotation("uploadLogo")
    public R<Void> upload(@Validated @ModelAttribute AppDeviceLogoUploadDto bo) {

        MultipartFile file = bo.getFile();
        if(file.getSize()>1024*1024*2){
            return R.warn("图片不能大于2M");
        }
        deviceXinghanBizService.uploadDeviceLogo(bo);

        return R.ok();
    }

    /**
     * 静电预警档位
     * 3,2,1,0,分别表示高档/中档/低挡/关闭
     */
    @PostMapping("/DetectGradeSettings")
    public R<Void> DetectGradeSettings(@RequestBody DeviceXinghanInstructDto params) {
        // params 转 JSONObject
        deviceXinghanBizService.upDetectGradeSettings(params);
        return R.ok();
    }

    /**
     * 照明档位
     * 照明档位，2,1,0,分别表示弱光/强光/关闭
     */
    @PostMapping("/LightGradeSettings")
    public R<Void> LightGradeSettings(@RequestBody DeviceXinghanInstructDto params) {
        // params 转 JSONObject
        deviceXinghanBizService.upLightGradeSettings(params);
        return R.ok();
    }

    /**
     * SOS档位
     * SOS档位，2,1,0, 分别表示红蓝模式/爆闪模式/关闭
     */
    @PostMapping("/SOSGradeSettings")
    public R<Void> SOSGradeSettings(@RequestBody DeviceXinghanInstructDto params) {
        // params 转 JSONObject
        deviceXinghanBizService.upSOSGradeSettings(params);
        return R.ok();
    }

    /**
     * SOS档位 批量
     * SOS档位，2,1,0, 分别表示红蓝模式/爆闪模式/关闭
     */
    @PostMapping("/SOSGradeSettingsBatch")
    public R<Void> SOSGradeSettingsBatch(@RequestBody DeviceXinghanInstructDto params) {
        // params 转 JSONObject
        deviceXinghanBizService.sendCommandBatch(params,"ins_SOSGrade","SOS档位");
        return R.ok();
    }

    /**
     * 静止报警状态
     * 静止报警状态，0-未静止报警，1-正在静止报警。
     */
    @PostMapping("/ShakeBitSettings")
    public R<Void> ShakeBitSettings(@RequestBody DeviceXinghanInstructDto params) {
        // params 转 JSONObject
        deviceXinghanBizService.upShakeBitSettings(params);
        return R.ok();
    }

    /**
     * 版本更新
     */
    @SaCheckPermission("system:appVersion:up")
    @PostMapping("/UpVersion")
    public R<Void> VersionSettings(@RequestBody List<SystemVersionDto> params) {
        // params 已经是 List<SystemVersionDto>
        // 2. 转 JSON 并写 Redis，key 自己定，带个过期时间
        String versionKey = GLOBAL_REDIS_KEY + "System:Version:Xinghan";
        String json = JSON.toJSONString(params);          // fastjson
        if (StringUtils.isBlank(json)) {   // hutool 工具，可用 StringUtils.isBlank 代替
            return R.fail("信息无效");
        }
        // 缓存告警消息到Redis
        RedisUtils.setCacheObject(versionKey, json, Duration.ofDays(30));
        return R.ok();
    }

}
