using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Ropin.Inspection.Api.Common;
using Ropin.Inspection.Api.Controllers;
using Ropin.Inspection.Model;
using Ropin.Inspection.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Ropin.Inspection.Model.ViewModel;
using Microsoft.AspNetCore.Authorization;
using Ropin.Inspection.Model.Common;
using static System.Net.Mime.MediaTypeNames;

namespace Ropin.Inspection.Api
{

    public class TmtnDevOpsController : BaseController
    {
        public ILogger<TmtnDevOpsController> _logger { get; }
        private readonly ITmtnDevOpsService _TmtnDevOpsService;
        private readonly IPushMsgService _pushMsgService;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="TmtnDevOpsService"></param>
        /// <param name="pushMsgService"></param>
        /// <param name="logger"></param>
        public TmtnDevOpsController(ITmtnDevOpsService TmtnDevOpsService, IPushMsgService pushMsgService, ILogger<TmtnDevOpsController> logger)
        {
            _TmtnDevOpsService = TmtnDevOpsService;
            _pushMsgService = pushMsgService;
            _logger = logger;
        }

        /// <summary>
        /// 通过id获取运维工单信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("GetDevOpsAsync/{id}")]
        public async Task<ApiResult> GetDevOpsAsync(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return new ApiResult(ReturnCode.GeneralError);
            }
            try
            {
                var content = await _TmtnDevOpsService.GetConditionAsync(new TmtnDevOpsSearchModel { C_ID = id });
                return new ApiResult<TmtnDevOpsViewModel>(content.FirstOrDefault());
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }

        /// <summary>
        /// 获取所有运维工单
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetDevOpssAsync/{name=}")]
        public async Task<ApiResult> GetDevOpssAsync(string name)
        {
            try
            {
                var contentList = await _TmtnDevOpsService.GetAllAsync();
                
                if (string.IsNullOrWhiteSpace(name))
                    return new ApiResult<IEnumerable<TmtnDevOpsViewModel>>(contentList);
                else
                    return new ApiResult<IEnumerable<TmtnDevOpsViewModel>>(contentList.Where(x => x.C_Name.Contains(name)));
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }

        /// <summary>
        /// 条件查询运维工单
        /// </summary>
        /// <param name="searchModel"></param>
        /// <returns></returns>
        [HttpPost("GetDevOpsByAsync")]
        public async Task<ApiResult> GetDevOpsByAsync(TmtnDevOpsSearchModel searchModel)
        {
            if (searchModel == null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            searchModel.IsPagination = false;
            try
            {
                var contentList = await _TmtnDevOpsService.GetConditionAsync(searchModel);
                return new ApiResult<PagesModel<TmtnDevOpsViewModel>>(new PagesModel<TmtnDevOpsViewModel>(contentList, searchModel));
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }
        /// <summary>
        /// 条件查询运维工单列表包含图片
        /// </summary>
        /// <param name="searchModel"></param>
        /// <returns></returns>
        [HttpPost("GetDevOpsWithImageAsync/{name=}")]
        public async Task<ApiResult> GetDevOpsWithImageAsync(TmtnDevOpsOrderSearchModel searchModel, string name)
        {
            if (searchModel == null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            searchModel.IsPagination = false;
            try
            {
                var contentList = await _TmtnDevOpsService.GetDevOpsWithImageAsync(searchModel);
                
                if (string.IsNullOrWhiteSpace(name))
                    return new ApiResult<PagesModel<TmtnDevOpsWithImageViewModel>>(new PagesModel<TmtnDevOpsWithImageViewModel>(contentList, searchModel));
                else
                    return new ApiResult<PagesModel<TmtnDevOpsWithImageViewModel>>(new PagesModel<TmtnDevOpsWithImageViewModel>(contentList.Where(x => x.C_Name.Contains(name)), searchModel));
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }

        /// <summary>
        /// 获取30天运维完成统计
        /// </summary>
        /// <param name="storeCode"></param>
        /// <returns></returns>
        [HttpGet("Get30DaysDevOpsStatisticsAsync/{storeCode}")]
        public async Task<ApiResult> GetRecords30DaysStatisticsAsync(string storeCode)
        {
            if (string.IsNullOrEmpty(storeCode))
            {
                return new ApiResult(ReturnCode.GeneralError);
            }
            try
            {
                var content = await _TmtnDevOpsService.GetRecords30DaysStatisticsAsync(storeCode);
                return new ApiResult<TispRecord30DaysStatisticsViewModel>(content);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }
        /// <summary>
        /// 获取30天运维完成统计大屏
        /// </summary>
        /// <param name="storeCode"></param>
        /// <returns></returns>
        [HttpGet("GetRecords30DaysStatisticsFullScreenAsync/{storeCode}")]
        [AllowAnonymous]
        public async Task<IEnumerable<FullScreenRecordItem>> GetRecords30DaysStatisticsFullScreenAsync(string storeCode)
        {
            if (string.IsNullOrEmpty(storeCode))
            {
                return null;
            }
            try
            {
                var content = await _TmtnDevOpsService.GetRecords30DaysStatisticsFullScreenAsync(storeCode);
                return content;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        /// <summary>
        /// 创建运维工单
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        [HttpPost("CreateDevOpsAsync")]
        public async Task<ApiResult> CreateDevOpsAsync(TmtnDevOpsViewModel content)
        {
            if (content == null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                var results =  await _TmtnDevOpsService.CreateDevOpsAsync(content);
                await _pushMsgService.PushAlarmMsgAsync(new TpushMsgModel
                {
                    C_DevStoreCode = content.C_DevStoreCode,
                    C_MsgTypeCode = "MSG_TYPE_002",
                    Msg = content.C_Name + "  "+ content.C_Remark,
                    Subject = "上报维保: " + content.C_Name,
                    DevNumber = content.C_DevStoreCode,
                    DevName = content.C_DevStoreName,
                    GenerationType = 2,
                    msgStatus = 0,
                }, "设备维保",null, results?.C_ID,"1");
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
            return new ApiResult(ReturnCode.Success);
        }

        /// <summary>
        /// 删除运维工单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("DeleteDevOpsAsync/{id}")]
        public async Task<ApiResult> DeleteDevOpsAsync(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return new ApiResult(ReturnCode.GeneralError);
            }
            try
            {
                await _TmtnDevOpsService.DeleteAsync(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("UpdateDevOpsAsync/{id}")]
        public async Task<ApiResult> UpdateDevOpsAsync(string id, TmtnDevOpsUpdateModel updateModel)
        {
            if (string.IsNullOrEmpty(id))
            {
                return new ApiResult(ReturnCode.GeneralError);
            }
            try
            {
                await _TmtnDevOpsService.UpdateAsync(id, updateModel);
                await _pushMsgService.PushAlarmMsgAsync(new TpushMsgModel
                {
                    C_DevStoreCode = updateModel.C_DevStoreCode,
                    C_MsgTypeCode = "MSG_TYPE_009",
                    Msg = updateModel.C_Name + "  " + updateModel.C_Remark,
                    Subject = updateModel.C_Status == "5"? "维保取消,设备名:": "维保确认,设备名:" + updateModel.C_DevStoreName,
                    DevNumber = updateModel.C_DevStoreCode,
                    DevName = updateModel.C_DevStoreName,
                    GenerationType = 2,
                    msgStatus = 0,
                }, "设备维保",null,id,updateModel.C_Status);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
            return new ApiResult(ReturnCode.Success);
        }

        /// <summary>
        /// 通过设备ID取运维内容及状态,大屏
        /// </summary>
        /// <param name="devStoreCode"></param>
        /// <returns></returns>
        [HttpPost("GetDevOpsFullScreenByDevIdAsync")]
        [AllowAnonymous]
        public async Task<ApiResult> GetDevOpsFullScreenByDevIdAsync(DevOpsItemSearchModel searchModel)
        {
            if (searchModel == null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                var opslist = await _TmtnDevOpsService.GetDevOpsFullScreenByDevIdAsync(searchModel);
                var repairList = await _TmtnDevOpsService.GetDevRepairFullScreenByDevIdAsync(searchModel);
                var recordList = await _TmtnDevOpsService.GetISPRecordAsync(searchModel);
                IEnumerable<DevOpsFullScreenRecord> list;
                if (opslist == null)
                    opslist = new List<DevOpsFullScreenRecord>();
                if (repairList == null)
                    repairList = new List<DevOpsFullScreenRecord>();
                if (recordList == null)
                    recordList = new List<DevOpsFullScreenRecord>();
                list = opslist?.Concat(repairList).Concat(recordList).ToList().OrderByDescending(o => o.RecordTime);

                if (!list.Any())
                {
                    searchModel.TotalCount = 0;
                    return new ApiResult<PagesModel<DevOpsFullScreenRecord>>(new PagesModel<DevOpsFullScreenRecord>(list, searchModel));
                }
                searchModel.TotalCount = list.Count();
                return new ApiResult<PagesModel<DevOpsFullScreenRecord>>(new PagesModel<DevOpsFullScreenRecord>(searchModel.IsPagination ? list.Skip((searchModel.PageIndex - 1) * searchModel.PageSize).Take(searchModel.PageSize) : list, searchModel));
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }
        /// <summary>
        /// 通过设备ID取运维内容及状态统计,大屏
        /// </summary>
        /// <param name="devStoreCode"></param>
        /// <returns></returns>
        [HttpPost("GetDevOpsCountFullScreenByDevIdAsync")]
        [AllowAnonymous]
        public async Task<ApiResult> GetDevOpsCountFullScreenByDevIdAsync(DevOpsItemSearchModel searchModel)
        {
            if (searchModel == null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                var content = await _TmtnDevOpsService.GetDevOpsCountFullScreenByDevIdAsync(searchModel);
                //content.DevOpsRecordItem.Where(x => x.C_Status == "1").Count();
                return new ApiResult<RepairStatistics>(content);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }
        /// <summary>
        /// 通过设备ID取维修内容及状态统计,大屏
        /// </summary>
        /// <param name="devStoreCode"></param>
        /// <returns></returns>
        [HttpPost("GetDevRepairCountFullScreenByDevIdAsync")]
        [AllowAnonymous]
        public async Task<ApiResult> GetDevRepairCountFullScreenByDevIdAsync(DevOpsItemSearchModel searchModel)
        {
            if (searchModel == null)
            {
                return new ApiResult(ReturnCode.ArgsError);
            }
            try
            {
                var content = await _TmtnDevOpsService.GetDevRepairCountFullScreenByDevIdAsync(searchModel);
                //content.DevOpsRecordItem.Where(x => x.C_Status == "1").Count();
                return new ApiResult<RepairStatistics>(content);
            }
            catch (Exception ex)
            {
                return new ApiResult(ReturnCode.GeneralError, ex.Message);
            }
        }

    }
}