using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Siger.Middlelayer.DashboardRepository.Repositories.Interface;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.DashboardRepository.Request;
using Siger.Middlelayer.DashboardRepository.Entities;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Share.Enum.ModuleEnum;
using Siger.ApiCommon.Filters;
using System.Linq.Expressions;
using Siger.Middlelayer.Repository.Extensions;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.DashboardRepository.Response;
using Siger.Middlelayer.Redis.Repositories;
using Siger.Middlelayer.Redis.RedisEntities;
using Siger.Middlelayer.Common.Log;
using Siger.ApiCommon.Result;
using Siger.Middlelayer.TlmRepository.Repositories.Interface;
using Siger.Middlelayer.TlmRepository.Response;
using Siger.Middlelayer.Repository.Data;
using Siger.Middlelayer.WmsRepository.Repositories.Interface;
using Siger.Middlelayer.WmsRepository.Response;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Utility.Helpers;
using Siger.Middlelayer.Common.FieldEnum;

namespace Siger.ApiDashboard.Controllers
{
    public class DashboardTlmController : BaseController
    {
        private readonly IToolLifeWorkorderRepository _workorderRepository;
        private readonly ISigerProjectUserRepository _projectUserRepository;
        private readonly IToolLifeToolTechRepository _toolTechRepository;
        private readonly IToolLifeToolChoiceSummaryRepository _choiceSummaryRepository;
        private readonly Isiger_wms_stock_alarmRepository _alarmRepository;
        private readonly Isiger_wms_stockRepository _stockRepository;
        private readonly IToolLifeToolInstallRepository _toolInstallRepository;
        private readonly ISigerProjectMachineAttributionRepository _machineAttributionRepository;
        private readonly ISigerProjectLevelSectionRepository _levelSectionRepository;
        private readonly IToolLifeToolPackageRepository _packageRepository;
        private readonly Isiger_wms_storage_locationRepository _locationRepository;
        private readonly IToolLifeToolRepository _toolLifeToolRepository;

        public DashboardTlmController(IToolLifeWorkorderRepository workorderRepository, ISigerProjectUserRepository projectUserRepository, IToolLifeToolTechRepository toolTechRepository
            , IToolLifeToolChoiceSummaryRepository choiceSummaryRepository, Isiger_wms_stock_alarmRepository alarmRepository, Isiger_wms_stockRepository stockRepository, IToolLifeToolInstallRepository toolInstallRepository
            , ISigerProjectMachineAttributionRepository machineAttributionRepository, ISigerProjectLevelSectionRepository levelSectionRepository, IToolLifeToolPackageRepository packageRepository
            , Isiger_wms_storage_locationRepository locationRepository, IToolLifeToolRepository toolLifeToolRepository)
        {
            _workorderRepository = workorderRepository;
            _projectUserRepository = projectUserRepository;
            _toolTechRepository = toolTechRepository;
            _choiceSummaryRepository = choiceSummaryRepository;
            _alarmRepository = alarmRepository;
            _stockRepository = stockRepository;
            _toolInstallRepository = toolInstallRepository;
            _machineAttributionRepository = machineAttributionRepository;
            _levelSectionRepository = levelSectionRepository;
            _packageRepository = packageRepository;
            _locationRepository = locationRepository;
            _toolLifeToolRepository = toolLifeToolRepository;
        }
        /// <summary>
        /// 产品备刀列表
        /// </summary>
        /// <returns></returns>
        [ProducesDefaultResponseType(typeof(ResponseToolPreparationList))]
        [HttpGet]
        public IActionResult ToolPreparationList()
        {
            var ret = new List<ResponseToolPreparationList>();
            var orders = _workorderRepository.GetPagedList(0, "", 0, "",0,"", 0, 0, ProjectId).Data;
            //var orders = _workorderRepository.GetWorkorderData(ProjectId);
            foreach (var order in orders)
            {
                var model = new ResponseToolPreparationList
                {
                    OrderNumber = order.order_number,
                    UserName = order.operator_name,
                    NeedTime = order.date,
                    ProductName = order.product_name,
                    MachineName = order.machineType_name,
                };
                var toolTech = _toolTechRepository.GetPagedList(order.technology_id, "", 0, 0, 1, ProjectId).Data.FirstOrDefault();
                if (toolTech!=null)
                {
                    var data = Mapper<ResponseToolPreparationList, ResponseToolPreparationList>.Map(model);
                    data.MaterialName = toolTech.material_name;
                    data.ToolLocation = toolTech.cutter_number;
                    //库位库存
                    var summarys = _choiceSummaryRepository.GetSummaryPagedList(order.technology_id, order.id, ProjectId).ToList();
                    if (!summarys.Any())
                    {
                        summarys = _choiceSummaryRepository.GetDataListFromTechTool(order.technology_id, "", ProjectId).ToList();
                    }

                    data.Location = summarys.FirstOrDefault(f => f.part_no == toolTech.part_no)?.position ?? "";
                    var positionId = summarys.FirstOrDefault(f => f.part_no == toolTech.part_no)?.positionId ?? 0;
                    data.Count = _choiceSummaryRepository.CountStockQuantity(0, toolTech.part_no, ProjectId, positionId);
                    ret.Add(data);
                }
            }
            return new ObjectResult(ret);
        }

        /// <summary>
        /// 刀具库存报警
        /// </summary>
        /// <returns></returns>
        [ProducesDefaultResponseType(typeof(ResponseStockAlarm))]
        [HttpGet]
        public IActionResult GetStockAlarm()
        {
            var result = _alarmRepository.GetPagedList(0, ProjectId, 0, 0);
            var res = new List<ResponseStockAlarm>();
            foreach (var item in result.Data)
            {
                var model = Mapper<ResponseStockAlarm, ResponseStockAlarm>.Map(item);
                if (model.status != (int)AlarmStatus.Operated)
                {
                    model.quantity = _stockRepository.GetList(t => t.material_id == item.material_id && t.status == (int)RowState.Valid &&
                        t.projectid == ProjectId && t.stock_state == (int)StockEnum.InWavehouse).Sum(t => t.quantity);
                    res.Add(model);
                    //TODO库位
                    var stockLocation = _stockRepository.Get(f => f.projectid == ProjectId && f.status != 0 && f.stock_state == 0)?.storage_location_id ?? 0;
                    model.Location = _locationRepository.Get(f => f.projectid == ProjectId && f.status != 0 && f.id == stockLocation)?.name ?? "";
                }
            }
            return new ObjectResult(res);
        }

        /// <summary>
        /// 刀具使用量
        /// </summary>
        /// <returns></returns>
        [ProducesDefaultResponseType(typeof(ResponseToolUseChart))]
        [HttpGet]
        public IActionResult GetToolUse()
        {
            var ret = new ResponseToolUseChart();
            var end = DateTime.Now.AddDays(1).AddSeconds(-1);
            var start = DateTime.Now.Date.AddDays(-15);
            var dates = DateTimeHelper.GetDateTimes(start, end, 0);
            var useList = _toolInstallRepository.GetList(t => t.install_category == InstallCategory.Install &&
                            t.create_time >= start && t.create_time <= end && t.project_id == ProjectId && t.status == (int)RowState.Valid).ToList();
            foreach (var date in dates)
            {
                var sDatetime = date;
                var eDatetime = date.AddDays(1).AddSeconds(-1);
                ret.X.Add(date.ToString(ParameterConstant.MonthDayFormay));
                ret.Y.Add(useList.Count(t => t.create_time <= eDatetime && t.create_time >= sDatetime));
            }
            return new ObjectResult(ret);
        }
        /// <summary>
        /// 刀具寿命预警
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTooLifeData()
        {
            var ret = new List<ResponseGetTooLifeData>();
            var tlmToolDataRepository = new TlmToolDataRepository(CompanyId, ProjectId);
            var data = tlmToolDataRepository.GetAllToolData();
            var sectionList = _levelSectionRepository.GetList(f => f.projectid == ProjectId && f.status != 0);
            var attrList = _machineAttributionRepository.GetList(f => f.projectid == ProjectId && f.status != 0);
            foreach (var item in data)
            {
                var model = new ResponseGetTooLifeData
                {
                    ToolLife = item.Life,
                    ToolLife2 = item.Life2,
                    ToolNumber = item.ToolNumber,
                    ToolNumber2 = item.ToolNumber2,
                    State = item.ChannelState
                };
                model.ToolLife = item.Life;
                var attr = attrList.FirstOrDefault(f => f.machine == item.MID);
                if (attr != null)
                {
                    model.Name = $"{sectionList.FirstOrDefault(f => f.id == attr.station)?.title ?? ""}-{attr.name}";
                }
                var toolid = _toolLifeToolRepository.Get(f => f.project_id == ProjectId && f.status != 0 && f.number == item.ToolNumber)?.id ?? 0;
                model.Location = _toolInstallRepository.GetToolLifeConfigData(ProjectId, item.MID).FirstOrDefault(f=>f.toolids.Contains(toolid))?.Location;
                ret.Add(model);
            }
            return new ObjectResult(ret);
        }

        /// <summary>
        /// 刀具寿命设置
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [NoTokenValidateFilter]
        [HttpPost]
        public IActionResult SetToolData([FromBody]RequestSetToolData request)
        {
            var cid = request.cid.ToInt();
            var pid = request.pid.ToInt();
            try
            {
                var tlmToolDataRepository = new TlmToolDataRepository(cid, pid);
                tlmToolDataRepository.SetToolData(new SetToolData { ChannelState = request.程序状态, Life = request.当前刀具剩余寿命, MID = request.MID, Step = request.步骤号, ToolNumber = request.刀具号 });
            }
            catch (Exception ex)
            {
                Logger.WriteLineError($"DashboardTlmController_SetToolData Failed! Message:{ex.Message}");
                throw new BadRequestException(CommonEnum.Fail);
            }
            return new ObjectResult(CommonEnum.Succefull);
        }
    }
}
