using Siger.ApiDashboard.Tasks.Model;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Dapper;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Utility.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Siger.ApiDashboard.Tasks.Reports
{
    public class ModuleProdcutOfMachine
    {
        public ProductivityOfMachineResult GetProductivityOfMachine(siger_project_monthreport_config config, siger_project_monthreport_config_template template)
        {
            var result = new ProductivityOfMachineResult { title = template.title };
            try
            {


                var translate = new TranslateHelper(ReportDbHelper.Instance.ProjectLanguage(template.project_id) == 1);
                var now = DateTime.Parse(DateTime.Now.ToShortDateString() + " " + config.send_time);
                var machineIds = ReportDbHelper.Instance.GetMachineIds(template);

                var range = ReportDbHelper.Instance.TimeRange(config);
                var timeRange = range.StartTime + " - " + range.EndTime;
                var dictYied = GetMachineYied(template, config.company_id, config.project_id, range.StartTime, range.EndTime, machineIds);

                var echart = new MachineOfProductivity_EcharData
                {
                    markingline = template.val
                };
                foreach (var d in dictYied)
                {
                    echart.xdata.Add(d.Key);
                    echart.ydata.Add(d.Value);
                }
                result.echartData.Add(echart);
            }
            catch (Exception e)
            {
                Logger.WriteLineError(e.ToString());
            }
            return result;
        }

        private Dictionary<string, int> GetMachineYied(siger_project_monthreport_config_template template, int companyId, int projectId, DateTime sTime, DateTime eTime, IEnumerable<int> machineIds)
        {
            var yieldRepository = new ProductRepository(companyId, projectId);

            var dict = new Dictionary<string, int>();
            switch (template.axios)
            {
                case 1:// 按设备
                    {
                        var machineLocation = ReportDbHelper.Instance.GetMachineLocation(machineIds).ToList();
                        var yileds = yieldRepository.GetYileds(sTime.ToString(ParameterConstant.DateTimeFormat), eTime.ToString(ParameterConstant.DateTimeFormat), machineIds).ToList();
                        var dataGrp = yileds.GroupBy(g => g.machineID);
                        foreach (var y in dataGrp)
                        {
                            var machine = machineLocation.Find(f => f.machine_id == y.Key);
                            if (machine == null)
                                continue;
                            dict.Add($"{machine.section_id}{ machine.machine_name}", y.ToList().Sum(f => f.yield));
                        }
                        break;
                    }
                case 2:// 按天
                    {
                        var yileds = yieldRepository.GetYileds(sTime.ToString(ParameterConstant.DateTimeFormat), eTime.ToString(ParameterConstant.DateTimeFormat), machineIds).ToList();
                        var dataGrp = yileds.GroupBy(g => g.dataTime.Date);
                        foreach (var y in dataGrp)
                        {
                            dict.Add(y.Key.Date.ToShortDateString(), y.ToList().Sum(f => f.yield));
                        }
                        break;
                    }
                case 3:// 按周
                    {
                        var patchId = 1;
                        var interal = DateTimeHelper.GetInteral(patchId);
                        var dates = DateTimeHelper.GetDateTimes(sTime, eTime, patchId);
                        foreach (var date in dates)
                        {
                            DateTime start;
                            DateTime end;
                            string dateTime;
                            if (patchId == 0 || patchId == 1)
                            {
                                start = date;
                                end = date.AddDays(interal).AddSeconds(-1) > DateTime.Now
                                    ? DateTime.Now
                                    : date.AddDays(interal).AddSeconds(-1);
                                dateTime = end.ToString(ParameterConstant.DateFormat);
                            }
                            else
                            {
                                start = date.AddDays(1 - date.Day);
                                end = date.AddDays(1 - date.Day).Date.AddMonths(1).AddSeconds(-1) > DateTime.Now
                                    ? DateTime.Now
                                    : date.AddDays(1 - date.Day).Date.AddMonths(1).AddSeconds(-1); //到月底
                                dateTime = end.ToString(ParameterConstant.YearMonthFormat);
                            }

                            var yileds = yieldRepository.GetYileds(start.ToString(ParameterConstant.DateTimeFormat), end.ToString(ParameterConstant.DateTimeFormat), machineIds).ToList();
                            dict.Add(dateTime, yileds.Sum(s => s.yield));
                        }
                        break;
                    }
                case 4:// 自定义分组
                    {
                        var groups = template.param.Split(',').Select(t => t.ToInt()).Distinct();
                        foreach (var g in groups)
                        {
                            var group = ReportDbHelper.Instance.ConfigDbContext.siger_project_dashboard_machine_group.FirstOrDefault(f => f.id == g);
                            //var machines = group.machineid.Split(',').Select(m => m.ToInt());
                            var machines = ReportDbHelper.Instance.GetMachineIdsByGroup(template.project_id, group.machineid);
                            var yileds = yieldRepository.GetYileds(sTime.ToString(ParameterConstant.DateTimeFormat), eTime.ToString(ParameterConstant.DateTimeFormat), machines).ToList();
                            dict.Add(group.group, yileds.Sum(s => s.yield));
                        }
                        break;
                    }
            }
            return dict;
        }

    }
}
