package com.ozs.web.controller.accountmanagment;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ozs.common.annotation.Log;
import com.ozs.common.core.controller.BaseController;
import com.ozs.common.core.domain.AjaxResult;
import com.ozs.common.core.domain.entity.SysDictData;
import com.ozs.common.enums.BusinessType;
import com.ozs.common.utils.AppendUtils;
import com.ozs.common.utils.IdempotenceUtils;
import com.ozs.common.utils.StringUtils;
import com.ozs.common.utils.http.HttpUtils;
import com.ozs.common.utils.stateSecrets.SM4Utils;
import com.ozs.entity.BaseCameraManagement;
import com.ozs.entity.BaseRailwayManagement;
import com.ozs.entity.BaseUser;
import com.ozs.entity.MsgAlarm;
import com.ozs.entity.MsgAlarmExt;
import com.ozs.entity.MsgAlarmFrequency;
import com.ozs.entity.vo.Files;
import com.ozs.entity.vo.MsgAlarmTemporary;
import com.ozs.entity.vo.MsgAlarmVo;
import com.ozs.entity.vo.ParameterVo;
import com.ozs.entity.vo.ReleaseAlarmVo;
import com.ozs.entity.vo.ReqMsgAlarmVo;
import com.ozs.service.BaseCameraManagementService;
import com.ozs.service.BaseRailwayManagementService;
import com.ozs.service.BaseUserService;
import com.ozs.service.MsgAlarmExtService;
import com.ozs.service.MsgAlarmFrequencyService;
import com.ozs.service.MsgAlarmService;
import com.ozs.service.MsgAlarmTemporaryService;
import com.ozs.service.SvcAddressService;
import com.ozs.system.service.ISysDictTypeService;
import com.ozs.web.controller.monitor.SysUserOnlineController;
import com.ozs.web.controller.websocket.WebSocketCommon;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author Administrator
 */
@RestController
@RequestMapping("/service/msgAlarmTemporary")
public class MsgAlarmTemporaryController extends BaseController {

    public static final String PATTERN = "^([0-9]+),([0-9]+),([0-9]+),([0-9]+),([0-9]+),([0-9]+)$";
    public static final String PATTERNS = "^[0-9]*$";

    @Autowired
    private IdempotenceUtils idempotenceUtils;

    @Autowired
    private MsgAlarmTemporaryService msgAlarmTemporaryService;

    @Autowired
    private BaseRailwayManagementService baseRailwayManagementService;

    @Autowired
    SvcAddressService svcAddressService;
    @Autowired
    BaseCameraManagementService baseCameraManagementService;
    @Autowired
    SysUserOnlineController sysUserOnlineController;
    @Autowired
    private BaseUserService baseUserService;
    @Autowired
    private MsgAlarmExtService msgAlarmExtService;
    @Autowired
    WebSocketCommon webSocketCommon;
    @Autowired
    private MsgAlarmService msgAlarmService;
    @Autowired
    private MsgAlarmFrequencyService msgAlarmFrequencyService;
    @Autowired
    private ISysDictTypeService dictTypeService;


    /**
     * 报警信息临时表分页
     *
     * @param msgAlarmVo
     * @return
     */
    @PostMapping("/list")
    @Log(title = "报警信息管理", businessType = BusinessType.SELECT)
    public AjaxResult selectMsgAlarm(@RequestBody MsgAlarmVo msgAlarmVo) {
        IPage<MsgAlarmTemporary> page = msgAlarmTemporaryService.page(new Page<>(msgAlarmVo.getPageNum(), msgAlarmVo.getPageSize()), null);
        if (!ObjectUtils.isEmpty(page) && page.getRecords().size() > 0) {
            List<MsgAlarmTemporary> dto1 = page.getRecords().stream().map(o -> {
                LambdaQueryWrapper<BaseRailwayManagement> queryWrapper = new LambdaQueryWrapper<BaseRailwayManagement>();
                if (!ObjectUtils.isEmpty(o.getAlarmRailway())) {
                    queryWrapper.eq(BaseRailwayManagement::getRailwayCode, o.getAlarmRailway());
                }
                BaseRailwayManagement baseRailwayManagement = baseRailwayManagementService.getOne(queryWrapper);
                if (!StringUtils.isEmptySunhh(baseRailwayManagement) && !StringUtils.isEmptySunhh(baseRailwayManagement.getRailwayName())) {
                    o.setRailwayName(baseRailwayManagement.getRailwayName());
                }
                String mils = AppendUtils.stringAppend(o.getAlarmMile());
                o.setAlarmMiles(mils);
                o.setLineDirName(o.getLineDir() == 1 ? "上行" : "下行");
                o.setStareName(o.getStare() == 1 ? "未生效" : "已生效");
                o.setAlarmTypeStr(o.getAlarmType() == 1 ? "泥石流" : (o.getAlarmType() == 2 ? "异物侵限" : (o.getAlarmType() == 3 ? "断轨监测" : "未知")));
                List<SysDictData> data = dictTypeService.selectDictDataByType("sys_alarm_type");
                data.stream().forEach(sysDictData -> {
                    if (sysDictData.getDictValue().equals(o.getAlarmType().toString())) {
                        o.setAlarmTypeName(sysDictData.getDictLabel());
                    }
                });
                return o;
            }).collect(Collectors.toList());
            page.setRecords(dto1);
        }
        return AjaxResult.success(page);
    }


    @PostMapping("/saveMsgAlarmTemporary")
    @Log(title = "报警信息临时表管理", businessType = BusinessType.INSERT)
    public AjaxResult saveMsgAlarmTemporary(@RequestBody MsgAlarmTemporary msgAlarmTemporary) {
        String idempotence = idempotenceUtils.getIdempotence(msgAlarmTemporary.getAlarmId());
        if (StringUtils.isNotEmpty(idempotence)) {
            return error("你的网络卡顿,请不要一直添加!!!");
        }
        idempotenceUtils.createIdempotence(msgAlarmTemporary.getAlarmId());
        if (!msgAlarmTemporary.getAlarmMile().toString().matches(PATTERNS)) {
            idempotenceUtils.deleteIdempotence(msgAlarmTemporary.getAlarmId());
            return error("里程位置填写格式不正确,请填写数字");
        }
        if (!msgAlarmTemporary.getAlarmConfidence().toString().matches(PATTERNS)) {
            idempotenceUtils.deleteIdempotence(msgAlarmTemporary.getAlarmId());
            return error("报警置信度格式不正确,请填写数字");
        }
        LambdaQueryWrapper<MsgAlarmTemporary> lw = new LambdaQueryWrapper<>();
        if (!ObjectUtils.isEmpty(msgAlarmTemporary.getAlarmId())) {
            lw.eq(MsgAlarmTemporary::getAlarmId, msgAlarmTemporary.getAlarmId());
            MsgAlarmTemporary msgAlarmTemporary1 = msgAlarmTemporaryService.getOne(lw);
            if (!ObjectUtils.isEmpty(msgAlarmTemporary1)) {
                idempotenceUtils.deleteIdempotence(msgAlarmTemporary.getAlarmId());
                return error("报警唯一标识已存在,不能重复添加");
            }
        }
        if (msgAlarmTemporaryService.save(msgAlarmTemporary)) {
            idempotenceUtils.deleteIdempotence(msgAlarmTemporary.getAlarmId());
            return AjaxResult.success();
        }
        idempotenceUtils.deleteIdempotence(msgAlarmTemporary.getAlarmId());
        return AjaxResult.error();
    }


    /**
     * 修改报警信息临时表信息
     *
     * @param msgAlarmTemporary
     * @return
     */
    @RequestMapping("/editMsgAlarmTemporary")
    @Log(title = "报警信息临时表管理", businessType = BusinessType.UPDATE)
    public AjaxResult editMsgAlarmTemporary(@RequestBody MsgAlarmTemporary msgAlarmTemporary) {
        MsgAlarmTemporary msgAlarmTemporary1 = msgAlarmTemporaryService.getById(msgAlarmTemporary.getId());
        if (ObjectUtils.isEmpty(msgAlarmTemporary1)) {
            return error("主键不存在");
        }
        if (!msgAlarmTemporary.getAlarmMile().toString().matches(PATTERNS)) {
            return error("里程位置填写格式不正确,请填写数字");
        }
        if (!msgAlarmTemporary.getAlarmConfidence().toString().matches(PATTERNS)) {
            idempotenceUtils.deleteIdempotence(msgAlarmTemporary.getAlarmId());
            return error("报警置信度格式不正确,请填写数字");
        }
        QueryWrapper<MsgAlarmTemporary> wrapper = new QueryWrapper<>();
        wrapper.eq("alarm_id", msgAlarmTemporary.getAlarmId());
        MsgAlarmTemporary one = msgAlarmTemporaryService.getOne(wrapper);
        if (!ObjectUtils.isEmpty(one) && !one.getId().equals(msgAlarmTemporary.getId())) {
            return error("报警唯一标识已存在,不能进行修改操作");
        }
        if (msgAlarmTemporaryService.updateById(msgAlarmTemporary)) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }


    @GetMapping("/alarm/{id}")
    public AjaxResult alarm(@PathVariable Long id) {
        MsgAlarmTemporary msgAlarmTemporary = msgAlarmTemporaryService.getById(id);
        if (msgAlarmTemporary.getStare() == 2) {
            return AjaxResult.error("数据已模拟,不能再次使用");
        }
        ReqMsgAlarmVo reqMsgAlarmVo = new ReqMsgAlarmVo();
        com.ozs.common.utils.bean.BeanUtils.copyProperties(msgAlarmTemporary, reqMsgAlarmVo);
        reqMsgAlarmVo.setAlarmTime(msgAlarmTemporary.getAlarmTime().getTime());
        Files files = new Files();
        files.setFileType(1);
        files.setFileUrl(msgAlarmTemporary.getFileUrl());
        Files[] files2 = new Files[1];
        files2[0] = files;
        reqMsgAlarmVo.setFiles(files2);
        if (ObjectUtils.isEmpty(reqMsgAlarmVo.getAlarmAttr())) {
                return AjaxResult.error("你填写的报警属性不能为空!!!");
        }
        if (!reqMsgAlarmVo.getAlarmMile().toString().matches(PATTERNS)) {
            return AjaxResult.error("报警里程位置填写错误");
        }
        if (reqMsgAlarmVo.getLineDir() != 1 && reqMsgAlarmVo.getLineDir() != 2) {
            return AjaxResult.error("行别填写错误");
        }
        LambdaQueryWrapper<BaseRailwayManagement> queryWrapper = new LambdaQueryWrapper<BaseRailwayManagement>();
        if (!ObjectUtils.isEmpty(reqMsgAlarmVo.getAlarmRailway())) {
            queryWrapper.eq(BaseRailwayManagement::getRailwayCode, reqMsgAlarmVo.getAlarmRailway());
        }
        BaseRailwayManagement baseRailwayManagement = baseRailwayManagementService.getOne(queryWrapper);
        if (ObjectUtils.isEmpty(baseRailwayManagement)) {
            return AjaxResult.error("填写的报警线路编码不存在");
        }
        if (ObjectUtils.isEmpty(reqMsgAlarmVo.getAlarmId())) {
            return AjaxResult.error("报警的唯一标识不能为空");
        }
        if (ObjectUtils.isEmpty(reqMsgAlarmVo.getAlarmTime())) {
            return AjaxResult.error("报警时间不能为空");
        }
        if (reqMsgAlarmVo.getAlarmType() < 1 || reqMsgAlarmVo.getAlarmType() > 3) {
            return AjaxResult.error("报警病害类型填写错误");
        }
        if (!reqMsgAlarmVo.getAlarmLevel().toString().matches(PATTERNS)) {
            return AjaxResult.error("报警级别填写错误");
        }
        if (reqMsgAlarmVo.getAlarmTime().toString().length() == 10) {
            reqMsgAlarmVo.setAlarmTime(reqMsgAlarmVo.getAlarmTime() * 1000);
        }

        LambdaQueryWrapper<BaseCameraManagement> wrapper = new LambdaQueryWrapper<BaseCameraManagement>();
        if (!ObjectUtils.isEmpty(reqMsgAlarmVo.getAlarmMile())) {
            wrapper.le(BaseCameraManagement::getBeginMile, reqMsgAlarmVo.getAlarmMile());
            wrapper.ge(BaseCameraManagement::getEndMile, reqMsgAlarmVo.getAlarmMile());
            wrapper.eq(BaseCameraManagement::getRailwayCode, reqMsgAlarmVo.getAlarmRailway());
            wrapper.eq(BaseCameraManagement::getLineDir, reqMsgAlarmVo.getLineDir());
        }
        List<BaseCameraManagement> baseCameraManagementList = baseCameraManagementService.list(wrapper);
        if (baseCameraManagementList.size() <= 0) {
            return AjaxResult.error("报警里程位置没有可用的相机!!!");
        }
        LambdaQueryWrapper<MsgAlarm> lw = new LambdaQueryWrapper<MsgAlarm>();
        if (!ObjectUtils.isEmpty(reqMsgAlarmVo.getAlarmId())) {
            lw.eq(MsgAlarm::getAlarmId, reqMsgAlarmVo.getAlarmId());
        }
        MsgAlarm alarm = msgAlarmService.getOne(lw);
        BaseUser admin = baseUserService.getUserName("admin");
        MsgAlarmFrequency msgAlarmVice = new MsgAlarmFrequency();
        if (ObjectUtils.isEmpty(alarm)) {
            MsgAlarm msgAlarm = new MsgAlarm();
            BeanUtils.copyProperties(reqMsgAlarmVo, msgAlarm);
            BeanUtils.copyProperties(reqMsgAlarmVo, msgAlarmVice);
            msgAlarm.setCreateBy(admin.getUserId());
            msgAlarm.setUpdateBy(admin.getUserId());
            msgAlarm.setAlarmTime(new Date(reqMsgAlarmVo.getAlarmTime()));
            msgAlarm.setRailwayCode(reqMsgAlarmVo.getAlarmRailway());
            msgAlarm.setSource(msgAlarmTemporary.getSource());
            msgAlarmService.save(msgAlarm);
            Files[] files1 = reqMsgAlarmVo.getFiles();
            if (files1.length > 0) {
                for (int i = 0; i < files1.length; i++) {
                    if (ObjectUtils.isEmpty(files1[i].fileUrl)) {
                        return AjaxResult.error("上传文件地址不能为空");
                    }
                    if (files1[i].fileType < 1 || files1[i].fileType > 3) {
                        return AjaxResult.error("文件类型填写错误");
                    }
                    MsgAlarmExt msgAlarmExt = new MsgAlarmExt();
                    msgAlarmExt.setAlarmId(msgAlarm.getAlarmId());
                    msgAlarmExt.setAlarmAttPath(files1[i].fileUrl);
                    msgAlarmExt.setAlarmAttType(files1[i].fileType);
                    msgAlarmExtService.save(msgAlarmExt);
                }
            }
            msgAlarmVice.setCreateBy(admin.getUserId());
            msgAlarmVice.setUpdateBy(admin.getUserId());
            msgAlarmVice.setRailwayCode(reqMsgAlarmVo.getAlarmRailway());
            msgAlarmVice.setAlarmTime(new Date(reqMsgAlarmVo.getAlarmTime()));
            msgAlarmFrequencyService.save(msgAlarmVice);
            webSocketCommon.publish(msgAlarm);
//            for (BaseCameraManagement baseCameraManagement : baseCameraManagementList) {
//                String invite = CameraUtil.invite(baseCameraManagement.getCameraCode(), baseCameraManagement.getChannel());
//                if ("304".equals(invite) || "200".equals(invite)) {
//                    String start = HttpUtils.sendGet(CameraUtil.startRecording(baseCameraManagement.getCameraCode(), baseCameraManagement.getChannel()));
//                    if (start.startsWith(baseCameraManagement.getCameraCode() + "/" + baseCameraManagement.getChannel())) {
//                        baseCameraManagement.setTaskId(start);
//                        baseCameraManagement.setUpdateBy(admin.getUserId());
//                    } else {
//                        return AjaxResult.error("视频录制失败:请确认流是否存在!!!");
//                    }
//                    if (!baseCameraManagementService.updateById(baseCameraManagement)) {
//                        return AjaxResult.error("开启录制视频失败!!!");
//                    }
//                } else {
//                    return AjaxResult.error("视频邀约失败,视频中心没有该相机编码或通道编码的摄像头!!!");
//                }
//            }

        } else {
            BeanUtils.copyProperties(reqMsgAlarmVo, msgAlarmVice);
            msgAlarmVice.setCreateBy(admin.getUserId());
            msgAlarmVice.setUpdateBy(admin.getUserId());
            msgAlarmVice.setAlarmTime(new Date(reqMsgAlarmVo.getAlarmTime()));
            msgAlarmVice.setRailwayCode(reqMsgAlarmVo.getAlarmRailway());
            msgAlarmFrequencyService.save(msgAlarmVice);
        }
        msgAlarmTemporary.setStare(2);
        msgAlarmTemporaryService.updateById(msgAlarmTemporary);
        return AjaxResult.success();
    }


    @PostMapping("/releaseAlarm")
    public AjaxResult releaseAlarm(@RequestBody ReleaseAlarmVo releaseAlarmVo) {
        if (ObjectUtils.isEmpty(releaseAlarmVo.getAlarmId())) {
            return AjaxResult.error("报警的唯一标识不能为空");
        }
        if (ObjectUtils.isEmpty(releaseAlarmVo.getReleaseTime())) {
            return AjaxResult.error("解除报警时间不能为空");
        }
        if (ObjectUtils.isEmpty(releaseAlarmVo.getReleaseContent())) {
            return AjaxResult.error("解除原因不能为空");
        }
        if (ObjectUtils.isEmpty(releaseAlarmVo.getReleaseTime())) {
            return AjaxResult.error("解除人不能为空");
        }
        LambdaQueryWrapper<MsgAlarm> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MsgAlarm::getAlarmId, releaseAlarmVo.getAlarmId());
        MsgAlarm msgAlarm = msgAlarmService.getOne(wrapper);
        if (ObjectUtils.isEmpty(msgAlarm)) {
            return AjaxResult.error("不存在该报警的唯一标识的数据");
        }
        if (releaseAlarmVo.getReleaseTime().toString().length() == 10) {
            releaseAlarmVo.setReleaseTime(releaseAlarmVo.getReleaseTime() * 1000);
        }
        msgAlarm.setReleasedTime(new Date(releaseAlarmVo.getReleaseTime()));
        msgAlarm.setReleaseContent(releaseAlarmVo.getReleaseContent());
        msgAlarm.setReleasedBy(releaseAlarmVo.getOperator());
        msgAlarm.setUpdateBy(releaseAlarmVo.getOperator());
        msgAlarm.setIsRelease(1);
        boolean count = msgAlarmService.updateById(msgAlarm);
        Map<String, Object> map = new HashMap<>();
        map.put("alarmId", msgAlarm.getAlarmId());
        if (count) {
            return AjaxResult.success("已解除");
        } else {
            return AjaxResult.error("未解除");
        }
    }
}
