package com.ruoyi.web.controller.api;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.config.JiPushService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.ApiResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.mall.domain.*;
import com.ruoyi.mall.service.*;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ApiDeviceController
 * @Description 基站设备相关接口
 * @Author LCL
 * @Date 2024/03/11
 * @Version 1.0
 **/

@RestController
@RequestMapping("/api/device")
@ResponseBody
public class ApiDeviceController {

    @Resource
    private IMallBaseStationService mallBaseStationService;
    @Resource
    private IMallDeviceService mallDeviceService;
    @Resource
    private IMallCompanyUserService mallCompanyUserService;
    @Resource
    private IMallWarnOperateLogService mallWarnOperateLogService;
    @Resource
    private IMallCameraVideoService mallCameraVideoService;


    /**
     * 获取基站设备列表
     *
     * @param pageNum  页码
     * @param pageSize 每页数据量
     * @param params   userId 用户ID
     *                 searchValue 搜索内容
     * @return pageInfo
     */
    @GetMapping("/getBaseStationList")
    public AjaxResult getBaseStationList(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                         @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                                         @RequestParam Map<String, Object> params) {
        if (!params.containsKey("userId") || StringUtils.isBlank(params.get("userId").toString())) {
            return AjaxResult.error("缺少userId");
        }

        try {
            PageHelper.startPage(pageNum, pageSize);
            List<Map<String, Object>> mapList = mallBaseStationService.selectAppMallBaseStationList(params);
            PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(mapList);
            return AjaxResult.success().put("data", pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取基站设备列表异常");
        }
    }

    /**
     * 获取基站设备详情
     *
     * @param params userId 用户ID
     *               baseStationId 基站ID
     * @return map
     */
    @GetMapping("/getBaseStationInfo")
    public AjaxResult getBaseStationInfo(@RequestParam Map<String, Object> params) {
        if (!params.containsKey("userId") || StringUtils.isBlank(params.get("userId").toString())) {
            return AjaxResult.error("缺少userId");
        }
        if (!params.containsKey("baseStationId") || StringUtils.isBlank(params.get("baseStationId").toString())) {
            return AjaxResult.error("缺少baseStationId");
        }

        try {
            HashMap<String, Object> map = new HashMap<>();
            // 基站
            Map<String, Object> baseStationMap = mallBaseStationService.selectAppMallBaseStation(params);
            map.put("baseStation", baseStationMap);

            Map<String, Object> param = new HashMap<>();
            param.put("baseStationId", Long.parseLong(params.get("baseStationId").toString()));

            // 报警主机
            param.put("deviceType", '1');
            List<Map<String, Object>> alarmHostList = mallDeviceService.selectAppMallDeviceList(param);
            map.put("alarmHost", alarmHostList);

            // 摄像头
            param.put("deviceType", '2');
            List<Map<String, Object>> cameraList = mallDeviceService.selectAppMallDeviceList(param);
            map.put("camera", cameraList);

            // 弹箱
            param.put("deviceType", '3');
            List<Map<String, Object>> cartridgeBoxList = mallDeviceService.selectAppMallDeviceList(param);
            map.put("cartridgeBox", cartridgeBoxList);

            // 语音喇叭
            param.put("deviceType", '4');
            List<Map<String, Object>> voiceSpeakerList = mallDeviceService.selectAppMallDeviceList(param);
            map.put("voiceSpeaker", voiceSpeakerList);

            // 语音喇叭和弹箱放在一起
            List<Map<String, Object>> listMaps = new ArrayList<Map<String, Object>>();
            listMaps.addAll(voiceSpeakerList);
            listMaps.addAll(cartridgeBoxList);
            map.put("hornAndBox", listMaps);

            // 电源
            param.put("deviceType", '5');
            List<Map<String, Object>> powerSupplyList = mallDeviceService.selectAppMallDeviceList(param);
            map.put("powerSupply", powerSupplyList);
            return AjaxResult.success().put("data", map);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取基站设备详情异常");
        }
    }

    /**
     * 操作设备
     *
     * @param params userId 用户ID
     *               baseStationId 基站ID
     *               deviceId 设备ID
     *               deviceDefence 设备布防：0-布防，1-撤防
     *               deviceOpen 设备开关：0-开启，1-关闭
     *               boxVoice 弹箱语音提示：0-不提示，1-提示
     *               boxTrigger 弹箱触发：1-触发
     * @return success
     */
    @RepeatSubmit
    @PostMapping("/operateDevice")
    @Log(title = "操作设备", businessType = BusinessType.UPDATE)
    public AjaxResult operateDevice(@RequestBody Map<String, Object> params) {
        if (!params.containsKey("userId") || StringUtils.isBlank(params.get("userId").toString())) {
            return AjaxResult.error("缺少userId");
        }
        if (!params.containsKey("baseStationId") || StringUtils.isBlank(params.get("baseStationId").toString())) {
            return AjaxResult.error("缺少baseStationId");
        }
        if (!params.containsKey("deviceId") || StringUtils.isBlank(params.get("deviceId").toString())) {
            return AjaxResult.error("缺少deviceId");
        }

        try {
            Long userId = MapUtils.getLong(params, "userId");
            Long baseStationId = MapUtils.getLong(params, "baseStationId");
            Long deviceId = MapUtils.getLong(params, "deviceId");

            // 判断公司基站管理员状态
            mallCompanyUserService.determineCompanyUser(userId);

            // 基站信息
            MallBaseStation mallBaseStation = mallBaseStationService.selectMallBaseStationByBaseStationId(baseStationId);
            if (ObjectUtils.isNotEmpty(mallBaseStation)) {
                if (!mallBaseStation.getUserId().equals(userId)) {
                    return AjaxResult.error("基站未绑定此账号");
                }
            } else {
                return AjaxResult.error("基站不存在");
            }
            // 设备信息
            MallDevice mallDevice = mallDeviceService.selectMallDeviceByDeviceId(deviceId);
            if (ObjectUtils.isNotEmpty(mallDevice)) {
                if (!baseStationId.equals(mallDevice.getBaseStationId())) {
                    return AjaxResult.error("设备未绑定此基站");
                }
            } else {
                return AjaxResult.error("设备不存在");
            }


            MallDevice mallDeviceInsert = new MallDevice();
            MallWarnOperateLog mallWarnOperateLog = new MallWarnOperateLog();

            mallDeviceInsert.setDeviceId(deviceId);

            int status = 0;
            switch (mallDevice.getDeviceType()) {
                case "1":
                    if (params.containsKey("deviceDefence") && StringUtils.isNotBlank(params.get("deviceDefence").toString())) {
                        String deviceDefence = MapUtils.getString(params, "deviceDefence");

                        // 报警主机 0-布防，1-撤防
                        mallDeviceInsert.setDeviceDefence(deviceDefence);

                        if ("0".equals(deviceDefence)) {
                            mallWarnOperateLog.setWarnOperateLogName("布防");
                        } else {
                            mallWarnOperateLog.setWarnOperateLogName("撤防");
                        }
                        status = 1;
                    }

                    break;
                case "3":
                    if (params.containsKey("deviceOpen") && StringUtils.isNotBlank(params.get("deviceOpen").toString())) {
                        String deviceOpen = MapUtils.getString(params, "deviceOpen");

                        // 弹箱 0-开启，1-关闭
                        mallDeviceInsert.setDeviceOpen(deviceOpen);

                        if ("0".equals(deviceOpen)) {
                            mallWarnOperateLog.setWarnOperateLogName("开启弹箱");
                        } else {
                            mallWarnOperateLog.setWarnOperateLogName("关闭弹箱");
                        }
                        status = 1;
                    }

                    if (params.containsKey("boxVoice") && StringUtils.isNotBlank(params.get("boxVoice").toString())) {
                        String boxVoice = MapUtils.getString(params, "boxVoice");

                        // 弹箱 语音提示：0-不提示，1-提示
                        mallDeviceInsert.setBoxVoice(boxVoice);

                        if ("0".equals(boxVoice)) {
                            mallWarnOperateLog.setWarnOperateLogName("关闭弹箱语音提示");
                        } else {
                            mallWarnOperateLog.setWarnOperateLogName("开启弹箱语音提示");
                        }
                        status = 1;
                    }

                    if (params.containsKey("boxTrigger") && StringUtils.isNotBlank(params.get("boxTrigger").toString())) {
                        String boxTrigger = MapUtils.getString(params, "boxTrigger");

                        // 弹箱 弹箱触发：1-触发
                        mallDeviceInsert.setBoxTrigger(boxTrigger);

                        if ("1".equals(boxTrigger)) {
                            mallDeviceInsert.setBoxUse("1");
                            mallWarnOperateLog.setWarnOperateLogName("触发弹箱");
                        }
                        status = 1;
                    }

                    break;
                case "4":
                    if (params.containsKey("deviceOpen") && StringUtils.isNotBlank(params.get("deviceOpen").toString())) {
                        String deviceOpen = MapUtils.getString(params, "deviceOpen");

                        // 语音喇叭 0-开启，1-关闭
                        mallDeviceInsert.setDeviceOpen(deviceOpen);

                        if ("0".equals(deviceOpen)) {
                            mallWarnOperateLog.setWarnOperateLogName("开启语音喇叭");
                        } else {
                            mallWarnOperateLog.setWarnOperateLogName("关闭语音喇叭");
                        }
                        status = 1;
                    }

                    break;
                default:
                    break;
            }

            if (status == 1) {
                // 修改设备
                mallDeviceService.updateMallDevice(mallDeviceInsert);

                mallWarnOperateLog.setUserId(userId);
                mallWarnOperateLog.setBaseStationId(baseStationId);
                mallWarnOperateLog.setDeviceId(deviceId);
                mallWarnOperateLog.setWarnOperateLogType("1");
                mallWarnOperateLog.setDeviceName(mallDeviceService.selectMallDeviceNameByDeviceType(mallDevice.getDeviceType()));
                // 添加操作记录
                mallWarnOperateLogService.insertMallWarnOperateLog(mallWarnOperateLog);
            }

            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("操作设备异常");
        }
    }

    /**
     * 获取告警系统日志记录列表
     *
     * @param pageNum  页码
     * @param pageSize 每页数据量
     * @param params   userId 用户ID
     *                 warnOperateLogType 记录类型：0-告警，1-系统（操作）
     *                 searchValue 搜索内容
     *                 provinceId 省ID
     *                 cityId 市ID
     *                 areaId 区县ID
     *                 beginTime 开始时间
     *                 endTime 结束时间
     * @return pageInfo
     */
    @GetMapping("/getWarnOperateLogList")
    public AjaxResult getWarnOperateLogList(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                            @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                                            @RequestParam Map<String, Object> params) {
        if (!params.containsKey("userId") || StringUtils.isBlank(params.get("userId").toString())) {
            return AjaxResult.error("缺少userId");
        }
        if (!params.containsKey("warnOperateLogType") || StringUtils.isBlank(params.get("warnOperateLogType").toString())) {
            return AjaxResult.error("缺少warnOperateLogType");
        }

        try {
            PageHelper.startPage(pageNum, pageSize);
            List<Map<String, Object>> mapList = mallWarnOperateLogService.selectAppMallWarnOperateLogList(params);
            PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(mapList);
            return AjaxResult.success().put("data", pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取告警系统日志记录列表异常");
        }

    }

    /**
     * 获取弹箱统计列表
     *
     * @param pageNum  页码
     * @param pageSize 每页数据量
     * @param params   userId 用户ID
     *                 searchValue 搜索内容
     *                 provinceId 省ID
     *                 cityId 市ID
     *                 areaId 区县ID
     *                 boxUse 弹箱使用：0-未使用，1-已使用（待补充）
     * @return pageInfo
     */
    @GetMapping("/getBoxStatisticsList")
    public AjaxResult getBoxStatisticsList(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                           @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                                           @RequestParam Map<String, Object> params) {
        if (!params.containsKey("userId") || StringUtils.isBlank(params.get("userId").toString())) {
            return AjaxResult.error("缺少userId");
        }

        try {
            PageHelper.startPage(pageNum, pageSize);
            List<Map<String, Object>> mapList = mallDeviceService.selectAppMallDeviceBoxList(params);
            PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(mapList);
            return AjaxResult.success().put("data", pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取弹箱统计列表异常");
        }
    }

    /**
     * 弹箱统计-已补充
     *
     * @param params userId 用户ID
     *               baseStationId 基站ID
     *               deviceId 设备ID
     * @return success
     */
    @RepeatSubmit(interval = 3000)
    @PostMapping("/operateDeviceSupplementBox")
    @Log(title = "弹箱统计", businessType = BusinessType.UPDATE)
    public AjaxResult operateDeviceSupplementBox(@RequestBody Map<String, Object> params) {
        if (!params.containsKey("userId") || StringUtils.isBlank(params.get("userId").toString())) {
            return AjaxResult.error("缺少userId");
        }
        if (!params.containsKey("baseStationId") || StringUtils.isBlank(params.get("baseStationId").toString())) {
            return AjaxResult.error("缺少baseStationId");
        }
        if (!params.containsKey("deviceId") || StringUtils.isBlank(params.get("deviceId").toString())) {
            return AjaxResult.error("缺少deviceId");
        }
        try {
            Long userId = MapUtils.getLong(params, "userId");
            Long deviceId = MapUtils.getLong(params, "deviceId");
            Long baseStationId = MapUtils.getLong(params, "baseStationId");

            MallDevice device = mallDeviceService.selectMallDeviceByDeviceId(deviceId);
            if (device == null || !"3".equals(device.getDeviceType())) {
                return AjaxResult.error("该设备不属于弹箱");
            }

            MallDevice mallDevice = new MallDevice();
            mallDevice.setDeviceId(deviceId);
            mallDevice.setBoxUse("0");
            mallDeviceService.updateMallDevice(mallDevice);

            MallWarnOperateLog mallWarnOperateLog = new MallWarnOperateLog();
            mallWarnOperateLog.setUserId(userId);
            mallWarnOperateLog.setBaseStationId(baseStationId);
            mallWarnOperateLog.setDeviceId(deviceId);
            mallWarnOperateLog.setWarnOperateLogName("补充弹箱");
            mallWarnOperateLog.setWarnOperateLogType("1");
            mallWarnOperateLog.setDeviceName(mallDeviceService.selectMallDeviceNameByDeviceType("3"));
            // 添加操作记录
            mallWarnOperateLogService.insertMallWarnOperateLog(mallWarnOperateLog);

            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("弹箱统计-已补充异常");
        }
    }

    /**
     * 接收硬件设备发来的数据
     *
     * @param params message 数据
     * @return mallCompanyUser
     */
    @GetMapping("/receivingDeviceData")
    @Log(title = "接收硬件设备发来的数据", businessType = BusinessType.UPDATE)
    public AjaxResult receivingDeviceData(@RequestParam Map<String, Object> params) {
        if (!params.containsKey("message")) {
            return AjaxResult.error("缺少message");
        }

        try {
            String message = MapUtils.getString(params, "message");

            Map<String, Object> map = mallDeviceService.processingReceivedData(message);

            return AjaxResult.success().put("data", map);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("接收数据异常");
        }
    }

    /**
     * 获取远程回放视频列表
     *
     * @param pageNum  页码
     * @param pageSize 每页数据量
     * @param params   userId 用户ID
     *                 provinceId 省ID
     *                 cityId 市ID
     *                 areaId 区县ID
     *                 beginTime 开始时间
     *                 endTime 结束时间
     *                 searchValue 搜索内容
     * @return pageInfo
     */
    @GetMapping("/getRemotePlayBackVideoList")
    public AjaxResult getRemotePlayBackVideoList(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                                 @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                                                 @RequestParam Map<String, Object> params) {
        if (!params.containsKey("userId") || StringUtils.isBlank(params.get("userId").toString())) {
            return AjaxResult.error("缺少userId");
        }

        try {
            PageHelper.startPage(pageNum, pageSize);
            List<Map<String, Object>> mapList = mallCameraVideoService.selectAppRemotePlayBackVideoListList(params);
            PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(mapList);
            return AjaxResult.success().put("data", pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取远程回放视频列表异常");
        }
    }

    /**
     * 获取远程回放视频详情
     *
     * @param pageNum  页码
     * @param pageSize 每页数据量
     * @param params userId 用户ID
     *               cameraVideoId 摄像头视频ID
     *               beginTime 开始时间
     *               endTime 结束时间
     * @return map
     */
    @GetMapping("/getRemotePlayBackVideoInfo")
    public AjaxResult getRemotePlayBackVideoInfo(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                                 @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                                                 @RequestParam Map<String, Object> params) {
        if (!params.containsKey("userId") || StringUtils.isBlank(params.get("userId").toString())) {
            return AjaxResult.error("缺少userId");
        }
        if (!params.containsKey("cameraVideoId") || StringUtils.isBlank(params.get("cameraVideoId").toString())) {
            return AjaxResult.error("缺少cameraVideoId");
        }

        try {
            Long cameraVideoId = MapUtils.getLong(params, "cameraVideoId");
            HashMap<String, Object> map = new HashMap<>();
            // 远程回放视频
            MallCameraVideo mallCameraVideo = mallCameraVideoService.selectMallCameraVideoByCameraVideoId(cameraVideoId);
            params.put("cameraId", mallCameraVideo.getCameraId());

            // 此摄像头远程回放视频列表
            PageHelper.startPage(pageNum, pageSize);
            List<Map<String, Object>> mapList = mallCameraVideoService.selectAppRemotePlayBackVideoListList(params);
            PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(mapList);
            map.put("videoUrl", mallCameraVideo.getVideoUrl());
            map.put("videoList", pageInfo);
            return AjaxResult.success().put("data", map);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取基站设备详情异常");
        }
    }

}
