using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using EquipmentApi.IRepositories;
using MadRunFabric.Model;
using MadRunFabric.Common;
using MadRunFabric.Common.Enums;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MongoDB.Driver;

namespace EquipmentApi.Controllers.workordermanage
{
    /// <summary>
    /// 工单统计控制器
    /// </summary>
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class WoStatisticsController : BaseController
    {
        private readonly ILogger<WoStatisticsController> _logger;
        private readonly IWo_Repair_BaseRepository _wo_repair_baseRepository;
        private readonly IWo_Maintain_BaseRepository _wo_maintain_baseRepository;
        private readonly ISys_DictionaryValueRepository _sys_dictionaryValuerepository;
        private readonly IWo_Repair_EvaluateRepository _wo_repair_evaluateRepository;

        public WoStatisticsController(ILogger<WoStatisticsController> logger,
            IWo_Repair_BaseRepository wo_repair_baseRepository
            , IWo_Maintain_BaseRepository wo_maintain_baseRepository
            , ISys_DictionaryValueRepository sys_dictionaryValuerepository
            , IWo_Repair_EvaluateRepository wo_repair_evaluateRepository
            )
        {
            _logger = logger;
            _wo_repair_baseRepository = wo_repair_baseRepository;
            _wo_maintain_baseRepository = wo_maintain_baseRepository;
            _sys_dictionaryValuerepository = sys_dictionaryValuerepository;
            _wo_repair_evaluateRepository = wo_repair_evaluateRepository;
        }

        /// <summary>
        /// 根据角色不同获取总体统计
        /// </summary>
        /// <param name="roleid"></param>
        /// <returns></returns>
        //[Authorize]
        [HttpGet("test")]
        public IActionResult TestAsync(string rolecode, string daytype)
        {
            //var obj = _wo_repair_baseRepository.GetPipeLineAsync();
            //return Success("", obj);
            return Success("");
        }

        /// <summary>
        /// 根据角色不同获取总体统计
        /// </summary>
        /// <param name="roleid"></param>
        /// <returns></returns>
        //[Authorize]
        [HttpGet("getallcounts")]
        public async Task<IActionResult> AllCountsAsync(string rolecode, string daytype)
        {
            var flist = new List<FilterDefinition<Wo_Repair_Base>>();
            flist.Add(Builders<Wo_Repair_Base>.Filter.Eq("isdelete", false));
            #region 筛选
            if (!string.IsNullOrWhiteSpace(rolecode))
            {
            }

            if (!string.IsNullOrWhiteSpace(daytype))
            {
                var datenow = DateTime.Now;
                var datestart = DateTime.Now;
                var dateend = DateTime.Now;
                switch (daytype)
                {
                    case "week":
                        datestart = datenow.AddDays(1 - Convert.ToInt32(datenow.DayOfWeek.ToString("d")));//本周周一
                        dateend = datestart.AddDays(6);//本周周日
                        break;
                    case "month":
                        datestart = datenow.AddDays(1 - datenow.Day);  //本月月初  
                        dateend = datestart.AddMonths(1).AddDays(-1);  //本月月末  
                        break;
                    case "year":
                        datestart = new DateTime(datenow.Year, 1, 1);  //本年年初  
                        dateend = new DateTime(datenow.Year, 12, 31);  //本年年末  
                        break;
                    default:
                        break;
                }
                flist.Add(Builders<Wo_Repair_Base>.Filter.Gte("createtime", datestart.ToLocalTime()));
                flist.Add(Builders<Wo_Repair_Base>.Filter.Lte("createtime", dateend.ToLocalTime()));

                //fmlist.Add(Builders<Wo_Maintain_Base>.Filter.Eq("createtime", datestart.ToLocalTime()));
                //fmlist.Add(Builders<Wo_Maintain_Base>.Filter.Eq("createtime", dateend.ToLocalTime()));
            }
            #endregion
            var list = await _wo_repair_baseRepository.Get(Builders<Wo_Repair_Base>.Filter.And(flist));

            #region 工单来源统计
            var c1_P = list.Where(c => c.channel == (int)EnumWorkOrderChannel.pc).Count();
            var c2_A = list.Where(c => c.channel == (int)EnumWorkOrderChannel.android).Count();
            var c3_I = list.Where(c => c.channel == (int)EnumWorkOrderChannel.ios).Count();
            var c4_W = list.Where(c => c.channel == (int)EnumWorkOrderChannel.wechat).Count();
            #endregion
            #region 报修类型统计 日常类、设备类
            var diclist = await _sys_dictionaryValuerepository.Get(c => c.dictionarycode.Equals("XTMC"));
            List<object> llll = new List<object>(diclist.Count());
            foreach (var item in diclist)
            {
                var cccc = list.Where(c => c.systemid.Equals(item.id)).Count();
                if (cccc > 0)
                {
                    var fff = new
                    {
                        sysname = item.name,
                        count = cccc
                    };
                    llll.Add(fff);
                }
            }
            var cc = llll;
            #endregion
            #region 维修及时率统计
            #endregion
            #region 维修状态统计
            var c_dwx = list.Where(c => c.wostate < (int)EnumWorkOrderState.evaluate || c.wostate == (int)EnumWorkOrderState.hangup).Count();
            var c_ywx = list.Where(c => c.wostate == (int)EnumWorkOrderState.evaluate).Count();
            #endregion
            #region 工单满意度统计

            var elist = new List<FilterDefinition<Wo_Repair_Base>>();
            elist.Add(Builders<Wo_Repair_Base>.Filter.Eq("isdelete", 0));
            var mydcount = await _wo_repair_baseRepository.CountAsync(Builders<Wo_Repair_Base>.Filter.And(elist));
            elist.Add(Builders<Wo_Repair_Base>.Filter.Gte("score", 3));
            var mycount = await _wo_repair_baseRepository.CountAsync(Builders<Wo_Repair_Base>.Filter.And(elist));

            var myl = decimal.Parse(mycount.ToString()) / mydcount;
            var bmyl = 1 - myl;
            #endregion
            #region 耗材统计
            var hc_list = list.Where(c => c.wostate == (int)EnumWorkOrderState.deal || c.wostate == (int)EnumWorkOrderState.evaluate || c.wostate == (int)EnumWorkOrderState.hangup).ToList();
            var hc_count = 0;
            //foreach (var item in hc_list)
            //{
            //    hc_count += item.materialcount;
            //}
            //materialcount
            #endregion
            #region 设备状态统计
            #endregion
            #region 设备保养统计

            #endregion

            #region 结果
            var obj = new
            {
                T1 = new
                {
                    c_PC = c1_P,
                    c_Andron = c2_A,
                    c_IOS = c3_I,
                    c_wechat = c4_W,
                },
                T2 = cc,
                //states = stateStatistics
                T4 = new
                {
                    c_DWC = c_dwx,
                    c_YWC = c_ywx
                },
                T5 = new
                {
                    my = Decimal.Round(myl, 2),
                    bmy = Decimal.Round(bmyl, 2)
                },
                T6 = new
                {
                    hccount = hc_count
                }
            };
            #endregion
            return Success("成功", obj);
        }

        #region 报修统计详情
        [HttpGet("getrepairstatis")]
        public async Task<IActionResult> GetRepairStatis(string rolecode, string daytype,string sysname,int pageIndex=1, int pagesize=10)
        {
            var flist = new List<FilterDefinition<Wo_Repair_Base>>();
            flist.Add(Builders<Wo_Repair_Base>.Filter.Eq("isdelete", false));
            #region 筛选
            //权限
            if (!string.IsNullOrWhiteSpace(rolecode))
            {
            }
            //日期类型
            if (!string.IsNullOrWhiteSpace(daytype))
            {
                var datenow = DateTime.Now;
                var datestart = DateTime.Now;
                var dateend = DateTime.Now;
                switch (daytype)
                {
                    case "week":
                        datestart = datenow.AddDays(1 - Convert.ToInt32(datenow.DayOfWeek.ToString("d")));//本周周一
                        dateend = datestart.AddDays(6);//本周周日
                        break;
                    case "month":
                        datestart = datenow.AddDays(1 - datenow.Day);  //本月月初  
                        dateend = datestart.AddMonths(1).AddDays(-1);  //本月月末  
                        break;
                    case "year":
                        datestart = new DateTime(datenow.Year, 1, 1);  //本年年初  
                        dateend = new DateTime(datenow.Year, 12, 31);  //本年年末  
                        break;
                    default:
                        break;
                }
                flist.Add(Builders<Wo_Repair_Base>.Filter.Gte("createtime", datestart.ToLocalTime()));
                flist.Add(Builders<Wo_Repair_Base>.Filter.Lte("createtime", dateend.ToLocalTime()));
            }

            //系统类型
            flist.Add(Builders<Wo_Repair_Base>.Filter.Eq("sysname", sysname));

            //状态不为取消或挂起
            flist.Add(Builders<Wo_Repair_Base>.Filter.Where(c => c.wostate < (int)EnumWorkOrderState.cancle));
            #endregion
            var list = await _wo_repair_baseRepository.GetByPage(Builders<Wo_Repair_Base>.Filter.And(flist),pageIndex,pagesize);
            #region 获取各个系统下的数量
            var diclist = await _sys_dictionaryValuerepository.Get(c => c.dictionarycode.Equals("XTMC"));
            List<object> llll = new List<object>(diclist.Count());
            foreach (var item in diclist)
            {
                var cccc = list.Where(c => c.systemid.Equals(item.id)).Count();
                if (cccc > 0)
                {
                    var fff = new
                    {
                        itemid=item.id,
                        sysname = item.name,
                        count = cccc
                    };
                    llll.Add(fff);
                }
            }
            var cc = llll;
            #endregion
            //工单开始，已指派，已抢单 均为未完成
            flist.Add(Builders<Wo_Repair_Base>.Filter.Where(c => c.wostate < (int)EnumWorkOrderState.deal));
            var c_dwx = await _wo_repair_baseRepository.CountAsync(Builders<Wo_Repair_Base>.Filter.And(flist));
            //已处理和已评价的均为已完成
            var c_ywx = list.Where(c => c.wostate >= (int)EnumWorkOrderState.deal).Count();
            var newlist = list.Select(l => {
                return new
                {
                    id = l.id,
                    wocode = l.wocode,
                    repairreplace=l.repairreplace,
                    isover = l.wostate < (int)EnumWorkOrderState.deal ? false : true  //是否完成
                };
            });

            var obj = new {
                list=newlist,
                counts=cc,

            };
            return Success("");
        }
        #endregion

    }
}