package com.zd.laboratory.controller;

import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.zd.common.core.constant.CacheConstants;
import com.zd.common.core.domain.per.PerFun;
import com.zd.common.core.domain.per.PerPrefix;
import com.zd.common.core.enums.HardwareOperate;
import com.zd.common.core.utils.SpringUtils;
import com.zd.common.core.web.controller.BaseController;
import com.zd.common.core.web.domain.ResultData;
import com.zd.common.core.web.page.TableDataInfo;
import com.zd.common.redis.service.RedisService;
import com.zd.common.security.annotation.PreAuthorize;
import com.zd.common.swagger.config.Knife4jConfiguration;
import com.zd.laboratory.domain.dto.LabSubListQuery;
import com.zd.laboratory.domain.vo.LabSubjectVO;
import com.zd.laboratory.event.OnecStatusEvent;
import com.zd.laboratory.mapper.LabSubjectAccessRecordMapper;
import com.zd.laboratory.mqtt.entiy.EquipmentStatus;
import com.zd.laboratory.mqtt.service.impl.SubMessageSendManager;
import com.zd.laboratory.service.ILabHardwareService;
import com.zd.laboratory.service.impl.LabSubjectManagerService;
import com.zd.laboratory.service.impl.SubQueryManager;
import com.zd.laboratory.socket.command.Symbol;
import com.zd.system.api.laboratory.domain.LabSubjectControllerVO;
import com.zd.system.api.laboratory.domain.TotalByID;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 实验室控制管理
 *
 * @Author: zhoupan
 * @Date: 2021/09/17/15:02
 * @Description:
 */
@Api(tags = {"实验室控制管理"})
@ApiSupport(author = Knife4jConfiguration.Author.ZP)
@RestController
@RequestMapping("/subject/manger")
public class LabSubMangerController extends BaseController {

    @Autowired
    LabSubjectManagerService subjectManagerService;
    @Autowired
    SubMessageSendManager subMessageSendManager;
    @Autowired
    RedisService redisService;
    @Autowired
    ILabHardwareService labHardwareService;

    @Autowired
    SubQueryManager subQueryManager;

    @Autowired
    LabSubjectAccessRecordMapper labSubjectAccessRecordMapper;

    /**
     * 查询实验室控制数据列表- 数据权限（包括负责人）
     * 2021年11月18日 放弃使用  重构了实验室查询
     * @see LabSubMangerV2Controller
     * @return
     */
//    @Deprecated 观测V2 并未使用，故保留
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_SUBJECT + PerFun.LIST)
    @ApiOperation("查询实验室控制数据列表- 数据权限（包括负责人）")
    @GetMapping("/list")
    public TableDataInfo<List<LabSubjectVO>> querySubCListVO(LabSubListQuery labSubListQuery) {
        startPage();
        List<LabSubjectVO> list = subjectManagerService.querySubCListVO(labSubListQuery);
        if(list==null){
            list = new ArrayList <>();
        }
        return getDataTable(list);
    }

    /**
     * 查询实验室详情
     * @param id 实验室ID
     * @param type 1 只查硬件数据， 0 查全部详情
     * @return
     */
    @ApiOperation("查询实验室详情")
    @GetMapping("/query/{id}/{type}")
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_SUBJECT + PerFun.QUERY)
    public LabSubjectControllerVO querySubById(@PathVariable("id") Long id, @PathVariable("type") Integer type) {
        return subjectManagerService.querySubById(id, type);
    }

    /**
     * 楼栋实验室统计
     */
    @ApiOperation("楼栋实验室统计")
    @GetMapping("/{ids}/SubTotal/")
    public ResultData<List<TotalByID>> queryBuildingSubTotal(@PathVariable Long... ids) {

        List<TotalByID> list = subjectManagerService.queryBuildingSubTotal(ids);
        return ResultData.success(list);
    }

    /**
     * 查询实验室控制数据列表- 仅负责人权限（小程序使用）
     *
     * @return
     */
    @ApiOperation("查询实验室控制数据列表- 仅负责人权限（小程序使用）")
    @GetMapping("/my/list")
    public ResultData<List<LabSubjectControllerVO>> queryMyAadminSubCListVO() {
//        startPage();
        List<LabSubjectControllerVO> list = subjectManagerService.queryMyAadminSubCListVO();
        return ResultData.success(list);
    }


    /**
     * 控制设备开关
     *
     * @return
     */
    @ApiOperation("控制设备开关")
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_SUBCONTROL + PerFun.SET)
    @PostMapping("/control/{id}/{command}")
    public ResultData controlSwitch(@PathVariable("id") @ApiParam("设备ID") Long id ,@PathVariable("command") Symbol.command command) {

        Boolean control = subjectManagerService.control(id, command);
        return ResultData.result(control,()->"电源控制失败！");
    }


    /**
     * 智能报警设备开关
     *
     * @return
     */
    @ApiOperation("智能报警控制设备开关")
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_SUBCONTROL + PerFun.SET)
    @PostMapping("/alarmControl/{id}/{command}")
    public ResultData alarmControl(@PathVariable("id") @ApiParam("设备ID") Long id ,@PathVariable("command") Symbol.command command) {
        Boolean control = subjectManagerService.alarmControl(id, command);
        return ResultData.result(control,()->"电源控制失败！");
    }

    @PostMapping("/controlByInside")
    public ResultData controlByInside(@RequestParam("id") @ApiParam("设备ID") Long id ,@RequestParam("type") String type) {
        Symbol.command command = Symbol.command.open;
        if(Symbol.command.close.getType().equals(type)){
            command = Symbol.command.close;
        }

        Boolean control = subjectManagerService.control(id, command);
        return ResultData.result(control,()->"电源控制失败！");
    }


    @PostMapping("/control/{id}")
    public ResultData test(@PathVariable("id") @ApiParam("设备ID") Long id) {

        subjectManagerService.test(id);
        return ResultData.result(true,()->"电源控制失败！");
    }


    /**
     * 发送语音-向对应实验室发送
     *
     * @return
     */
    @ApiOperation("发送语音-向对应实验室发送")
    @PostMapping("/voice/{id}")
    public ResultData controlSwitch(@PathVariable("id") @ApiParam("实验室ID") Long id,@RequestParam("type") Integer type,@RequestParam("txt") String txt ) {
        subMessageSendManager.sendOnepcSubNews(id,type,txt);

        return ResultData.success();
    }

    /**
     * 发送语音-向对应实验室发送
     *
     * @return
     */
    @ApiOperation("心跳接收")
    @PutMapping("/{num}/heartbeat")
    public ResultData heartbeat(@PathVariable("num") @ApiParam("设备编码") String num) {
//        Boolean aBoolean = redisService.redisTemplate.opsForValue().setIfAbsent(CacheConstants.HEARTBEAT+num, true , 60L, TimeUnit.SECONDS);
//        if(aBoolean==true)
//        {
//            EquipmentStatus equipmentStatus = new EquipmentStatus();
//            equipmentStatus.setNum(num);
//            equipmentStatus.setHardwareOperate(HardwareOperate.ONLINE);
//            OnecStatusEvent onecStatusEvent = new OnecStatusEvent(equipmentStatus);
//            SpringUtils.getApplicationContext().publishEvent(onecStatusEvent);
//        }
        if(!redisService.hasKey(CacheConstants.HEARTBEAT+num)){
            redisService.setCacheObject(CacheConstants.HEARTBEAT+num, true , 60L, TimeUnit.SECONDS);
            EquipmentStatus equipmentStatus = new EquipmentStatus();
            equipmentStatus.setNum(num);
            equipmentStatus.setHardwareOperate(HardwareOperate.ONLINE);
            OnecStatusEvent onecStatusEvent = new OnecStatusEvent(equipmentStatus);
            SpringUtils.getApplicationContext().publishEvent(onecStatusEvent);
        }else{
            redisService.setCacheObject(CacheConstants.HEARTBEAT+num, true , 60L, TimeUnit.SECONDS);
        }
        return ResultData.success();
    }

    /**
     * 查询实验室正常打卡人数
     * @return
     */
    @ApiOperation("查询实验室正常打卡人数")
    @GetMapping("/records/{suId}/count")
    public ResultData queryRecordsSubs( @PathVariable Long suId)
    {
        int i = labSubjectAccessRecordMapper.selectAccessRecordCountBySubId(suId);
        return ResultData.success(i);
    }


//
//    /**
//     * 正在发生的预案数据： 当前用户数权限和业务权限内的
//     * @return
//     */
//    @ApiOperation("正在发生的预案数据： 当前用户数权限和业务权限内的")
//    @GetMapping("/warning/{count}")
//    public ResultData queryWarningSubs(@ApiParam("最大请求数量（-1代表无限制）") @PathVariable Long count)
//    {
//        SubQueryConfig subQueryConfig = new SubQueryConfig();
//        subQueryConfig.setDangerLevel(true);
//        subQueryConfig.setAddr(true);
//        subQueryConfig.setConversionDictSubName(true);
////        subQueryConfig.setBaseInfo(false);
//        subQueryConfig.setSensorFunction(true);
//        subQueryConfig.setInitSensorFunctionValue(true);
//        subQueryConfig.setInitWarnSensorFunction(true);
//        subQueryConfig.setHardware(true);
//        subQueryConfig.setBaseInfo(false);
//        subQueryConfig.setSafeInfo(true);
//        return ResultData.success(subQueryManager.querySubs(subQueryConfig,10l));
//    }

//    /**
//     * 历史预案数据:当前用户数权限和业务权限内的
//     * @return
//     */
//    @ApiOperation("历史预案数据：当前用户数权限和业务权限内的")
//    @GetMapping("/warned/{day}")
//    public ResultData queryWarnedSubs(@ApiParam("前几day的数据（-1代表无限制）") @PathVariable Long count)
//    {
//
//        return null;
//    }

//    /**
//     * 控制设备
//     *
//     * @return
//     */
//    @ApiOperation("控制设备")
//    @PostMapping("/control")
//    public ResultData control(@RequestBody Control control) {
//
//        //
//        //
//        //
//
//        return null;
//    }

}
