using System;
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.Dapper.Utilities.Oee;
using Siger.Middlelayer.Dapper.Utilities.Slice;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Share.Models;
using Siger.Middlelayer.Utility.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Siger.ApiDashboard.Tasks.Reports
{
    public class ModuleCrop
    {
        public CropResult GetCropResult(siger_project_monthreport_config config, siger_project_monthreport_config_template template)
        {
            var result = new CropResult
            {
                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).ToList();
                //统计周期
                var range = ReportDbHelper.Instance.TimeRange(config);
                var timeRange = range.StartTime + " - " + range.EndTime;
                var croResult = GetMachineCropData(template, range.StartTime, range.EndTime, machineIds, config.company_id, config.project_id);

                var echartData = new Crop_EcharData
                {
                    markingline = template.val
                };
                foreach (var r in croResult)
                {

                    echartData.xdata.Add(r.Key);
                    echartData.ydata.Add(r.Value);
                    var diffval = Math.Round(r.Value - template.val, 2);

                    result.tableData.Add(new Crop_tableData
                    {
                        datetime = r.Key,
                        hour1 = r.Value,
                        hour2 = diffval
                    });
                }
                result.echartData.Add(echartData);
            }
            catch (Exception e)
            {
                Logger.WriteLineError(e.ToString());
            }
            return result;
        }

        private Dictionary<string, double> GetMachineCropData(siger_project_monthreport_config_template template, DateTime beginDate, DateTime endDate, List<int> machineIds, int companyId, int projectId)
        {
            var responses = new List<MachineCanvasDataInfo>();

            var repository = new ProductRepository(companyId, projectId);
            var sliceRepositoey = new SliceSateRepository(companyId, projectId);
            var dic = new Dictionary<string, double>();
            var key = string.Empty;
            var val = 0d;
            switch (template.axios)
            {
                case 1:// 按设备
                    {
                        var machineLocation = ReportDbHelper.Instance.GetMachineLocation(machineIds).ToList();
                        foreach (var m in machineLocation)
                        {

                            var sliceSates = sliceRepositoey.GetCncSliceSates(new List<int> { m.machine_id }, beginDate.ToString(ParameterConstant.DateTimeFormat), endDate.ToString(ParameterConstant.DateTimeFormat));
                            //稼动率
                            if (sliceSates.Any())
                            {
                                var times = ReportDbHelper.Instance.GetRestTimesByMachine(new List<int> { m.machine_id }, projectId);
                                var oee = OeeManager.GetOeeByTime(beginDate, endDate, sliceSates, new List<int> { m.machine_id }, null, times);
                                val = Math.Round(oee.OEE1, 2);
                            }
                            dic.Add($"{m.section_id}{ m.machine_name}", val);
                        }
                        break;
                    }
                case 2: //按天
                    {
                        var patchId = 0;
                        var interal = DateTimeHelper.GetInteral(patchId);
                        var dates = DateTimeHelper.GetDateTimes(beginDate, endDate, 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 sliceSates = sliceRepositoey.GetCncSliceSates(machineIds, start.ToString(ParameterConstant.DateTimeFormat), end.ToString(ParameterConstant.DateTimeFormat));
                            //稼动率
                            if (sliceSates.Any())
                            {
                                var times = ReportDbHelper.Instance.GetRestTimesByMachine(machineIds, projectId);
                                var oee = OeeManager.GetOeeByTime(start, end, sliceSates, machineIds, null, times);
                                val = Math.Round(oee.OEE1, 2);
                            }
                            dic.Add(dateTime, val);
                        }

                        break;
                    }
                case 3: //按周
                    {
                        var patchId = 1;
                        var interal = DateTimeHelper.GetInteral(patchId);
                        var dates = DateTimeHelper.GetDateTimes(beginDate, endDate, 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 sliceSates = sliceRepositoey.GetCncSliceSates(machineIds, start.ToString(ParameterConstant.DateTimeFormat), end.ToString(ParameterConstant.DateTimeFormat));
                            //稼动率
                            if (sliceSates.Any())
                            {
                                var times = ReportDbHelper.Instance.GetRestTimesByMachine(machineIds, projectId);
                                var oee = OeeManager.GetOeeByTime(start, end, sliceSates, machineIds, null, times);
                                val = Math.Round(oee.OEE1, 2);
                            }
                            dic.Add(dateTime, val);
                        }
                        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 setp = SliceManager.GetMachineSlice(beginDate, endDate, machines, companyId, projectId, group != null ? group.group : g.ToStr()).Result;

                            var sliceSates = sliceRepositoey.GetCncSliceSates(machines, beginDate.ToString(ParameterConstant.DateTimeFormat), endDate.ToString(ParameterConstant.DateTimeFormat));
                            //稼动率
                            if (sliceSates.Any())
                            {
                                var times = ReportDbHelper.Instance.GetRestTimesByMachine(machines, projectId);
                                var oee = OeeManager.GetOeeByTime(beginDate, endDate, sliceSates, machines, null, times);
                                val = Math.Round(oee.OEE1, 2);
                            }
                            dic.Add(group.group, val);
                        }
                        break;
                    }

            }
            return dic;
        }
    }
}
