package com.sooka.sponest.monitor.dahua.controller;

import com.dahuatech.hutool.json.JSONArray;
import com.dahuatech.icc.exception.ClientException;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import com.sooka.sponest.monitor.dahua.domain.CenterdataTAttach;
import com.sooka.sponest.monitor.dahua.domain.CentermonitorTMonitoringEquipmentPositionDO;
import com.sooka.sponest.monitor.dahua.domain.PlayBackProperties;
import com.sooka.sponest.monitor.dahua.service.DahuaService;
import com.sooka.sponest.monitor.device.mapper.CentermonitorTMonitoringEquipmentPositionMapper;
import com.sooka.sponest.monitor.remoteapi.service.center.system.RemoteService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.springframework.web.bind.annotation.RequestMethod.*;

@Api(tags = "大华控制器")
@RestController
@RequestMapping("DahuaController")
@Slf4j
public class DahuaController {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    DahuaService dahuaService;

    @Resource
    RemoteService remoteService;

    @Resource
    CentermonitorTMonitoringEquipmentPositionMapper centermonitorTMonitoringEquipmentPositionMapper;

    /**
     * 获取token方法
     * 调用此方法以获取token
     * */
    @Log(title = "大华", businessType = BusinessType.OTHER)
    @ApiOperation(value = "获取token", notes = "获取token")
    @RequestMapping(value = "getToken",method = GET)
    public String getToken() {
        return dahuaService.getToken();
    }

    /**
     * 获取token方法
     * 调用此方法以密码形式获取token
     * */
    @Log(title = "大华", businessType = BusinessType.OTHER)
    @ApiOperation(value = "密码获取token", notes = "密码获取token")
    @RequestMapping(value = "getTokenByPassword",method = GET)
    public String getTokenByPassword() {
        return dahuaService.getTokenByPassword();
    }

    /**
     * 订阅大华事件方法，更换icc服务后需要更改nacos配置
     * 并重新调用此方法以订阅事件
     * 火情报警：business  forest.alarm
     * 设备上/离线：state
     * 设备低电压：alarm 225
     * new String[]{"forest.alarm"}
     * */
    @Log(title = "大华", businessType = BusinessType.OTHER)
    @ApiOperation(value = "订阅大华事件", notes = "订阅大华事件")
    @RequestMapping(value = "eventSubscribe",method = POST)
    public AjaxResult eventSubscribe(String name, String monitorUrl, String category, String[] type) throws ClientException{
        return dahuaService.eventSubscribe(name,monitorUrl,category,type);
    }

    /**
     * 取消事件订阅
     * monitorType 固定为 url
     * category state alarm ...
     * */
    @Log(title = "大华", businessType = BusinessType.OTHER)
    @ApiOperation(value = "事件订阅列表查询", notes = "事件订阅列表查询")
    @RequestMapping(value = "subscribeList",method = GET)
    public AjaxResult subscribeList(String monitorType, String category) throws ClientException{
        return dahuaService.subscribeList(monitorType,category);
    }

    /**
     * 取消事件订阅
     * name 为 ip_port
     * */
    @Log(title = "大华", businessType = BusinessType.OTHER)
    @ApiOperation(value = "取消事件订阅", notes = "取消事件订阅")
    @RequestMapping(value = "removeEventSubscribe",method = DELETE)
    public AjaxResult removeEventSubscribe(String name) throws ClientException{
        return dahuaService.removeEventSubscribe(name);
    }

    /**
     * 事件订阅接收消息方法
     * @param request
     * @return
     */
    @Log(title = "大华", businessType = BusinessType.OTHER)
    @RequestMapping(value = "/receiveEvents",method = POST)
    public AjaxResult receiveEvents(HttpServletRequest request) {
        String blody = "";
        try {
             blody = ReadAsChars(request);
            logger.info("接收报文----" + blody);
            return AjaxResult.success("接收报文成功",blody);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("接收报文失败",blody);
    }

    /**
     * 火点摄像头联动接口
     * @param lng
     * @param lat
     * @param list
     * @return
     */
    @Log(title = "大华", businessType = BusinessType.OTHER)
    @RequestMapping(value = "/rotation",method = GET)
    public AjaxResult rotation(Double lng, Double lat, @RequestParam("list") List<String> list) {
        return dahuaService.rotation(lng,lat,list);
    }

    /**
     * 摄像头获取回放
     * @return
     */
    @Log(title = "大华", businessType = BusinessType.OTHER)
    @RequestMapping(value = "/getPlaybackByTime",method = POST)
    public AjaxResult getPlaybackByTime(@RequestBody String properties) {
        return dahuaService.getPlaybackByTime(properties);
    }

    /**
     * 获取大华账号密码id等信息
     *
     */
    @Log(title = "大华", businessType = BusinessType.OTHER)
    @ApiOperation(value = "获取大华视频服务", notes = "获取大华视频服务")
    @RequestMapping(value = "getDahuaVideoServer", method = GET)
    public Object getDahuaData() {
        Map<String, Object> result = new HashMap<>();
        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        R<SysUser> userResponse = remoteService.selectById(userId);//取运管用户信息中数据
        AjaxResult videoServerResult = dahuaService.getDahuaVideoServer();//取nacos中数据
        Map<String, Object> userData = new HashMap<>();
        userData.put("userName", userResponse.getData().getDahuaAccount());
        userData.put("userPwd", userResponse.getData().getDahuaPassword());
        userData.put("loginIp", videoServerResult.get("loginIp"));
        userData.put("loginPort", videoServerResult.get("loginPort"));
        result.put("videoServer", userData);
        return userData;
    }

    /**
     * 获取大华账号密码id等信息（APP）
     *
     */
    @Log(title = "大华", businessType = BusinessType.OTHER)
    @ApiOperation(value = "获取大华视频服务", notes = "获取大华视频服务")
    @RequestMapping(value = "getDahuaVideoServerApp",method = GET)
    public Map<String, Object> getDahuaVideoServerApp(){
        Map<String, Object> result = new HashMap<>();
        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        R<SysUser> userResponse = remoteService.selectById(userId);//取运管用户信息中数据
        AjaxResult videoServerResult = dahuaService.getDahuaVideoServerApp();//取nacos中数据
        Map<String, Object> userData = new HashMap<>();
        userData.put("userNameApp", userResponse.getData().getDahuaAccount());
        userData.put("userPwdApp", userResponse.getData().getDahuaPassword());
        userData.put("loginIpApp", videoServerResult.get("loginIpApp"));
        userData.put("loginPortApp", videoServerResult.get("loginPortApp"));
        result.put("data", userData);
        return AjaxResult.success(userData);
    }

    /**
     * 获取大华ICC服务
     */
    @Log(title = "大华", businessType = BusinessType.OTHER)
    @ApiOperation(value = "获取大华ICC服务", notes = "获取大华ICC服务")
    @RequestMapping(value = "getDahuaDssServer", method = GET)
    public Object getDahuaDssServer() {
        LoginUser user = SecurityUtils.getLoginUser();
        if(user == null){
            return AjaxResult.error("用户未登录");
        }
        return AjaxResult.success(dahuaService.getDahuaDssServer());//取nacos中数据;
    }

    /**
     * 远程获取图片路径
     * @param attach_ids
     */
    @Log(title = "大华", businessType = BusinessType.OTHER)
    @ApiOperation(value = "获取图片路径", notes = "获取图片路径")
    @RequestMapping(value = "getImgUrl",method = POST)
    public List<CenterdataTAttach> getImgUrl(@RequestBody List<CenterdataTAttach> attach_ids){
        return dahuaService.getImgUrl(attach_ids);
    }

    /**
     * 远程获取图片路径
     * @param attach_ids
     */
    @Log(title = "大华", businessType = BusinessType.OTHER)
    @ApiOperation(value = "远程获取图片路径", notes = "远程获取图片路径")
    @ApiImplicitParam(name = "attach_ids", value = "附件对象集合(List)", paramType = "query", example = "List<CenterdataTAttach>")
    @PostMapping("remotegetImgUrl")
    public R<List<CenterdataTAttach>> remotegetImgUrl(@RequestBody List<CenterdataTAttach> attach_ids){
        return R.ok(dahuaService.getImgUrl(attach_ids));
    }

    /**
     * 同步摄像头离线状态
     * 调用此方法以将大华平台摄像头状态同步到一体化平台监控中心
     * */
    @Log(title = "大华", businessType = BusinessType.OTHER)
    @ApiOperation(value = "同步摄像头离线状态", notes = "调用此方法以将大华平台摄像头状态同步到一体化平台监控中心")
    @RequestMapping(value = "synchronizeOfflineCamera",method = POST)
    public AjaxResult synchronizeOfflineCamera() {
        return dahuaService.synchronizeOfflineCamera();
    }

    /**
     * 获取大华摄像头的预置点
     * */
    @Log(title = "大华", businessType = BusinessType.OTHER)
    @ApiOperation(value = "获取摄像头预置点", notes = "获取摄像头预置点")
    @RequestMapping(value = "getPresetPoints",method = GET)
    public AjaxResult getPresetPoints(String channelId) {
        return dahuaService.getPresetPoints(channelId);
    }

    /**
     * 预置点控制(添加/删除/定位)
     * */
    @Log(title = "大华", businessType = BusinessType.OTHER)
    @ApiOperation(value = "预置点控制(添加/删除/定位)", notes = "预置点控制(添加/删除/定位)")
    @RequestMapping(value = "operatePresetPoint",method = GET)
    public AjaxResult operatePresetPoint(String channelId,String presetPointCode,String presetPointName,String operateType) {
        return dahuaService.operatePresetPoint(channelId,presetPointCode,presetPointName,operateType);
    }

    /**
     *获取记录仪位置数据
     */
    @PostMapping("putDahuaRecorderLocation")
    @ResponseBody
    public AjaxResult insertLocationListToday(@RequestBody CentermonitorTMonitoringEquipmentPositionDO centermonitorTMonitoringEquipmentPositionDO) {
        try {
            dahuaService.insertEquipmentPosition(centermonitorTMonitoringEquipmentPositionDO);
            //更新执法记录仪经纬度
            logger.info("获取记录仪位置数据:{}",centermonitorTMonitoringEquipmentPositionDO);
            centermonitorTMonitoringEquipmentPositionMapper.updateLongitudeAndLatitudeByCameraCode(centermonitorTMonitoringEquipmentPositionDO.getGpsX(),centermonitorTMonitoringEquipmentPositionDO.getGpsY(),centermonitorTMonitoringEquipmentPositionDO.getChannelCode());
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(500, "内部服务器错误");
        }
    }



    public static String ReadAsChars(HttpServletRequest request) {

        BufferedReader br = null;
        StringBuilder sb = new StringBuilder("");
        try {
            br = request.getReader();
            String str;
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }
}
