using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.TpmRepository.Repositories.Interface;
using Siger.Middlelayer.TpmRepository.Response;
using Siger.Middlelayer.Utility.Helpers;

namespace Siger.ApiDashboard.Controllers
{
    public class DashboardRepairController : BaseController
    {
        private readonly ISigerProjectMachineRepository _machineRepository;
        private readonly ISigerProjectUserRepository _projectUserRepository;
        private readonly IRepairRepository _repairRepository;
        private readonly IPlanRepository _planRepository;
        private readonly ISparepartRepository _sparepartRepository;
        private readonly ISparepartTypeRepository _sparepartTypeRepository;
        private readonly ISigerAndonExpectionTypeRepository _andonExpectionTypeRepository;
        private readonly ISigerProjectUserGroupRepository _projectUserGroupRepository;
        private readonly ISigerProjectSparepartOrderDetail _sparepartOrderDetail;
        private readonly IPlanSignRepository _planSignRepository;

        /// <inheritdoc />
        public DashboardRepairController(ISigerProjectMachineRepository machineRepository, ISigerProjectUserRepository projectUserRepository,
            IRepairRepository repairRepository,
            IPlanRepository planRepository, ISparepartRepository sparepartRepository, ISigerProjectSparepartOrderDetail sparepartOrderDetail,
            IPlanSignRepository planSignRepository, ISparepartTypeRepository sparepartTypeRepository, ISigerAndonExpectionTypeRepository andonExpectionTypeRepository,
            ISigerProjectUserGroupRepository projectUserGroupRepository)
        {
            _machineRepository = machineRepository;
            _projectUserRepository = projectUserRepository;
            _repairRepository = repairRepository;
            _planRepository = planRepository;
            _sparepartRepository = sparepartRepository;
            _sparepartOrderDetail = sparepartOrderDetail;
            _planSignRepository = planSignRepository;
            _sparepartTypeRepository = sparepartTypeRepository;
            _andonExpectionTypeRepository = andonExpectionTypeRepository;
            _projectUserGroupRepository = projectUserGroupRepository;
        }

        /// <summary>
        /// 获取维修班组状态
        /// </summary>
        /// <param name="usergroup"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetUserStateList(string usergroup)
        {
            var responses = new List<ResponseGetUserStateList>();
            var users = _projectUserRepository.GetProjectUserList(0, (int)SectionType.Maintenance, ProjectId).ToList();
            //department condition
            //var usergroups = GetDepartment(usergroup);
            //if (usergroups.Any())
            //{
            //    users = users.Where(f => usergroups.Contains(f.usergroupid)).ToList();
            //}
            //if (!users.Any())
            //{
            //    return new ObjectResult(responses);
            //}

            var start = UnixTimeHelper.ConvertDataTimeLong(DateTime.Now.Date);
            var end = start + 86400;
            foreach (var user in users)
            {
                var response = new ResponseGetUserStateList
                {
                    user_name = user.realname,
                    mobile = user.mobile
                };

                //班次
                //var cal = _calendarRepository.Get(q => q.user_mid == user.id && q.date.Date == DateTime.Now.Date && q.status == (int)RowState.Valid);
                //if (cal != null)
                //{
                //    var shift = _projectShiftRepository.Get(q => q.id == cal.shift_id && q.projectid == ProjectId && q.status == (int)RowState.Valid);
                //    response.shift_name = shift != null ? shift.title : "";
                //}

                //维修设备
                var repair = _repairRepository.Get(q =>  q.signmid == user.id && (q.status == (int)MachineRepairStatus.WaitingForRepair || q.status == (int)MachineRepairStatus.WaitingForRenew) && q.projectid == ProjectId);
                if (repair != null)
                {
                    var machintTitle = _machineRepository.GetLineLevelTitlebByMachine(repair.machineid, ProjectId);
                    response.status = machintTitle + "维修中";
                }
                else //维护工单
                {
                    var plan = _planSignRepository.GetList(q => q.create_mid == user.id && q.projectid == ProjectId && q.status == (int)RowState.Valid
                                                                 && q.create_time >= start && q.create_time < end).FirstOrDefault();
                    if (plan != null)
                    {
                        //var machine = _machineRepository.Get(q =>
                        //    q.id == plan.machine_id && q.status == (int)RowState.Valid && q.projectid == ProjectId);
                        //response.status = machine != null ? machine.title + "维护中" : "";
                        var machintTitle = _machineRepository.GetLineLevelTitlebByMachine(plan.machine_id, ProjectId);
                        response.status = machintTitle + "维护中";
                    }
                    else
                    {
                        response.status = "在岗";
                    }
                }

                responses.Add(response);
            }

            return new ObjectResult(responses);
        }

        /// <summary>
        /// 设备故障分析
        /// </summary>
        /// <param name="usergroup"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMachineRepairSummary(string usergroup)
        {
            var monthStart = UnixTimeHelper.GetUnixByDate(DateTime.Now.ToString(ParameterConstant.MouthFirstDay));
            var monthEnd = UnixTimeHelper.GetUnixByDate(DateTime.Now.AddMonths(1).ToString(ParameterConstant.MouthFirstDay));

            var todayStart = UnixTimeHelper.GetUnixByDate(DateTime.Now.ToString(ParameterConstant.DateFormat));
            var todayEnd = UnixTimeHelper.GetUnixByDate(DateTime.Now.ToString(ParameterConstant.DateTimeFormat));

            var responses = new ResponseGetMachineRepairList();
            var machines = _machineRepository.GetList(q => q.projectid == ProjectId && q.status == (int)RowState.Valid).ToList();
            if (machines.Count == 0)
            {
                return new ObjectResult(responses);
            }
            var repairs = _repairRepository.GetAllRepairs(ProjectId, monthStart, monthEnd);
            //department condition
            //var usergroups = GetDepartment(usergroup);
            //if (usergroups.Any())
            //{
            //    var expections = _andonExpectionTypeRepository.GetList(f => f.projectid == ProjectId && f.status != 0
            //    && (usergroups.Contains(f.usergroup) || usergroups.Contains(f.second_usergroup))).Select(s => s.id).ToList();
            //    repairs = repairs.Where(f => expections.Contains(f.expection_id)).ToList();
            //}
            if (repairs.Any())
            {
                responses.total = repairs.Count();
                var typenames = repairs.Select(m => m.type_name).Distinct().Take(6).ToList();
                foreach (var typename in typenames)
                {
                    var typelist = repairs.Where(q => q.type_name == typename);
                    var response = new ResponseMachineRepair
                    {
                        type_nme = typename,
                        percent = Math.Round((double)typelist.Count() * 100 / repairs.Count(), 1),
                        count= typelist.Count()
                    };
                    responses.repairs.Add(response);
                }

                var todaycounts = repairs.Where(q => q.create_time >= todayStart && q.create_time <= todayEnd).ToList();
                responses.today_percent = todaycounts.Count.ToString("000");
                responses.month_percent = repairs.Count().ToString("000");
            }

            return new ObjectResult(responses);
        }

        /// <summary>
        /// 维修工单列表
        /// </summary>
        /// <param name="usergroup"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetRepairList(string usergroup)
        {
            //var repairs = _repairRepository.GetRepairs(ProjectId).Take(50).ToList();
            //department condition
            //var usergroups = GetDepartment(usergroup);
            //if (usergroups.Any())
            //{
            //    var expections = _andonExpectionTypeRepository.GetList(f => f.projectid == ProjectId && f.status != 0
            //    && (usergroups.Contains(f.usergroup) || usergroups.Contains(f.second_usergroup))).Select(s => s.id).ToList();
            //    repairs = repairs.Where(f => expections.Contains(f.expection)).ToList();
            //}

            var repairs = _repairRepository.GetRepairs(ProjectId);

            //foreach (var item in repairs)
            //{
            //    item.faultcontent = "    ";
            //    if (item.expection != 0)
            //    {
            //        var expection = _andonExpectionTypeRepository.GetExpectionParent(item.expection, ProjectId).FirstOrDefault(f => f.level == 2)?.name ?? "    ";
            //        item.faultcontent = expection;
            //    }
            //}
            return new ObjectResult(repairs);
        }

        /// <summary>
        /// 获取维护项目
        /// </summary>
        /// <param name="usergroup"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetPlanList(string usergroup)
        {
            var todayStart = UnixTimeHelper.GetUnixByDate(DateTime.Now.ToString(ParameterConstant.DateFormat));
            var todayEnd = UnixTimeHelper.GetUnixByDate(DateTime.Now.Date.AddDays(1).AddMilliseconds(-1).ToString(ParameterConstant.DateTimeFormat));
            var plans = _planRepository.GetAllPlans(ProjectId, todayStart, todayEnd);
           
            return new ObjectResult(plans);
        }

        /// <summary>
        /// 获取备件
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetSparepares()
        {
            var response = new ResponseGetSparepare();

            var sps = _sparepartRepository.GetList(q => q.projectid == ProjectId && q.status == (int)RowState.Valid && q.sku < q.mini_sku)
                .OrderBy(q => q.sku).Take(20).ToList();

            foreach (var sp in sps)
            {
                response.sparepareSkus.Add(new SparepareSku
                {
                    name = sp.title,
                    current_sku = sp.sku,
                    safe_sku = sp.mini_sku,
                    purchase_sku = _sparepartOrderDetail.GetList(q =>
                        q.sparepart_code == sp.code && q.status == (int)OrderStatus.Purchasing &&
                        q.projectid == ProjectId).Sum(q => q.count)
                });
            }

            var repairs = _repairRepository.GetList(q => q.projectid == ProjectId && q.status > (int)MachineRepairStatus.WaitingForOrders &&
                                                         q.status < (int)MachineRepairStatus.Deleted && q.sparepartid != "");
            if (repairs.Any())
            {
                var dics = new Dictionary<int, int>();
                foreach (var repair in repairs.ToList())
                {
                    var spars = repair.sparepartid.Split(',');
                    foreach (var spar in spars)
                    {
                        var spsp = spar.Split('*');
                        if (spsp.Length == 2)
                        {
                            var id = spsp[0].ToInt();
                            var value = spsp[1].ToInt();
                            if (dics.ContainsKey(id))
                            {
                                dics[id] += value;
                            }
                            else
                            {
                                dics.Add(id, value);
                            }
                        }
                    }
                }

                if (dics.Any())
                {
                    var list = dics.OrderByDescending(q => q.Value).Take(5);
                    foreach (var pair in list.OrderBy(q => q.Value))
                    {
                        var sp = _sparepartRepository.Get(q => q.id == pair.Key && q.projectid == ProjectId && q.status == (int)RowState.Valid);
                        if (sp != null)
                        {
                            response.sparepareUses.Add(new SparepareUse
                            {
                                count = pair.Value,
                                name = sp.title,
                            });
                        }
                    }
                }
            }

            return new ObjectResult(response);
        }

        /// <summary>
        /// 平均修复时间
        /// </summary>
        /// <param name="usergroup"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMttr(string usergroup)
        {
            var startDate = DateTime.Now.AddDays(-14);
            var monthStart = UnixTimeHelper.GetUnixByDate(startDate.ToString(ParameterConstant.DateFormat));
            var monthEnd = UnixTimeHelper.GetUnixByDate(DateTime.Now.ToString(ParameterConstant.DateTimeFormat));

            var responses = new List<ResponseRepairTime>();

            var repairs = _repairRepository.GetAllFinishedRepairs(ProjectId, monthStart, monthEnd);
            //var usergroups = GetDepartment(usergroup);
            //if (usergroups.Any())
            //{
            //    var expections = _andonExpectionTypeRepository.GetList(f => f.projectid == ProjectId && f.status != 0
            //    && (usergroups.Contains(f.usergroup) || usergroups.Contains(f.second_usergroup))).Select(s => s.id).ToList();
            //    repairs = repairs.Where(f => expections.Contains(f.expection_id)).ToList();
            //}
            var dates = DateTimeHelper.GetDateTimes(startDate, DateTime.Now.Date.AddDays(1).AddSeconds(-1), 0);
            for (var i = 0; i < dates.Count; i++)
            {
                var start = UnixTimeHelper.ConvertDataTimeLong(dates[i].Date);
                var end = UnixTimeHelper.ConvertDataTimeLong(dates[i].Date.AddDays(1).AddSeconds(-1));

                double avgtime = 0;
                var dayrepairs = repairs.Where(q => q.create_time >= start && q.create_time <= end);
                if (dayrepairs.Any())
                {
                    avgtime = dayrepairs.Sum(q => q.repirtime) / dayrepairs.Count();
                }

                var response = new ResponseRepairTime
                {
                    date = dates[i].ToString("MM/dd"),
                    repair_time = Math.Round(avgtime / 60, 0)
                };

                responses.Add(response);
            }

            return new ObjectResult(responses);
        }

        /// <summary>
        /// 获取sectionids(1全部2TS3非TS)
        /// </summary>
        /// <param name="department"></param>
        /// <returns></returns>
        //private List<int> GetDepartment(string department)
        //{
        //    var ret = new List<int>();
        //    if (string.IsNullOrEmpty(department) || department == "1")
        //    {
        //        return _projectUserGroupRepository.GetList(f => f.status != 0 && f.projectid == ProjectId).Select(s => s.id).ToList();
        //    }
        //    if (department == "2")
        //    {
        //        return _projectUserGroupRepository.GetList(f => f.title.Contains("技术") && f.status != 0 && f.projectid == ProjectId).Select(s => s.id).ToList();
        //    }
        //    if (department == "3")
        //    {
        //        return _projectUserGroupRepository.GetList(f => !f.title.Contains("技术") && f.status != 0 && f.projectid == ProjectId).Select(s => s.id).ToList();
        //    }
        //    return ret;
        //}
    }
}