package com.dcsoft.system.artemis.controller;


import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dcsoft.common.core.constant.CacheConstants;
import com.dcsoft.common.core.utils.JsonUtils;
import com.dcsoft.common.core.web.controller.BaseController;
import com.dcsoft.common.core.web.domain.AjaxResult;
import com.dcsoft.common.redis.service.RedisService;
import com.dcsoft.system.artemis.vo.CarInfoVo;
import com.dcsoft.system.artemis.vo.ChannelVo;
import com.dcsoft.system.artemis.vo.DeviceVo;
import com.dcsoft.system.artemis.vo.VideoStreamVo;
import com.dcsoft.system.camera.domain.TbCamera;
import com.dcsoft.system.camera.service.ITbCameraService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


/**
 * 用户管理 业务处理
 *
 * @author xueyi
 */
@RestController
@RequestMapping("/artemis")
public class ArtemisController extends BaseController {

    @Value("${video.path}")
    private String path;

    @Value("${video.password}")
    private String password;//7636c512092e65e889b806359639b937

    @Autowired
    private ITbCameraService tbCameraService;

    @Resource
    private RedisService redisService;


    @Value("${artemis.url}")
    public String url;
    @Value("${artemis.appKey}")
    public String appKey;
    @Value("${artemis.appSecret}")
    public String appSecret;

    private static final String ARTEMIS_PATH = "/artemis";

    /**
     * 获取设备信息
     *
     * @return 用户信息
     */
    @PostMapping("/cameras")
    public AjaxResult cameras() {
        // 获取access-token
        String accessToken = getToken();

        // 分页查询国标设备
        List<DeviceVo> deviceVos = queryDevice(accessToken);

        List<ChannelVo> channelVos = new ArrayList<>();
        for (DeviceVo deviceVo : deviceVos) {
            // 分页查询通道
            List<ChannelVo> channelList = queryChannels(accessToken, deviceVo);
            channelVos.addAll(channelList);
        }

        // 获取车辆设备信息
        List<CarInfoVo> carInfoVos = queryCarInfo(accessToken);

        List<ChannelVo> list = new ArrayList<>();
        for (CarInfoVo carInfoVo : carInfoVos) {
            ChannelVo channelVo = new ChannelVo();
            channelVo.setName(carInfoVo.getName());
            channelVo.setChannelId(carInfoVo.getStream());
            channelVo.setDeviceId(carInfoVo.getApp());
            list.add(channelVo);
        }
        channelVos.addAll(list);

        // 保存摄像投配置信息
        if(!CollectionUtils.isEmpty(channelVos)) {
            tbCameraService.saveCamera(channelVos);
        }
        return AjaxResult.success();

    }

    /**
     * 获取token
     */
    private String getToken() {
        String cacheObject = redisService.getCacheObject(CacheConstants.LOGIN_TOKEN);
        if(StringUtils.isNotEmpty(cacheObject)) {
            return cacheObject;
        }
        HttpResponse response = HttpUtil.createGet("http://"+ path +"/api/user/login?username=admin&password="+password).execute();
        String body = response.body();
        JSONObject json = JSONObject.parseObject(body);
        String string = json.get("data").toString();
        JSONObject jsonObject = JSONObject.parseObject(string);
        String accessToken = jsonObject.get("accessToken").toString();
        redisService.setCacheObject(CacheConstants.LOGIN_TOKEN, accessToken, CacheConstants.REFRESH_TIME, TimeUnit.MINUTES);
        return accessToken;

    }

    /**
     * 分页查询国标设备
     */
    private List<DeviceVo> queryDevice(String accessToken) {
        HttpResponse response = HttpUtil.createGet("http://"+ path +"/api/device/query/devices?page=1&count=100000").header("access-token", accessToken).execute();
        String body = response.body();
        JSONObject json = JSONObject.parseObject(body);
        String string = json.get("data").toString();
        JSONObject jsonObject = JSONObject.parseObject(string);
        return JsonUtils.parseArray(jsonObject.get("list").toString(), DeviceVo.class);
    }

    /**
     * 分页查询通道
     */
    private List<ChannelVo> queryChannels(String accessToken, DeviceVo deviceVo) {
        String url = "http://"+ path +"/api/device/query/devices/"+ deviceVo.getDeviceId() +"/channels?page=1&count=10000";
        HttpResponse response = HttpUtil.createGet(url).header("access-token", accessToken).execute();
        String body = response.body();
        JSONObject json = JSONObject.parseObject(body);
        String string = json.get("data").toString();
        JSONObject jsonObject = JSONObject.parseObject(string);
        return JsonUtils.parseArray(jsonObject.get("list").toString(), ChannelVo.class);
    }

    /**
     * 获取视频流信息
     * @param accessToken
     * @param channelVo
     * @return
     */
    private VideoStreamVo queryVideoStream(String accessToken, ChannelVo channelVo) {
        String url = "http://"+ path +"/api/play/start/"+ channelVo.getDeviceId() +"/"+ channelVo.getChannelId();
        HttpResponse response = HttpUtil.createGet(url).header("access-token", accessToken).execute();
        String body = response.body();
        JSONObject json = JSONObject.parseObject(body);
        String string = json.get("data").toString();
        VideoStreamVo videoStreamVo = JsonUtils.parseObject(string, VideoStreamVo.class);
        videoStreamVo.setChannelId(channelVo.getChannelId());
        videoStreamVo.setDeviceId(channelVo.getDeviceId());
        return videoStreamVo;
    }

    /**
     * 获取车辆信息
     * @param accessToken
     */
    private List<CarInfoVo> queryCarInfo(String accessToken) {
        HttpResponse response = HttpUtil.createGet("http://"+ path +"/api/proxy/list?page=1&count=100000").header("access-token", accessToken).execute();
        String body = response.body();
        JSONObject json = JSONObject.parseObject(body);
        String string = json.get("data").toString();
        JSONObject jsonObject = JSONObject.parseObject(string);
        return JsonUtils.parseArray(jsonObject.get("list").toString(), CarInfoVo.class);

    }


    /**
     * 获取设备信息
     *
     * @return 用户信息
     */
    @PostMapping("/playCamera")
    public AjaxResult playCamera(String deviceId, String channelId) {
        // 获取access-token
        String accessToken = getToken();

        // 获取视频流信息
        ChannelVo channelVo = new ChannelVo();
        channelVo.setChannelId(channelId);
        channelVo.setDeviceId(deviceId);
        VideoStreamVo videoStreamVo = queryVideoStream(accessToken, channelVo);
        return AjaxResult.success(videoStreamVo);
    }

    /**
     * 查询录像列表
     * @param deviceId
     * @param channelId
     * @param startTime
     * @param endTime
     * @return
     */
    @PostMapping("/queryVideoPlayback")
    public AjaxResult queryVideoPlayback(String deviceId, String channelId, String startTime, String endTime) {
        String accessToken = getToken();
        String url = "http://"+ path +"/api/gb_record/query/"+deviceId+"/"+channelId+"?startTime="+startTime+"&endTime="+endTime;
        HttpResponse response = HttpUtil.createGet(url).header("access-token", accessToken).execute();
        String body = response.body();
        JSONObject json = JSONObject.parseObject(body);
        return AjaxResult.success(json);
    }

    /**
     * 获取录像视频流
     * @param deviceId
     * @param channelId
     * @return
     */
    @PostMapping("/queryPlaybackVideoStream")
    public AjaxResult queryPlaybackVideoStream(String deviceId, String channelId, String startTime, String endTime) {
        String accessToken = getToken();
        String url = "http://"+ path +"/api/playback/start/"+ deviceId +"/"+ channelId + "?startTime="+startTime+"&endTime="+endTime;
        HttpResponse response = HttpUtil.createGet(url).header("access-token", accessToken).execute();
        String body = response.body();
        JSONObject json = JSONObject.parseObject(body);
        String string = json.get("data").toString();
        return AjaxResult.success(JsonUtils.parseObject(string, VideoStreamVo.class));
    }

    /**
     * 设置视频倍数
     * @param streamId
     * @param speed
     * @return
     */
    @PostMapping("/queryVideoSpeed")
    public AjaxResult queryVideoSpeed(String streamId, String speed) {
        String accessToken = getToken();
        String url = "http://"+ path +"/api/playback/speed/"+ streamId +"/"+ speed;
        HttpResponse response = HttpUtil.createGet(url).header("access-token", accessToken).execute();
        String body = response.body();
        JSONObject json = JSONObject.parseObject(body);
        return AjaxResult.success(json);
    }

    /**
     * 停止播放
     * @return
     */
    @PostMapping("/stopVideoStream")
    public AjaxResult stopVideoStream(String deviceId, String channelId, String streamId) {
        String accessToken = getToken();
        String url = "http://"+ path +"/api/playback/stop/"+ deviceId +"/"+ channelId +"/"+ streamId;
        HttpResponse response = HttpUtil.createGet(url).header("access-token", accessToken).execute();
        String body = response.body();
        JSONObject json = JSONObject.parseObject(body);
        return AjaxResult.success(json);
    }

}
