using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Dapper;
using Siger.Middlelayer.DashboardRepository.Repositories.Interface;
using Siger.Middlelayer.DashboardRepository.Response;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Share.Enum.ModuleEnum;
using Siger.ApiCommon.Filters;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.KpiRespository.Repositories.Interface;
using Siger.Middlelayer.TpmRepository.Repositories.Interface;
using Siger.Middlelayer.Utility.Helpers;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.ApiDashboard.Utilities;

namespace Siger.ApiDashboard.Controllers
{
    public class DashboardFactoryController : BaseController
    {
        private readonly IDashboardLevelRepository _dashboardLevelRepository;
        private readonly ISigerProjectProductRepository _productRepository;
        private readonly ISigerProjectLevelSectionRepository _sigerProjectLevelSection;
        private readonly IDashboardFactoryChanel _dashboardFactoryChanel;
        private readonly ISigerKpiTasklist _kpiTasklist;
        private readonly ISigerProjectUserRepository _sigerProjectUser;
        private readonly IDashboardTotalSetRepository _totalSetRepository;
        private readonly OeeHelper _oeeHelper;

        public DashboardFactoryController(IDashboardLevelRepository dashboardLevel, IProductRouteRepository _ProductRoute, ISigerProjectProductRepository sigerProjectProduct,
            ISigerProjectLevelSectionRepository sigerProjectLevelSection, IDashboardFactoryChanel factoryChanel, ISigerKpiTasklist kpiTasklist, ISigerProjectUserRepository sigerProjectUser,
            ISigerAndonStationConfigRepository sigerAndonStationConfig, IDashboardTotalSetRepository totalSetRepository, OeeHelper oeeHelper)
        {
            _dashboardLevelRepository = dashboardLevel;
            _productRepository = sigerProjectProduct;
            _sigerProjectLevelSection = sigerProjectLevelSection;
            _dashboardFactoryChanel = factoryChanel;
            _kpiTasklist = kpiTasklist;
            _sigerProjectUser = sigerProjectUser;
            _totalSetRepository = totalSetRepository;
            _oeeHelper = oeeHelper;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="section"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetFactoryOee(int section, string date)
        {
            var result = new List<ResponseChanelOee>();
            return new ObjectResult(2);
        }

        /// <summary>
        ///  各产线 /通道 标准达成率
        /// </summary>
        /// <param name="section">0 :所有产线</param>
        /// <param name="date"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetFactoryAchievement(int section, string date)
        {
            var oeeList = new List<ResponseOee>();
            var result = new ResponseFactoryChanelProduce();

            var projectId = ProjectId;
            var dateRange = DateTimeHelper.GetDateTimeRange(date.ToString());
            var dtStart = dateRange.StarTime;
            var dtEnd = dateRange.EndTime;

            var users = _sigerProjectUser.GetList(f => f.projectid == ProjectId && f.status == (int)RowState.Valid);
            var yieldRepository = new LocationYieldRepository(CompanyId, projectId);

            var bottleMachines = _dashboardLevelRepository.GetBottleSection(ProjectId).ToList();
            if (!bottleMachines.Any())
                throw new BadRequestException(CommonEnum.RecordNotFound);

            var oees = new double[] { 92.55, 75.98, 88.55, 79.43, 82.45 };
            var lightNums = new double[] { 205, 174, 199, 188, 194 };
            var grayNums = new double[] { 215, 215, 216, 245, 246 };
            var i = 0;
            foreach (var bottle in bottleMachines.Take(5))
            {
                //var yields = yieldRepository.GetLocationYields(bottle.MachineId, dtStart.ToString(UnixTimeHelper.DateTimeFormat), dtEnd.ToString(UnixTimeHelper.DateTimeFormat));
                //var curOee = 0d;
                //var actCountTTl = yields.Sum(s => s.yield);

                //var targetCountTTl = 0d;
                //DateTime dtDay;
                //for (dtDay = dtStart; dtDay.CompareTo(dtEnd) < 0; dtDay = dtDay.AddHours(1))
                //{
                //    var stepStarTime = dtDay;
                //    var stepEndTime = dtDay.AddHours(1).AddSeconds(-1);
                //    var targetVal = _dashboardLevelRepository.BottleProductTarget(ProjectId, bottle.MachineId, stepStarTime, stepEndTime);
                //    if (targetVal == null)
                //        continue;
                //    targetCountTTl += targetVal.Val;
                //}

                //if (targetCountTTl > 0)
                //{
                //    var _cuOee = actCountTTl / targetCountTTl;
                //    curOee = Math.Round(_cuOee, 4);
                //    curOee = Math.Round(curOee * 100, 2);
                //}
                result.produces.Add(new ResponseChanelProduce
                {
                    name = bottle.ParentTitle,
                    lightNum = lightNums[i],
                    grayNum = grayNums[i]
                });

                //var oeeModel = _oeeHelper.GetOee(UnixTimeHelper.ConvertDataTimeLong(dtStart), UnixTimeHelper.ConvertDataTimeLong(dtEnd), bottle.ParentId, ProjectId, CompanyId,yields,bottle.MachineId);
                result.oees.Add(new ResponseChanelOee
                {
                    name = bottle.ParentTitle,
                    oee = oees[i],
                    denominator = 0
                });
                i++;
                //oeeList.Add(oeeModel);
            }
            var totalset = _totalSetRepository.Get(q => q.project_id == ProjectId);
            result.days = _kpiTasklist.GetKpiSafeDay(totalset?.safe_day.ToInt() ?? 0, ProjectId).ToStr().ToInt();
            result.staff = users.Count();
            //var molecular = oeeList.Sum(s => s.Molecular);
            //var denominator = oeeList.Sum(s => s.Denominator);
            //if (denominator == 0)
            //    result.oeeNum = 0;
            //else
            //    result.oeeNum = Math.Round(molecular * 100 / denominator, 2);
            result.oeeNum = 83.79;

            if (result.oeeNum > 100)
            {
                result.oeeNum = 100.00;
            }
            result.value = result.oees.Select(s => s.oee).ToList();
            result.totalProduce = result.produces.Sum(s => s.lightNum);

            return new ObjectResult(result);
        }

        /// <summary>
        /// 获取当前产品 和客户
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetProductLogo()
        {
            var swiperInfo = new List<ResponseLogoInfo>();
            var levelline = _dashboardFactoryChanel.GetDashboardChanel(ProjectId);
            if (!levelline.Any())
                throw new BadRequestException(RequestEnum.LevelSectionNotFound);
            var yieldRepository = new LocationYieldRepository(CompanyId, ProjectId);
            foreach (var line in levelline)
            {
                var stations = _sigerProjectLevelSection.GetAccStationByline(ProjectId, line.id).Select(s => s.id).ToList();
                var bottleMachines = _dashboardLevelRepository.GetBottleSection(stations, ProjectId).ToList();
                if (!bottleMachines.Any())
                    continue;

                var dtStart = DateTimeHelper.GetTodayStartTime();
                var schedu = 8; //8，12小时制
                var cfg = _dashboardLevelRepository.Get(f => f.ProjectId == ProjectId && f.Section == line.id && f.PageType == (int)DashboardEnum.Chanel);
                if (cfg != null)
                {
                    schedu = cfg.Schedu;
                }
                var _hour = cfg == null ? schedu : cfg.Startime;
                var stepStartDate = cfg.CurrentDate?.AddHours(_hour) ?? dtStart;
                var stepEndDate = stepStartDate.AddHours(schedu);

                var yields = yieldRepository.GetLocationYields(bottleMachines, stepStartDate, stepEndDate).ToList();
                var totalCount = yields.Sum(s => s.yield);
                var yeidProduct = yields.LastOrDefault();
                var pname = string.Empty;
                var pmodel = string.Empty;
                var purl = string.Empty;
                if (yeidProduct != null)
                {
                    var productInfo = _productRepository.Get(f => f.projectid == ProjectId && f.name == yeidProduct.productName);
                    pname = productInfo != null ? productInfo.name : "";
                    pmodel = productInfo != null ? productInfo.drawingcode : "";
                    purl = productInfo != null ? productInfo.image : "";
                }
                swiperInfo.Add(new ResponseLogoInfo
                {
                    productPlan = cfg.Column4,
                    chanelName = line.title,
                    productActual = totalCount.ToString(),
                    productName = pname,
                    productModel = pmodel,
                    pic = purl
                });

            }

            return new ObjectResult(swiperInfo);
        }
    }
}
