using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Api.SignToken;
using AutoMapper;
using EquipmentApi.IRepositories;
using MadRunFabric.Common;
using MadRunFabric.Common.Http;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace EquipmentApi.Controllers.reportmanage
{
    [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class RunningChartController : BaseController
    {
        private readonly ILogger<RunningChartController> _logger;
        private readonly IConfiguration _configuration;
        private readonly ISys_User_AccountRepository _sys_user_accountRepository;
        private readonly IRunningChartRepository _runningchartRepository;
        private readonly ISignTokenService _signTokenService;
        private readonly ISys_NewsRepository _sys_newsRepository;
        private readonly IMapper _mapper;

        public RunningChartController(
            ILogger<RunningChartController> logger,
            IConfiguration configuration,
            ISys_User_AccountRepository sys_user_accountRepository,
            IRunningChartRepository runningchartRepository,
            ISignTokenService signTokenService,
            ISys_NewsRepository sys_newsRepository,
            IMapper mapper
            )
        {
            _logger = logger;
            _configuration = configuration;
            _sys_user_accountRepository = sys_user_accountRepository;
            _runningchartRepository = runningchartRepository;
            _signTokenService = signTokenService;
            _sys_newsRepository = sys_newsRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 综合-获取温度、湿度、风速、空气质量
        /// </summary>
        /// <param name="latitude"></param>
        /// <param name="longitude"></param>
        /// <returns></returns>
        [HttpGet("getweatherbylatlng")]
        public IActionResult GetWeatherByLatLng(string latitude, string longitude)
        {
            string lurl = _configuration["location:url"];
            string key = _configuration["location:key"];
            string poi = _configuration["location:poi"];
            string strresult = HttpMethods.HttpGet(lurl + $"?location={latitude},{longitude}&key={key}&get_poi={poi}");
            var cityinfo = strresult.ToJObject()["result"].ToString().ToJObject()["address_component"].ToString().ToJObject();

            string province = cityinfo["province"].ToString();
            string city = cityinfo["city"].ToString();
            string wurl = _configuration["weather:url"].ToString();
            string paras = _configuration["weather:params"].ToString();
            string result = HttpHelper.HttpGet(wurl + "?" + paras.Replace("省名", province).Replace("市名", city));

            return Success("获取成功", result.ToJObject());
        }


        /// <summary>
        /// 综合-获取温度、湿度、风速、空气质量
        /// </summary>
        /// <param name="province"></param>
        /// <param name="city"></param>
        /// <returns></returns>
        [HttpGet("getweather")]
        public IActionResult GetWeather(string province, string city)
        {
            string url = _configuration["weather:url"].ToString();
            string paras = _configuration["weather:params"].ToString();
            string result = HttpHelper.HttpGet(url + "?" + paras.Replace("省名", province).Replace("市名", city));

            return Success("获取成功", result.ToJObject());
        }

        /// <summary>
        /// 维修工单-状态
        /// </summary>
        /// <param name="projectid"></param>
        /// <param name="datetype"></param>
        /// <returns></returns>
        [HttpGet("getrepairstate")]
        public IActionResult GetRepairState(string projectid, int datetype = 4)
        {
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            string start = string.Empty;
            string end = string.Empty;
            GetStartEndTime(datetype, out start, out end);
            var result = _runningchartRepository.GetRepairState(projectid, start, end, userinfo);

            return Success("获取成功", result);
        }

        /// <summary>
        /// 维修工单-来源
        /// </summary>
        /// <returns></returns>
        [HttpGet("getrepairsource")]
        public IActionResult GetRepairSource(string projectid, int datetype = 4)
        {
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            string start = string.Empty;
            string end = string.Empty;
            GetStartEndTime(datetype, out start, out end);
            var result = _runningchartRepository.GetRepairSource(projectid, start, end, userinfo);

            return Success("获取成功", result);
        }

        /// <summary>
        /// 维修工单-满意度
        /// </summary>
        /// <returns></returns>
        [HttpGet("getrepairscore")]
        public IActionResult GetRepairScore(string projectid, int datetype = 4)
        {
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            string start = string.Empty;
            string end = string.Empty;
            GetStartEndTime(datetype, out start, out end);
            var result = _runningchartRepository.GetRepairScore(projectid, start, end, userinfo);

            return Success("获取成功", result);
        }

        /// <summary>
        /// 维修工单-及时率
        /// </summary>
        /// <returns></returns>
        [HttpGet("getrepairtime")]
        public IActionResult GetRepairTime(string projectid, int datetype = 4)
        {
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            string start = string.Empty;
            string end = string.Empty;
            GetStartEndTime(datetype, out start, out end);
            var result = _runningchartRepository.GetRepairTime(projectid, start, end, userinfo);

            return Success("获取成功", result);
        }

        /// <summary>
        /// 维修工单-报修状态数量
        /// </summary>
        /// <param name="projectid"></param>
        /// <param name="datetype"></param>
        /// <returns></returns>
        [HttpGet("getrepairstatecount")]
        public IActionResult GetRepairStateCount(string projectid, int datetype = 4)
        {
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            string start = string.Empty;
            string end = string.Empty;
            GetStartEndTime(datetype, out start, out end);
            var result = _runningchartRepository.GetRepairStateCount(projectid, start, end, userinfo);

            return Success("获取成功", result);
        }

        /// <summary>
        /// 维修工单-维修工满意度
        /// </summary>
        /// <param name="projectid"></param>
        /// <param name="datetype"></param>
        /// <returns></returns>
        [HttpGet("getuserrepaireval")]
        public IActionResult GetUserRepairEval(string projectid, int datetype = 4)
        {
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            string start = string.Empty;
            string end = string.Empty;
            GetStartEndTime(datetype, out start, out end);
            var result = _runningchartRepository.GetUserRepairEval(projectid, start, end, userinfo);

            return Success("获取成功", result);
        }

        /// <summary>
        /// 维修工单-维修工接单量
        /// </summary>
        /// <param name="projectid"></param>
        /// <param name="datetype"></param>
        /// <returns></returns>
        [HttpGet("getuseracceptcount")]
        public IActionResult GetUserAcceptCount(string projectid, int datetype = 4)
        {
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            string start = string.Empty;
            string end = string.Empty;
            GetStartEndTime(datetype, out start, out end);
            var result = _runningchartRepository.GetUserAcceptCount(projectid, start, end, userinfo);

            return Success("获取成功", result);
        }

        /// <summary>
        /// 维修工单-24小时报修统计
        /// </summary>
        /// <param name="projectid"></param>
        /// <param name="datetype"></param>
        /// <returns></returns>
        [HttpGet("get24hourrepaircount")]
        public IActionResult Get24HourRepairCount(string projectid, int datetype = 4)
        {
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            string start = string.Empty;
            string end = string.Empty;
            GetStartEndTime(datetype, out start, out end);

            var result = _runningchartRepository.Get24HourRepairCount(projectid, start, end, userinfo);

            return Success("获取成功", result);
        }

        /// <summary>
        /// 维修工单-工单未完成
        /// </summary>
        /// <param name="projectid"></param>
        /// <param name="top"></param>
        /// <returns></returns>
        [HttpGet("getnodeallist")]
        public IActionResult GetNoDealList(string projectid, int top = 15)
        {
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            var result = _runningchartRepository.GetNoDealList(projectid, top, userinfo);

            return Success("获取成功", result);
        }

        /// <summary>
        /// 项目-到期项目
        /// </summary>
        /// <param name="projectid"></param>
        /// <returns></returns>
        [HttpGet("getprojecttimeout")]
        public IActionResult GetProjectTimeOut(string projectid)
        {
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            var result = _runningchartRepository.GetProjectTimeOut(projectid, userinfo);

            return Success("获取成功", result);
        }

        /// <summary>
        /// 项目-项目状态数量
        /// </summary>
        /// <param name="projectid"></param>
        /// <returns></returns>
        [HttpGet("getprojectstatecount")]
        public IActionResult GetProjectStateCount(string projectid)
        {
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            var result = _runningchartRepository.GetProjectStateCount(projectid, userinfo);

            return Success("获取成功", result);
        }

        /// <summary>
        /// 项目-已维修工单
        /// </summary>
        /// <param name="projectid"></param>
        /// <param name="datetype"></param>
        /// <returns></returns>
        [HttpGet("getprojectrepair")]
        public IActionResult GetProjectRepair(string projectid, int datetype = 4)
        {
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            string start = string.Empty;
            string end = string.Empty;
            GetStartEndTime(datetype, out start, out end);
            var result = _runningchartRepository.GetProjectRepair(projectid, start, end, userinfo);

            return Success("获取成功", result);
        }

        /// <summary>
        /// 项目-项目信息列表
        /// </summary>
        /// <param name="projectid"></param>
        /// <param name="datetype"></param>
        /// <returns></returns>
        [HttpGet("getprojectlist")]
        public IActionResult GetProjectList(string projectid, int datetype = 4)
        {
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            string start = string.Empty;
            string end = string.Empty;
            GetStartEndTime(datetype, out start, out end);
            var result = _runningchartRepository.GetProjectList(projectid, start, end, userinfo);

            return Success("获取成功", result);
        }

        /// <summary>
        /// 项目-项目数量、维修人员、设备数量
        /// </summary>
        /// <param name="projectid"></param>
        /// <returns></returns>
        [HttpGet("getprojectrepairuserequipment")]
        public IActionResult GetProjectRepairUserEquipment(string projectid)
        {
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            var result = _runningchartRepository.GetProjectRepairUserEquipment(projectid, userinfo);

            return Success("获取成功", result);
        }

        /// <summary>
        /// 项目-新闻列表
        /// </summary>
        /// <param name="projectid"></param>
        /// <returns></returns>
        [HttpGet("getnewslist")]
        public async Task<IActionResult> GetNewsListAsync(string projectid)
        {
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string rolecode = User.Claims.FirstOrDefault(c => c.Type == "RoleCode").Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            #region 定时发布
            DateTime dtnow = DateTime.Now;
            var lists = (await _sys_newsRepository.Get(x => x.state == 1 && x.publishtype == 1 && x.timingtime <= dtnow)).ToList();
            if (!string.IsNullOrEmpty(projectid))
                lists = lists.Where(x => x.projectid == projectid).ToList();
            if (lists.Count > 0)
            {
                foreach (var item in lists)
                {
                    item.state = 0;
                    item.createtime = DateTime.Now.ToLocalTime();
                    await _sys_newsRepository.UpdateOne(item);
                }
            }
            #endregion

            var result = _runningchartRepository.GetNewsList(projectid, rolecode, userinfo);

            return Success("获取成功", result);
        }

        /// <summary>
        /// 巡检统计
        /// </summary>
        /// <param name="projectid"></param>
        /// <returns></returns>
        [HttpGet("getrunninglist")]
        public IActionResult GetRunningList(string projectid, int datetype = 4)
        {
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());
            string start = string.Empty;
            string end = string.Empty;
            GetStartEndTime(datetype, out start, out end);
            var result = _runningchartRepository.GetRunningList(projectid, start, end, userinfo);

            return Success("获取成功", result);
        }
        /// <summary>
        /// 维保统计
        /// </summary>
        /// <param name="projectid"></param>
        /// <returns></returns>
        [HttpGet("getmaintainlist")]
        public IActionResult GetMaintainList(string projectid, int datetype = 4)
        {
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());
            string start = string.Empty;
            string end = string.Empty;
            GetStartEndTime(datetype, out start, out end);
            var result = _runningchartRepository.GetMaintainList(projectid, start, end, userinfo);

            return Success("获取成功", result);
        }

        /// <summary>
        /// 维保事项
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpGet("getmaintainmsgs")]
        public IActionResult getmaintainmsgs(string projectid, int datetype = 2)
        {
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(nowusercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(nowusercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());
            string start = string.Empty;
            string end = string.Empty;
            GetStartEndTime(datetype, out start, out end);
            var result = _runningchartRepository.GetMaintainMatter(projectid, start, end, userinfo);
            return Success("获取成功", result);
        }

        /// <summary>
        /// 获取当天、本周、本月、本年、累计时间
        /// </summary>
        /// <param name="datetype"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        public void GetStartEndTime(int datetype, out string start, out string end)
        {
            start = string.Empty;
            end = string.Empty;

            var datenow = DateTime.Now;
            var datestart = datenow;
            var dateend = datenow;
            switch (datetype)
            {
                case 0://当天
                    break;
                case 1://本周
                    int n = (int)datenow.DayOfWeek == 0 ? 7 : (int)datenow.DayOfWeek;
                    datestart = datenow.AddDays(1 - n);//本周周一
                    dateend = datestart.AddDays(6);//本周周日
                    break;
                case 2://本月

                    datestart = datenow.AddDays(1 - datenow.Day);  //本月月初  
                    dateend = datestart.AddMonths(1).AddDays(-1);  //本月月末  
                    break;
                case 3://本年
                    datestart = new DateTime(datenow.Year, 1, 1);  //本年年初  
                    dateend = new DateTime(datenow.Year, 12, 31);  //本年年末  
                    break;
                case 4://全部
                    break;
                default:
                    break;
            }
            if (datetype != 4)
            {
                start = datestart.ToString("yyyy-MM-dd") + " 00:00:00";
                end = dateend.ToString("yyyy-MM-dd") + " 23:59:59";
            }
        }
    }
}