using log4net;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Ropin.Inspection.Api.Common;
using Ropin.Inspection.Model.SearchModel.VMC;
using Ropin.Inspection.Model.ViewModel.VMC;
using Ropin.Inspection.Model;
using Ropin.Inspection.Service.VMC.Interface;
using System.Threading.Tasks;
using System;
using Ropin.Inspection.Model.Entities;
using Ropin.Inspection.Common.Helper;
using System.Collections.Generic;
using System.Linq;
using Ropin.Inspection.Model.Common;

namespace Ropin.Inspection.Api.Controllers.VMC
{
    public class VmcCameraController : BaseController
    {
        private readonly IVmcCameraService _repository;
        private static readonly ILog log = LogManager.GetLogger(typeof(VmcCameraController));
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="repository"></param>
        public VmcCameraController(IVmcCameraService repository)
        {
            _repository = repository;
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        [HttpPost("CreateAsync")]
        public async Task<ApiResult> CreateAsync(VmcCameraViewModel content)
        {
            if (content == null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                await _repository.CreateOneAsync(content);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
            return new ApiResult(ReturnCode.Success);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("DeleteAsync/{id}")]
        public async Task<ApiResult> DeleteAsync(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return new ApiResult(ReturnCode.GeneralError);
            }
            try
            {
                await _repository.DeleteAsync(id);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
            return new ApiResult(ReturnCode.Success);
        }
        /// <summary>
        /// 禁用
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPut("ForbiddenAsync/{id}")]
        public async Task<ApiResult> ForbiddenAsync(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return new ApiResult(ReturnCode.GeneralError);
            }
            try
            {
                await _repository.ForbiddenAsync(id);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
            return new ApiResult(ReturnCode.Success);
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id"></param>
        /// <param name="updateModel"></param>
        /// <returns></returns>
        [HttpPut("UpdateAsync/{id}")]
        [AllowAnonymous]
        public async Task<ApiResult> UpdateAsync(string id, VmcCameraViewModel updateModel)
        {
            if (string.IsNullOrEmpty(id))
            {
                return new ApiResult(ReturnCode.GeneralError);
            }
            try
            {
                await _repository.UpdateAsync(updateModel, id);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
            return new ApiResult(ReturnCode.Success);
        }
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns></returns>
        [HttpPost("PageAsync")]
        [AllowAnonymous]
        public async Task<ApiResult> PageAsync(VmcCameraSearch searchModel)
        {
            if (searchModel == null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                var contentList = await _repository.GetConditionAsync(searchModel);
                return new ApiResult<PagesModel<VmcCameraViewModel>>(new PagesModel<VmcCameraViewModel>(contentList, searchModel));
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }
        /// <summary>
        /// 通过id获取详情
        /// </summary>
        /// <returns></returns>
        [HttpGet("DetailsAsync")]
        [AllowAnonymous]
        public async Task<ApiResult> DetailsAsync(string Id)
        {
            if (string.IsNullOrEmpty(Id))
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                VmcCameraViewModel data = await _repository.GetByIdAsync(Id);
                return new ApiResult<VmcCameraViewModel>(data);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }
        /// <summary>
        /// 新增业主摄像头迁移
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        [HttpPost("CreateCameraMigrateAsync")]
        public async Task<ApiResult> CreateCameraMigrateAsync(TVMC_CameraMigrate content)
        {
            if (content == null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                await _repository.CreateCameraMigrate(content);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
            return new ApiResult(ReturnCode.Success);
        }
        /// <summary>
        /// 获取业主摄像头迁移列表
        /// </summary>
        /// <returns></returns>
        [HttpPost("CameraMigratePageAsync")]
        [AllowAnonymous]
        public async Task<ApiResult> CameraMigratePageAsync(VmcCameraMigrateSearch searchModel)
        {
            if (searchModel == null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                var contentList = await _repository.GetCameraMigrateConditionAsync(searchModel);
                return new ApiResult<PagesModel<VmcCameraMigrateViewModel>>(new PagesModel<VmcCameraMigrateViewModel>(contentList, searchModel));
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }

        /// <summary>
        /// 新增设备摄像头关联-单实体
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        [HttpPost("CreateDevCameraAsync")]
        public async Task<ApiResult> CreateDevCameraAsync(TVMC_DevCamera content)
        {
            if (content == null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                await _repository.CreateDevCamera(content);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
            return new ApiResult(ReturnCode.Success);
        }

        /// <summary>
        /// 新增设备摄像头关联-列表
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        [HttpPost("CreateDevCameraListAsync")]
        public async Task<ApiResult> CreateDevCameraListAsync(VmcDevCamera content)
        {
            if (content == null||content.CameraList == null|| content.CameraList.Count==0)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                await _repository.CreateDevCameraList(content);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
            return new ApiResult(ReturnCode.Success);
        }

        /// <summary>
        /// 获取设备摄像头列表
        /// </summary>
        /// <returns></returns>
        [HttpPost("DevCameraPageAsync")]
        [AllowAnonymous]
        public async Task<ApiResult> DevCameraPageAsync(VmcDevSearch searchModel)
        {
            if (searchModel == null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                var contentList = await _repository.GetDevCameraConditionAsync(searchModel);
                return new ApiResult<PagesModel<VmcDevCameraViewModel>>(new PagesModel<VmcDevCameraViewModel>(contentList, searchModel));
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }

        /// <summary>
        /// 获取LiveGBS登录token
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetLiveFBSToken")]
        [AllowAnonymous]
        public async Task<ApiResult> GetLiveFBSToken()
        {
            try
            {
                GBSToken token = await LiveGBSHelper.GetToken();
                return new ApiResult<GBSToken>(token);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }

        /// <summary>
        /// 获取LiveGBS列表
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetLiveFBSListAsync")]
        [AllowAnonymous]
        public async Task<ApiResult> GetLiveFBSListAsync(TbdmCodeSearchModel searchModel)
        {
            if (searchModel == null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                if (!string.IsNullOrEmpty(searchModel.C_Value))
                {
                    switch (searchModel.C_Code)
                    {
                        case "VIDEO_TYPE_001": LiveGBSHelper.loginUrl = searchModel.C_Value;break;
                        default:
                            break;
                    }                    
                }
                //LiveGBS
                if (searchModel.C_Code== "VIDEO_TYPE_001")
                {
                    List<LiveGBSModel> list = new List<LiveGBSModel>();
                    DeviceChanneModel channeModel = await LiveGBSHelper.GetDeviceChannellist();
                    if (channeModel != null && channeModel.ChannelList.Count > 0)
                    {
                        foreach (var item in channeModel.ChannelList)
                        {
                            LiveGBSModel model = new LiveGBSModel();
                            model.ChannelID = item.ID;
                            model.DeviceID = item.DeviceID;
                            model.DeviceName = item.DeviceName;
                            model.DeviceOnline = item.DeviceOnline;
                            model.Channel = item.Channel;
                            model.Name = item.Name;
                            model.SnapURL = item.SnapURL;
                            model.Model = item.Model;
                            model.Status = item.Status;
                            ChannelVideo channelVideo = await LiveGBSHelper.GeChannelVideo(item.DeviceID, item.ID);
                            if (channelVideo != null)
                            {
                                model.StreamID = channelVideo.StreamID;
                                model.SMSID = channelVideo.SMSID;
                                if (!string.IsNullOrEmpty(channelVideo.FLV))
                                {
                                    string flv = "/sms" + channelVideo.FLV?.Split("sms")[1];
                                    model.FLV = flv;
                                }
                                if (!string.IsNullOrEmpty(channelVideo.HLS))
                                {
                                    string hls = "/sms" + channelVideo.HLS?.Split("sms")[1];
                                    model.HLS = hls;
                                }
                                model.RTMP = channelVideo.RTMP;
                                //model.VSnapURL = channelVideo.SnapURL;
                                model.WEBRTC = channelVideo.WEBRTC;
                                model.WS_FLV = channelVideo.WS_FLV;
                            }
                            list.Add(model);
                        }
                    }
                    return new ApiResult<List<LiveGBSModel>>(list);
                }
                else
                {
                    return new ApiResult<object>(null);
                }
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }

        /// <summary>
        ///  前端设备录像(历史视频)
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetLiveFBSHistoryAsync")]
        [AllowAnonymous]
        public async Task<ApiResult> GetLiveFBSHistoryAsync(VmcCameraSearch searchModel)
        {
            if (searchModel == null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                bool IsPage = searchModel.IsPagination;
                searchModel.IsPagination = false;
                var contentList = await _repository.GetConditionAsync(searchModel);
                if (contentList == null)
                {
                    return new ApiResult<IEnumerable<RecordList>>(null);
                }
                List<RecordList> list = new List<RecordList>();
                foreach (var content in contentList)
                {
                    //LiveGBS
                    if (content.C_Type == "VIDEO_TYPE_001")
                    {
                        if (!string.IsNullOrEmpty(content.C_Serial) && !string.IsNullOrEmpty(content.C_CameraCode))
                        {
                            LiveGBSHelper.loginUrl = content.TypeValue;
                            string startTime = searchModel.VideoStartData;
                            string EndTime = searchModel.VideoEndData;
                            if (string.IsNullOrEmpty(startTime))
                            {
                                startTime = DateTime.Now.AddHours(-1).ToString("yyy-MM-ddTHH:mm:ss");
                            }
                            if (string.IsNullOrEmpty(EndTime))
                            {
                                EndTime = DateTime.Now.ToString("yyy-MM-ddTHH:mm:ss");
                            }
                            playbackRecordList datas = await LiveGBSHelper.playbackRecordList(content.C_Serial, content.C_CameraCode, startTime, EndTime);
                            if (datas != null && datas.RecordList != null && datas.RecordList.Count > 0)
                            {
                                datas.RecordList.ForEach(record =>
                                {
                                    record.CameraName = content.C_Name;
                                    record.DeviceID = content.C_Serial;
                                    record.ChannelID = content.C_CameraCode;
                                });

                                list.AddRange(datas.RecordList);
                            }
                        }                      
                    }
                }
                searchModel.TotalCount=list.Count;
                if (IsPage)
                {
                    var pageLIst= list.Skip((searchModel.PageIndex - 1) * searchModel.PageSize).Take(searchModel.PageSize);
                    return new ApiResult<PagesModel<RecordList>>(new PagesModel<RecordList>(pageLIst, searchModel));
                }
                else
                {
                    return new ApiResult<PagesModel<RecordList>>(new PagesModel<RecordList>(list, searchModel));
                }
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }

        /// <summary>
        /// 前端设备录像-视频回放
        /// </summary>
        /// <returns></returns>
        [HttpPost("LiveFBSPlaybackStart")]
        [AllowAnonymous]
        public async Task<ApiResult> LiveFBSPlaybackStart(LiveFBSSearch searchModel)
        {
            if (searchModel == null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                string startTime = searchModel.VideoStartData;
                string EndTime = searchModel.VideoEndData;
                ChannelVideo datas = await LiveGBSHelper.playbackStart(searchModel.C_Serial, searchModel.C_CameraCode, startTime, EndTime,searchModel.Download,searchModel.DownloadSpeed);
                if (!string.IsNullOrEmpty(datas.FLV))
                {
                    string flv = "/sms" + datas.FLV?.Split("sms")[1];
                    datas.FLV = flv;
                }
                if (!string.IsNullOrEmpty(datas.HLS))
                {
                    string hls = "/sms" + datas.HLS?.Split("sms")[1];
                    datas.HLS = hls;
                }
                return new ApiResult<ChannelVideo>(datas);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }

        /// <summary>
        /// 前端设备录像-回放控制
        /// </summary>
        /// <returns></returns>
        [HttpPost("LiveFBSPlaybackControl")]
        [AllowAnonymous]
        public async Task<ApiResult> LiveFBSPlaybackControl(LiveGBSPlayControl searchModel)
        {
            if (searchModel == null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                string datas = await LiveGBSHelper.playbackControl(searchModel.StreamId, searchModel.Command,searchModel.Range, searchModel.Scale);
                return new ApiResult<object>(datas);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }

        /// <summary>
        /// 前端设备录像- 视频回放流停止
        /// </summary>
        /// <returns></returns>
        [HttpPost("LiveFBSPlaybackStop")]
        [AllowAnonymous]
        public async Task<ApiResult> LiveFBSPlaybackStop(LiveFBSSearch searchModel)
        {
            if (searchModel == null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                playbackStopPlaybackFileURL datas = await LiveGBSHelper.playbackStop(searchModel.StreamId);
                if (datas!=null&&!string.IsNullOrEmpty(datas.PlaybackFileURL))
                {
                    string hls = "/sms" + datas.PlaybackFileURL.Split("sms")[1];
                    datas.PlaybackFileURL = hls;
                }

                return new ApiResult<playbackStopPlaybackFileURL>(datas);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }


        /// <summary>
        /// 前端设备录像- 单条回放流信息
        /// </summary>
        /// <returns></returns>
        [HttpPost("LiveFBSPlaybackStreaminfo")]
        [AllowAnonymous]
        public async Task<ApiResult> LiveFBSPlaybackStreaminfo(LiveFBSSearch searchModel)
        {
            if (searchModel == null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                playbackStreaminfoEntity datas = await LiveGBSHelper.playbackStreaminfo(searchModel.StreamId);
                if (datas != null && !string.IsNullOrEmpty(datas.PlaybackFileURL))
                {
                    string hls = "/sms" + datas.PlaybackFileURL.Split("sms")[1];
                    datas.PlaybackFileURL = hls;
                }
                return new ApiResult<playbackStreaminfoEntity>(datas);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }
    }
}