package com.xtd.project.hkmanager.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xtd.common.exception.CustomException;
import com.xtd.common.utils.DateUtils;
import com.xtd.common.utils.SecurityUtils;
import com.xtd.common.utils.StringUtils;
import com.xtd.framework.web.controller.BaseController;
import com.xtd.framework.web.domain.AjaxResult;
import com.xtd.framework.web.page.TableDataInfo;
import com.xtd.project.hkmanager.entity.Alarm;
import com.xtd.project.hkmanager.entity.AlarmForm;
import com.xtd.project.hkmanager.entity.SynLog;
import com.xtd.project.hkmanager.service.AlarmService;
import com.xtd.project.hkmanager.service.SynLogService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lym
 * @date 2020/4/2 17:38
 */
@RestController
@RequestMapping("/alarm")
@Api(description = "报警信息管理")
public class AlarmController extends BaseController {

    @Autowired
    AlarmService alarmService;
    @Autowired
    SynLogService synLogService;

    @ApiOperation(value = "同步报警信息",notes = "同步报警信息")
    @ApiResponse(code = 200,message = "操作成功")
    @GetMapping("/synAlarm")
    public AjaxResult synAlarm(Integer pageNo,Integer pageSize,Integer saveNum
            ,@RequestParam("startTime") String startTime,@RequestParam("endTime") String endTime){
        if (saveNum == null){
            saveNum = 0;
        }

        //路径
        String url = "/els/v1/events/search";
        Integer total = 0;

        //组装请求参数
        Map<String,Object> bodys = new HashMap<String, Object>();
        bodys.put("handleStatus","");
        bodys.put("startTime",startTime);
        bodys.put("endTime",endTime);

        setPage(bodys,pageNo,pageSize);
        String body = JSON.toJSON(bodys).toString();

        //调用接口
        Object object = postSelect(url,body,null,null,null);
        if (object != null){
            Map json = (Map) object;
            total = (Integer) json.get("total");
            Object listData = json.get("list");
            int i = batchSave(listData);
            //return AjaxResult.success(listData);
            saveNum += i;
            pageNo = Integer.parseInt(bodys.get("pageNo").toString());
            pageSize = Integer.parseInt(bodys.get("pageSize").toString());
            if (total > (pageNo * pageSize)){ //递归调用
                return synAlarm(pageNo + 1,pageSize,saveNum,startTime,endTime);
            }

            saveSynLog(bodys,saveNum);
            if (saveNum < 1){
                return AjaxResult.success("没有要同步的报警信息");
            }

            return AjaxResult.success("成功同步"+saveNum+"个报警信息");
        }
        return AjaxResult.error();
    }

    /**
     * 批量添加
     * @param data
     * @return
     */
    public int batchSave(Object data){
        List<JSONObject> list = (List<JSONObject>) data;
        Map<String, Alarm> map = new HashMap<>();
        Alarm alarm = null;
        Boolean isLogin = isLogin(); //是否登录
        for (JSONObject json:list){
            alarm = new Alarm();
            String guid = json.get("id").toString();
            alarm.setGuid(guid);
            //报警详情
            List<JSONObject> eventInfos = (List<JSONObject>) json.get("eventLogSrcList");
            JSONObject eventInfo = eventInfos.get(0);
            alarm.setFkRegionId(eventInfo.get("regionIndexCode") == null?null:eventInfo.get("regionIndexCode").toString());
            alarm.setRegionName(eventInfo.get("regionName") == null?null:eventInfo.get("regionName").toString());

            //报警设备信息
            String imageUrl = null,imageServerCode = null;
            if (eventInfo.containsKey("data") && eventInfo.get("data") != null){
                JSONObject eventDevice = JSONObject.parseObject(eventInfo.get("data").toString());
                String eventType = eventDevice.getString("eventType"); //事件类型
                //录像开始时间
                String recvTime = eventDevice.get("recvTime").toString().replace("T"," ");
                Date recvStartTime = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS,recvTime);
                alarm.setRecvStartTime(recvStartTime);
                //录像结束时间
                String endTime = json.get("endTime").toString().replace("T"," ");
                Date recvEndTime = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS,endTime);
                alarm.setRecvEndTime(recvEndTime);

                List<JSONObject> eventDataList = (List<JSONObject>) eventDevice.get(eventType); //事件类型报警详情
                JSONObject eventData = eventDataList.get(0);
                imageUrl = eventData.get("imageUrl") == null?null:eventData.get("imageUrl").toString();
                //编码设备
                if (eventData != null && eventData.containsKey("targetAttrs")){
                    JSONObject eventDeviceInfo = eventData.getJSONObject("targetAttrs");
                    alarm.setFkEncodeId(eventDeviceInfo.get("deviceIndexCode") == null?null:eventDeviceInfo.get("deviceIndexCode").toString());
                    imageServerCode = eventDeviceInfo.get("imageServerCode") == null?null:eventDeviceInfo.get("imageServerCode").toString();
                }
            }

            //报警图片路径
            if (imageUrl != null && imageUrl.contains("http://") && imageServerCode != null){
                    imageUrl = imageUrl.substring(imageUrl.indexOf("/pic")); //图片相对路径
                    alarm.setImageUrl(imageUrl);
                    alarm.setImageServerCode(imageServerCode);
            }

            alarm.setFkDeviceId(eventInfo.get("resIndexCode") == null?null:eventInfo.get("resIndexCode").toString());
            alarm.setDeviceName(eventInfo.get("resName") == null?null:eventInfo.get("resName").toString());
            alarm.setEventRuleId(json.get("eventRuleId") == null?null:json.get("eventRuleId").toString());
            alarm.setEventTypeId(eventInfo.get("eventType") == null?null:(int)eventInfo.get("eventType"));
            alarm.setEventTypeName(eventInfo.get("eventTypeName") == null?null:eventInfo.get("eventTypeName").toString());
            alarm.setAlarmName(json.get("eventTypeName") == null?null:json.get("eventTypeName").toString());

            String dateTime = json.get("startTime").toString().replace("T"," ");
            Date alarmTime = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS,dateTime);
            alarm.setAlarmTime(alarmTime);
            alarm.setAlarmLevel(json.get("eventLevelValue") == null?null:json.get("eventLevelValue").toString());
            alarm.setHandleStatus(json.get("handleStatus") == null?null:(int)json.get("handleStatus"));
            alarm.setRemark(json.get("remark") == null?null:json.get("remark").toString());
            if (isLogin){
                alarm.setFkOrgGuid(getDeptId());
                alarm.setCreateUser(getUserId());
            }
            map.put(guid,alarm);
        }

        int i = 0;
        if (map.size() > 0){
            i = alarmService.batchSave(map);
        }
        return i;
    }

    /**
     * 是否有登录用户
     * @return
     */
    private Boolean isLogin(){
        Boolean isLogin = true; //登录
        try {
            SecurityUtils.getAuthentication().getPrincipal();
        }catch (Exception e){
            isLogin = false;  //未登录
        }

        return isLogin;
    }

    /**
     * 添加同步日志
     * @param map
     * @param saveNum
     */
    private void saveSynLog(Map<String,Object> map,Integer saveNum){
        SynLog synLog = new SynLog();
        synLog.setType(2);

        JSONObject json = new JSONObject();
        json.put("startTime",map.get("startTime"));
        json.put("endTime",map.get("endTime"));
        json.put("saveNum",saveNum);
        synLog.setLogData(json.toJSONString());
        if (isLogin()){
            synLog.setCreateUser(getUserId());
        }
        synLogService.saveSelective(synLog);
    }

    /**
     * 查询列表
     * @return
     */
    @ApiOperation(value = "报警信息查询",notes = "报警信息查询")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "alarmForm",value = "报警信息",dataType = "AlarmForm")
    )
    @ApiResponse(code = 200,message = "操作成功")
    @PostMapping("/selectList")
    public TableDataInfo selectList(@RequestBody AlarmForm alarmForm){
        List<Alarm> list = alarmService.selectList(alarmForm);
        return getDataTable(list);
    }

    @ApiOperation(value = "获取图片路径",notes = "获取图片路径")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "imageUrl",value = "图片相对路径",dataType = "String"),
            @ApiImplicitParam(name = "imageServerCode",value = "图片存储服务器唯一标识",dataType = "String")
    })
    @ApiResponse(code = 200,message = "操作成功")
    @GetMapping("/getImgUrl")
    private AjaxResult getImgUrl(@RequestParam("imageUrl") String imageUrl,@RequestParam("imageServerCode")String imageServerCode){
        //路径
        String url = "/video/v1/events/picture";

        //组装请求参数
        Map<String,Object> bodys = new HashMap<>();
        bodys.put("svrIndexCode",imageServerCode);
        bodys.put("picUri",imageUrl);
        bodys.put("netProtocol","http");

        String body = JSON.toJSON(bodys).toString();
        //调用接口
        Object object = postAction(url,body,null,null,null);
        if (object != null){
            return AjaxResult.success(object);
        }
        return AjaxResult.error();
    }

    @ApiOperation(value = "修改报警信息状态",notes = "修改报警信息状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "guid",value = "主键",dataType = "String"),
            @ApiImplicitParam(name = "alarmStatus",value = "报警状态",dataType = "Integer")
    })
    @ApiResponse(code = 200,message = "操作成功")
    @GetMapping("/updateAlarmStatus")
    public AjaxResult updateAlarmStatus(@RequestParam("guid") String guid,@RequestParam("alarmStatus") Integer alarmStatus){
        if (StringUtils.isEmpty(guid)){
            throw new CustomException("主键不能为空", 1);
        }
        if (alarmStatus == null){
            throw new CustomException("报警信息状态不能为空", 1);
        }
        Alarm alarm = new Alarm();
        alarm.setGuid(guid);
        alarm.setAlarmStatus(alarmStatus);
        int i = alarmService.modifyByPrimaryKeySelective(alarm);
        if (i > 0){
            return AjaxResult.success();
        }

        return AjaxResult.error();
    }

    @ApiOperation(value = "报警信息误报/屏蔽",notes = "报警信息误报/屏蔽")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "alarm",value = "报警信息",dataType = "Alarm")
    )
    @ApiResponse(code = 200,message = "操作成功")
    @PostMapping("/shield")
    public AjaxResult shield(@RequestBody Alarm alarm){
        //验证数据
        vaildData(alarm);

        String startDate = DateUtils.getTime();
        String endDate = null;
        if (alarm.getAlarmStatus() == 2){ //误报,24小时内相同告警不会再报
            endDate = DateUtils.getAddHourDate(DateUtils.parseDate(startDate),alarm.getShieldTime());
            System.out.println(startDate + ";    " + endDate);
        }
        if (alarm.getAlarmStatus() == 3){ //误报,24小时内相同告警不会再报
            endDate = DateUtils.getAddMinuteDate(DateUtils.parseDate(startDate),alarm.getShieldTime());
            System.out.println(startDate + ";    " + endDate);
        }

        if (alarm.getAlarmStatus() == 2){
            int i = 0;//alarmService.modifyByPrimaryKeySelective(alarm);
            if (i > 0){
                return AjaxResult.success();
            }
        }

        return AjaxResult.error();
    }

    private void vaildData(Alarm alarm){
        if (StringUtils.isEmpty(alarm.getGuid())){
            throw new CustomException("主键不能为空", 1);
        }
        if (alarm.getAlarmStatus() == null){
            throw new CustomException("报警信息状态不能为空", 1);
        }
        if (alarm.getEventTypeId() == null){
            throw new CustomException("报警类型id不能为空", 1);
        }
        if (StringUtils.isEmpty(alarm.getFkDeviceId())){
            throw new CustomException("报警设备id不能为空", 1);
        }

        if (alarm.getAlarmStatus() == 2){
            alarm.setShieldTime(24);
        }

        if (alarm.getAlarmStatus() == 3){
            if (alarm.getShieldTime() == null){
                throw new CustomException("屏蔽时间不能为空", 1);
            }
        }
    }
}
