using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Siger.ApiCommon.Result;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.DashboardRepository.Entities;
using Siger.Middlelayer.DashboardRepository.Repositories.Interface;
using Siger.Middlelayer.DashboardRepository.Request;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Utility.Helpers;

namespace Siger.ApiDashboard.Controllers
{
    public class SaaSMonitorController : BaseController
    {

        private readonly IUnitOfWork _unitOfWork;
        private readonly ISaasMonitorRepository _saasMonitor;
        public SaaSMonitorController(IUnitOfWork unitOfWork, ISaasMonitorRepository saasMonitor)
        {
            _unitOfWork = unitOfWork;
            _saasMonitor = saasMonitor;
        }
        /// <summary>
        /// 配置页面 增
        /// </summary>
        /// <param name="ret"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Add([FromBody] RequestAddress ret)
        {
            if (ret != null)
            {
                var result = new siger_tr_saas_monitor()
                {
                    customer_name = ret.customer_name,
                    machine_quantity = ret.machine_quantity,
                    quantity = ret.quantity,
                    province = ret.province,
                    city = ret.city,
                    area = ret.area,
                    address = ret.address,
                    longitude = ret.longitude,
                    latitude = ret.latitude,
                    signing_time = DateTime.TryParse(ret.signing_time, out var signing_time) ? signing_time : default,
                    ProjectId = ProjectId
                };
                _saasMonitor.Insert(result);
                if (_unitOfWork.Commit() > 0)
                {
                    return new ObjectResult(CommonEnum.Succefull);
                }
                throw new BadRequestException(CommonEnum.Fail);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 配置页面 删
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Delete(int id)
        {
            var saas = _saasMonitor.Get(q => q.id >= id && q.ProjectId == ProjectId && q.status == (int)RowState.Valid);
            if (saas != null)
            {
                saas.status = (int)RowState.Invalid;
                _saasMonitor.Update(saas);
            }
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 配置页面 改
        /// </summary>
        /// <param name="ret"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Update([FromBody] RequestUpdate ret)
        {
            if (ret != null)
            {
                var saas = _saasMonitor.Get(q => q.id >= ret.id && q.ProjectId == ProjectId && q.status == (int)RowState.Valid);
                if (saas != null)
                {
                    saas.customer_name = ret.customer_name;
                    saas.machine_quantity = ret.machine_quantity;
                    saas.quantity = ret.quantity;
                    saas.province = ret.province;
                    saas.city = ret.city;
                    saas.area = ret.area;
                    saas.address = ret.address;
                    saas.longitude = ret.longitude;
                    saas.latitude = ret.latitude;
                    saas.signing_time = DateTime.TryParse(ret.signing_time, out var signing_time) ? signing_time : default;
                    _saasMonitor.Update(saas);
                }
                if (_unitOfWork.Commit() > 0)
                {
                    return new ObjectResult(CommonEnum.Succefull);
                }
                throw new BadRequestException(CommonEnum.Fail);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 配置页面 查
        /// </summary>
        /// <param name="ret"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Select([FromBody] RequestSelect ret)
        {
            var result = _saasMonitor.GetPagedSaaS(ret, ProjectId);
            return new PagedObjectResult(result.Data, result.Total, ret.page, ret.pagesize);
        }
        /// <summary>
        /// 获取每月客户数量
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetCustomerCountByMonth()
        {
            var list = new List<RequestCustomerCountByMonth>();
            var firstDay = new DateTime(DateTime.Now.Year, 1, 1);
            var lastDay = new DateTime(DateTime.Now.Year, 12, 31);
            var query = _saasMonitor.GetList(q => q.signing_time >= firstDay && q.signing_time <= lastDay && q.ProjectId == ProjectId && q.status == (int)RowState.Valid).ToList();
            if (query.Any())
            {
                for (int i = 1; i <= 12; i++)
                {
                    var count = 0;
                    foreach (var item in query)
                    {
                        if (i.ToString().Equals(item.signing_time.Month.ToString()))
                        {
                            count++;
                        }
                    }
                    var saas = new RequestCustomerCountByMonth()
                    {
                        quantity = count,
                        month = i
                    };
                    list.Add(saas);
                }
            }
            return new ObjectResult(list);
        }

        /// <summary>
        /// 获取每月设备数量
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMachineCountByMonth()
        {
            var list = new List<RequestCustomerCountByMonth>();
            var firstDay = new DateTime(DateTime.Now.Year, 1, 1);
            var lastDay = new DateTime(DateTime.Now.Year, 12, 31);
            var query = _saasMonitor.GetList(q => q.signing_time >= firstDay && q.signing_time <= lastDay && q.ProjectId == ProjectId && q.status == (int)RowState.Valid).ToList();
            if (query.Any())
            {
                for (int i = 1; i <= 12; i++)
                {
                    var count = 0;
                    foreach (var item in query)
                    {
                        if (i.ToString().Equals(item.signing_time.Month.ToString()))
                        {
                            count += item.machine_quantity;
                        }
                    }
                    var saas = new RequestCustomerCountByMonth()
                    {
                        quantity = count,
                        month = i
                    };
                    list.Add(saas);
                }
            }
            return new ObjectResult(list);
        }

        /// <summary>
        /// 获取当月客户签约情况
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMachineCustomerSituation()
        {
            var list = new List<RequestCustomerSituation>();
            var firstDay = new DateTime(DateTime.Now.Year, 1, 1);
            var lastDay = new DateTime(DateTime.Now.Year, 12, 31);
            var query = _saasMonitor.GetList(q => q.signing_time >= firstDay && q.signing_time <= lastDay && q.ProjectId == ProjectId && q.status == (int)RowState.Valid).ToList();
            if (query.Any())
            {
                foreach (var item in query)
                {
                    if (DateTime.Now.Month.ToString().Equals(item.signing_time.Month.ToString()))
                    {
                        var saas = new RequestCustomerSituation()
                        {
                            customer_name = item.customer_name,
                            address = item.address,
                            quantity = item.machine_quantity,
                            province=item.province,
                            city=item.city,
                            area=item.area
                        };
                        list.Add(saas);
                    }
                }
            }
            return new ObjectResult(list);
        }

        /// <summary>
        /// 获取客户分布
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetCustomerAddress()
        {
            var list = new List<RequestCustomerAddress>();
            var provinceList = _saasMonitor.GetList(q => q.ProjectId == ProjectId && q.status == (int)RowState.Valid).Select(q => q.province).Distinct().ToList();
            var query = _saasMonitor.GetList(q => q.ProjectId == ProjectId && q.status == (int)RowState.Valid).ToList();
            foreach (var i in provinceList)
            {
                var count = 0;
                foreach (var item in query)
                {
                    if (i.ToString().Equals(item.province))
                    {
                        count++;
                    }
                }
                var saas = new RequestCustomerAddress()
                {
                    quantity = count,
                    province = i
                };
                list.Add(saas);
            }
            var lists = list.OrderBy(q => q.quantity);
            return new ObjectResult(lists);
        }


        /// <summary>
        /// 获取设备分布
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMachineAddress()
        {
            var list = new List<RequestCustomerAddress>();
            var provinceList = _saasMonitor.GetList(q => q.ProjectId == ProjectId && q.status == (int)RowState.Valid).Select(q => q.province).Distinct().ToList();
            var query = _saasMonitor.GetList(q => q.ProjectId == ProjectId && q.status == (int)RowState.Valid).ToList();
            foreach (var i in provinceList)
            {
                var count = 0;
                foreach (var item in query)
                {
                    if (i.ToString().Equals(item.province))
                    {
                        count += item.machine_quantity;
                    }
                }
                var saas = new RequestCustomerAddress()
                {
                    quantity = count,
                    province = i
                };
                list.Add(saas);
            }
            var lists = list.OrderBy(q=>q.quantity);
            return new ObjectResult(lists);
        }

        /// <summary>
        /// 获取经纬度坐标
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetCoordinate()
        {
            var list = new List<RequestCoordinate>();
            var cityList = _saasMonitor.GetList(q => q.ProjectId == ProjectId && q.status == (int)RowState.Valid).Select(q => q.city).Distinct().ToList();
            foreach (var i in cityList)
            {
                var query = _saasMonitor.GetList(q => q.ProjectId == ProjectId && q.status == (int)RowState.Valid && q.city==i).FirstOrDefault();
                var saas = new RequestCoordinate()
                {
                    city = i,
                    latitude = query.latitude,
                    longitude=query.longitude
                };
                list.Add(saas);
            }
            return new ObjectResult(list);
        }

        [HttpGet]
        public IActionResult GetAllNumber()
        {
            var saas = new RequestAllNum();
            var firstDay = new DateTime(DateTime.Now.Year, 1, 1);
            var lastDay = new DateTime(DateTime.Now.Year, 12, 31);
            var query = _saasMonitor.GetList(q => q.signing_time >= firstDay && q.signing_time <= lastDay && q.ProjectId == ProjectId && q.status == (int)RowState.Valid).ToList();
            if (query.Any())
            {
                var machine_count = 0;
                var customer_count = 0;
                var user_count = 0;
                foreach (var item in query)
                {
                    machine_count += item.machine_quantity;
                    customer_count++;
                    user_count += item.quantity;
                }
                saas.customer_quantity= customer_count;
                saas.machine_quantity = machine_count;
                saas.user_quantity = user_count;
            }
            return new ObjectResult(saas);
        }
    }
}
