using Microsoft.Extensions.Logging;
using SlnMesnac.Business.@base;
using SlnMesnac.Config;
using SlnMesnac.Model.domain;
using SlnMesnac.Model.dto;
using SlnMesnac.Model.enums;
using SlnMesnac.Plc;
using SlnMesnac.Repository.service;
using SlnMesnac.Rfid;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

#region << 版 本 注 释 >>
/*--------------------------------------------------------------------
* 版权所有 (c) 2024 WenJY 保留所有权利。
* CLR版本：4.0.30319.42000
* 机器名称：LAPTOP-E0N2L34V
* 命名空间：SlnMesnac.Business
* 唯一标识：b1e2fab0-4f30-42b9-bcc3-19800d1b1f9b
*
* 创建者：WenJY
* 电子邮箱：wenjy@mesnac.com
* 创建时间：2024-04-08 16:06:54
* 版本：V1.0.0
* 描述：
*
*--------------------------------------------------------------------
* 修改人：
* 时间：
* 修改说明：
*
* 版本：V1.0.0
*--------------------------------------------------------------------*/
#endregion << 版 本 注 释 >>
namespace SlnMesnac.Business
{
    /// <summary>
    /// 托盘装载业务类
    /// </summary>
    public class PalletStowBusiness:BaseBusiness
    {
        private readonly IMesProductPlanService _mesProductPlanService;

        private readonly IWmsInstockService _msInstockService;

        private readonly IRealPalletTaskService _realPalletTaskService;

        private List<RealPalletTask> _palletTasks;


        public PalletStowBusiness(ILogger<BaseBusiness> logger, AppConfig appConfig, List<PlcAbsractFactory> plcFactories, List<RfidAbsractFactory> rfidFactories, IMesProductPlanService mesProductPlanService, IWmsInstockService msInstockService, IRealPalletTaskService realPalletTaskService, List<RealPalletTask> palletTasks,IServiceProvider serviceProvider) : base(logger, appConfig, plcFactories, rfidFactories, serviceProvider)
        {
            _mesProductPlanService = mesProductPlanService;
            _msInstockService = msInstockService;
            _realPalletTaskService = realPalletTaskService;
            _palletTasks = palletTasks;
          
        }
       

        /// <summary>
        /// 刷新托盘队列
        /// </summary>
        public delegate void RefreshPalletTaskList(List<RealPalletTask> list);
        public event RefreshPalletTaskList? RefreshPalletTaskListEvent;


        public void Init()
        {
            EmptyPalletHandle();
           
        }

        /// <summary>
        /// 空托盘进入码垛位处理
        /// </summary>
        private void EmptyPalletHandle()
        {
            //读取PLC空托盘流转信号
            while (true)
            {
                try
                {
                    var plc = base.GetPlcByKey("plc");

                    if (plc == null)
                    {
                        _logger.LogInformation("读取PLC空托盘流转信号,PLC连接信息为空......");
                        Thread.Sleep(3000);
                        continue;
                    }

                    if (!plc.readBoolByAddress(GetPlcAddressByConfigKey("空托到位")))
                    {
                        _logger.LogInformation("等待空托盘到位信号触发......");
                        Thread.Sleep(5000);
                        continue;
                    }

                    //读取RFID、获取当前正在执行的计划、将当前计划、工单等信息与托盘绑定
                    RefreshMessage("空托盘到位信号触发成功,读取托盘RFID信息");

                    ReadEpcStrByRfidKey("test", out string epcStr);

                    if (string.IsNullOrEmpty(epcStr))
                    {
                        throw new ArgumentException($"托盘信息读取失败");
                    }


                    RefreshMessage($"空托盘RFID信息读取成功，标签信息：{epcStr}");

                    Thread.Sleep(1000);

                    _mesProductPlanService.GetStartedProdPlan(out MesProductPlanDto productPlanDto);

                    if (productPlanDto == null)
                    {
                        throw new ArgumentException($"未获取到正在执行的生产计划");
                    }

                    plc.writeInt16ByAddress(GetPlcAddressByConfigKey("空托到位"), 0);
                    
                    //绑定信息存入wms_product_instock
                    _msInstockService.Insert(new WmsInstock()
                    {
                        PalletInfoCode = epcStr,
                        PlanCode = productPlanDto.PlanCode,
                        SaleorderCode = productPlanDto.SaleorderCode,
                        SaleOrderId = productPlanDto.SaleOrderId,
                    });
                    RefreshMessage($"绑定托盘信息，托盘:{epcStr};计划:{productPlanDto.PlanCode};工单:{productPlanDto.SaleorderCode}");

                    _realPalletTaskService.InsertPalletTask(new RealPalletTask() { PalletCode = epcStr,RecordTime = DateTime.Now });

                    RefreshPalletTaskListEvent?.Invoke(_palletTasks);

                }
                catch (Exception e)
                {
                    RefreshMessage($"空托盘进入码垛位处理异常：{e.Message}");
                }
                Thread.Sleep(5000);
            }
        }

        public void RemovePalletInfo(string palletCode)
        {
            _realPalletTaskService.RemovePalletTask(palletCode);
            RefreshPalletTaskListEvent?.Invoke(_palletTasks);
        }
    }
}
