using HighWayIot.Log4net;
using HighWayIot.Plc;
using HighWayIot.Plc.PlcHelper;
using HighWayIot.Repository.domain;
using HighWayIot.Repository.service;
using HighWayIot.Winform.UserControlPages;
using HslCommunication.Profinet.Keyence;
using Models;
using SixLabors.ImageSharp.PixelFormats;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace HighWayIot.Winform.Business
{
    /// <summary>
    /// 报表数据刷新业务类
    /// </summary>
    public class MonitorDataRefreshBusiness
    {
        TransferSingal transferSingal = new TransferSingal();

        private Timer refreshTimer;

        public MonitorDataRefreshBusiness()
        {
            // 启动定时器，每隔1秒刷新一次报表数据
            refreshTimer = new System.Threading.Timer(RefreshData, null, 0, 1000);
        }

        /// <summary>
        /// 数据刷新
        /// </summary>
        /// <param name="o"></param>
        private void RefreshData(object o)
        {
            try
            {
                byte[] signals = transferSingal.ReadStationReportSignal();
                if (signals == null)
                {
                    return;
                }

                //解析返回的信号数据
                ushort[] rgvNo = new ushort[7];
                ushort[] rgvState = new ushort[7];
                float[] weights = new float[4];

                for (int i = 0; i < 7; i++)
                {
                    rgvNo[i] = PlcConnect.MelsecInstance2.ByteTransform.TransUInt16(signals, (i * 2) + 20); 
                    rgvState[i] = PlcConnect.MelsecInstance2.ByteTransform.TransUInt16(signals, i * 2);
                    if (i > 2)
                    {
                        weights[i - 3] = PlcConnect.MelsecInstance2.ByteTransform.TransSingle(signals, ((i - 3) * 4) + 38);
                    }
                }
                //LogHelper.Instance.Info(string.Join(", ", rgvNo));
                //LogHelper.Instance.Info(string.Join(", ", rgvState));

                //装圈工位
                if (rgvState[0] == 1)
                {
                    // 监控画面信息插入
                    if(MonitorInsert(RecipeSendBusiness.NowRecipeCode, RecipeSendBusiness.NowDeviceNo, rgvNo[0]))
                    {
                        MonitorMainPage.MonitorRefreshAction.Invoke();
                    }
                    transferSingal.WriteStationReportSignal(1); // 复位信号
                }
                //基部胶
                if (rgvState[1] == 1)
                {
                    ZxDailyReportEntity entity = ZxDailyReportService.Instance.GetNearData(rgvNo[1]);
                    if (entity == null)
                    {
                        transferSingal.WriteStationReportSignal(2); // 复位信号
                        goto n1;
                    }
                    entity.BaseEndTime = DateTime.Now;
                    if (ZxDailyReportService.Instance.UpdateDailyReportInfo(entity))
                    {
                        MonitorMainPage.MonitorRefreshAction.Invoke();
                    }
                    transferSingal.WriteStationReportSignal(2); // 复位信号
                }
            n1:

                //中层胶
                if (rgvState[2] == 1)
                {
                    ZxDailyReportEntity entity = ZxDailyReportService.Instance.GetNearData(rgvNo[2]);
                    if (entity == null)
                    {
                        transferSingal.WriteStationReportSignal(3); // 复位信号
                        goto n2;
                    }
                    entity.MidEndTime = DateTime.Now;
                    if (ZxDailyReportService.Instance.UpdateDailyReportInfo(entity))
                    {
                        MonitorMainPage.MonitorRefreshAction.Invoke();
                    }
                    MonitorMainPage.MonitorRefreshAction.Invoke();
                    transferSingal.WriteStationReportSignal(3); // 复位信号
                }
            n2:

                //胎面胶
                for (int i = 3; i <= 5; i++)
                {
                    if (rgvState[i] == 1)
                    {
                        // 监控画面信息插入
                        ZxDailyReportEntity entity = ZxDailyReportService.Instance.GetNearData(rgvNo[i]);
                        if (entity == null)
                        {
                            transferSingal.WriteStationReportSignal(i + 1); // 复位信号
                            continue;
                        }
                        entity.FaceEndTime = DateTime.Now;
                        int temp = Convert.ToInt32(weights[i - 3]);
                        if (temp != 0)
                        {
                            entity.RawTireWeight = temp;
                        }
                        if (ZxDailyReportService.Instance.UpdateDailyReportInfo(entity))
                        {
                            MonitorMainPage.MonitorRefreshAction.Invoke();
                        }
                        transferSingal.WriteStationReportSignal(i + 1); // 复位信号
                    }
                }

                //结束
                if (rgvState[6] == 1)
                {
                    ZxDailyReportEntity entity = ZxDailyReportService.Instance.GetNearData(rgvNo[6]);
                    if (entity == null)
                    {
                        transferSingal.WriteStationReportSignal(7); // 复位信号
                        return;
                    }
                    int temp = Convert.ToInt32(weights[3]);
                    entity.IsDone = 1;
                    if (temp != 0)
                    {
                        entity.RepeatWeight = temp;
                    }
                    if (ZxDailyReportService.Instance.UpdateDailyReportInfo(entity))
                    {
                        MonitorMainPage.MonitorRefreshAction.Invoke();
                    }
                    transferSingal.WriteStationReportSignal(7); // 复位信号

                }
            }
            catch (Exception ex)
            {
                Log4net.LogHelper.Instance.Error("报表解析方法出现错误", ex);
            }
        }

        /// <summary>
        /// 监控画面信息插入
        /// </summary>
        /// <param name="deviceNo">机台号</param>
        /// <param name="recipeCode">硫化机台编号</param>
        /// <param name="rgvNo">RGV编号</param>
        public bool MonitorInsert(string recipeCode, string deviceNo, int rgvNo)
        {
            DateTime judgeTime = DateTime.Now - TimeSpan.FromMinutes(30);
            List<ZxDailyReportEntity> judgeEntity = ZxDailyReportService.Instance
                .GetDailyReportInfos(x =>
                x.DeviceNo == rgvNo &&
                x.IsDone == 0 &&
                x.StartTime >= judgeTime
                ).ToList();

            //要是二十分钟内有没完结的相同记录，就不插入
            if (judgeEntity.Count > 0)
            {
                Log4net.LogHelper.Instance.Info($"（{deviceNo}车）重复插入");
                return false;
            }

            ZxRecipeEntity recipeEntity = ZxRecipeService.Instance.GetRecipeInfosByRecipeCode(recipeCode).FirstOrDefault();
            if (recipeEntity == null)
            {
                Log4net.LogHelper.Instance.Info($"没有符合的配方数据（{deviceNo}车）");
                return false;
            }

            ZxDailyReportEntity entity = new ZxDailyReportEntity()
            {
                Uuid = Guid.NewGuid().ToString("N"),
                VulcanizationNo = deviceNo,
                StartTime = DateTime.Now,
                RecipeName = recipeEntity.RecipeName,
                RecipeCode = recipeEntity.RecipeCode,
                SpecCode = recipeEntity.RecipeSpecCode,
                DeviceNo = rgvNo,
                RawTireWeight = 0,//(int)ZxRecipeParaService.Instance.GetRecipeParaInfoByRecipeCode(recipeCode).FirstOrDefault()?.TireWeight,
                IsDone = 0
            };

            return ZxDailyReportService.Instance.InsertDailyReportInfo(entity);
        }
    }
}
