using CFX;
using CFX.Structures;
using Microsoft.AspNetCore.Http;
using Sln.Iot.Business.Entity;
using Sln.Iot.CFX.CFXConnect;
using Sln.Iot.CFX.Event;
using Sln.Iot.Common;
using Sln.Iot.Config;
using Sln.Iot.Model.Entity;
using Sln.Iot.PLC;
using Sln.Iot.Serilog;
using Sln.Iot.Socket;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;

namespace Sln.Iot.Business
{
    public class MesReportBusiness
    {
        private Timer _timer;
        private readonly SerilogHelper _log = SerilogHelper.Instance;
        private readonly DeltaHttpClient _deltaHttpClient = DeltaHttpClient.Instance;
        private readonly AppConfig _appConfig = AppConfigSetting.Load();
        private readonly PLCConnect _plc = PLCConnect.Instance;

        CFXConnectVacuum _cfxVacuum = CFXConnectVacuum.Instance;
        CFXConnectOven _cfxOven = CFXConnectOven.Instance;
        StationParametersModifiedEvent stationParametersModifiedEvent = new StationParametersModifiedEvent();

        public MesReportBusiness()
        {
            //_deltaHttpClient.Init();
            _timer = new Timer(TimerCallback, null, 0, 1000 * _appConfig.MesSendDelay);
        }

        public void TimerCallback(object? state)
        {
            //MES上报
            ErrorGet(1);
            //_deltaHttpClient.PostRequestSend(tranter(GlobalVar.Connect1Entity));
            ErrorGet(2);
            //_deltaHttpClient.PostRequestSend(tranter(GlobalVar.Connect2Entity));

            //CFX上传
            _cfxVacuum.PublishEvent(new CFXEnvelope(stationParametersModifiedEvent.Handle(ParameterSet(GlobalVar.Connect1Entity.InterfaceID,
                "制程设备",
                GlobalVar.Connect1Entity.Status,
                GlobalVar.Connect1Entity.Status,
                GlobalVar.Connect1Entity.StatusCode,
                GlobalVar.Connect1Entity.PassQuantity.ToString(),
                GlobalVar.Connect1Entity.FailQuantity.ToString(),
                GlobalVar.Connect1Entity.CycleTime.ToString(),
                GlobalVar.Connect1Entity.RunningTime.ToString(),
                GlobalVar.Connect1Entity.WaitingTime.ToString(),
                "1",
                GlobalVar.Connect1Entity.InputQuantity.ToString(),
                GlobalVar.Connect1Entity.ErrorCount.ToString(),
                GlobalVar.Connect1Entity.ErrorTime.ToString()
                ))));

            _cfxOven.PublishEvent(new CFXEnvelope(stationParametersModifiedEvent.Handle(ParameterSet(GlobalVar.Connect2Entity.InterfaceID,
                "制程设备",
                GlobalVar.Connect2Entity.Status,
                GlobalVar.Connect2Entity.Status,
                GlobalVar.Connect2Entity.StatusCode,
                GlobalVar.Connect2Entity.PassQuantity.ToString(),
                GlobalVar.Connect2Entity.FailQuantity.ToString(),
                GlobalVar.Connect2Entity.CycleTime.ToString(),
                GlobalVar.Connect2Entity.RunningTime.ToString(),
                GlobalVar.Connect2Entity.WaitingTime.ToString(),
                "1",
                GlobalVar.Connect2Entity.InputQuantity.ToString(),
                GlobalVar.Connect2Entity.ErrorCount.ToString(),
                GlobalVar.Connect2Entity.ErrorTime.ToString()
                ))));

            if (_appConfig.IsMESLog)
            {
                _log.Info($"CFX真空箱上报 - InterfaceID:{GlobalVar.Connect1Entity.InterfaceID}, D262 状态码 Status:{GlobalVar.Connect1Entity.Status}, D108 灯号 StatusCode:{GlobalVar.Connect1Entity.StatusCode}, PassQty:{GlobalVar.Connect1Entity.PassQuantity}, FailQty:{GlobalVar.Connect1Entity.FailQuantity}, CycleTime:{GlobalVar.Connect1Entity.CycleTime}, RunningTime:{GlobalVar.Connect1Entity.RunningTime}, WaitingTime:{GlobalVar.Connect1Entity.WaitingTime}, InputQty:{GlobalVar.Connect1Entity.InputQuantity}, ErrorCnt:{GlobalVar.Connect1Entity.ErrorCount}, ErrorTimes:{GlobalVar.Connect1Entity.ErrorTime}");
                _log.Info($"CFX烤箱上报 - InterfaceID:{GlobalVar.Connect2Entity.InterfaceID}, D262 状态码 Status:{GlobalVar.Connect2Entity.Status}, D15176 灯号 StatusCode:{GlobalVar.Connect2Entity.StatusCode}, PassQty:{GlobalVar.Connect2Entity.PassQuantity}, FailQty:{GlobalVar.Connect2Entity.FailQuantity}, CycleTime:{GlobalVar.Connect2Entity.CycleTime}, RunningTime:{GlobalVar.Connect2Entity.RunningTime}, WaitingTime:{GlobalVar.Connect2Entity.WaitingTime}, InputQty:{GlobalVar.Connect2Entity.InputQuantity}, ErrorCnt:{GlobalVar.Connect2Entity.ErrorCount}, ErrorTimes:{GlobalVar.Connect2Entity.ErrorTime}");
            }

        }

        private string tranter(MesReportEntity entity)
        {
            //entity.CycleTime = _appConfig.CycleTime;

            #region 傳送字的資料
            string strSendData;
            strSendData = "[{";
            // strSendData += "\"factory\":\"" + "DG5" + "\",";
            strSendData += "\"interfaceID\":\"" + entity.InterfaceID + "\",";
            // strSendData += "\"EquipType\":" + EquipType + ",";
            strSendData += "\"status\":" + entity.StatusCode + ",";
            strSendData += "\"statusCode\":\"" + entity.Status + "\",";
            strSendData += "\"passQty\":" + entity.PassQuantity + ",";
            strSendData += "\"failQty\":" + entity.FailQuantity + ",";
            strSendData += "\"errorCnt\":" + entity.ErrorCount + ",";
            strSendData += "\"errorTimes\":" + entity.ErrorTime + ",";
            strSendData += "\"cycleTime\":" + entity.CycleTime + ",";
            strSendData += "\"runningTime\":" + entity.RunningTime + ",";
            strSendData += "\"waitingTime\":" + entity.WaitingTime + ",";
            // strSendData += "\"selfCheck\":" + (SELFCHECK ? "1" : "0") + ",";
            strSendData += "\"selfCheck\":" + "1" + ",";
            strSendData += "\"inputQty\":" + entity.InputQuantity + ",";
            strSendData += "\"barcode\":\"" + entity.Barcode + "\",";
            strSendData += "\"model\":\"" + entity.Cya + "\",";

            strSendData += "\"paramList\":[";
            //  strSendData += "{\"paramCode\":\"" + Key1 + "\",";
            // strSendData += "\"paramValue\":\"" + Value1 + "\"},";
            // strSendData += "{\"paramCode\":\"" + Key2 + "\",";
            //  strSendData += "\"paramValue\":\"" + Value2 + "\"},";
            //  strSendData += "{\"paramCode\":\"" + Key3 + "\",";
            //  strSendData += "\"paramValue\":\"" + Value3 + "\"},";
            //因为我们的数据此部分没有，如果再remove，将删除[，导致格式错误
            //  strSendData = strSendData.Remove(strSendData.Length - 1);//20170525 Tim 修改最後一個,沒刪除的bug
            strSendData += "]";
            strSendData += "}]";

            //_cfxHelper.PublishEvent(new CFXEnvelope(stationParametersModifiedEvent.Handle(ParameterSet(entity.InterfaceID,
            //    "制程设备",
            //    entity.Status,
            //    entity.Status,
            //    entity.StatusCode,
            //    entity.PassQuantity.ToString(),
            //    entity.FailQuantity.ToString(),
            //    entity.CycleTime.ToString(),
            //    entity.RunningTime.ToString(),
            //    entity.WaitingTime.ToString(),
            //    "1",
            //    entity.InputQuantity.ToString(),
            //    entity.ErrorCount.ToString(),
            //    entity.ErrorTime.ToString()
            //    ))));

            #endregion
            return strSendData;
        }

        /// <summary>
        /// 设备状态获取
        /// </summary>
        /// <returns></returns>
        private void ErrorGet(int deviceNo)
        {
            string status = "0";
            string statusCode = "0";
            if (deviceNo == 1) //真空箱
            { //灯号
                GlobalVar.Connect1Entity.RunningTime = (int)(DateTime.Now - GlobalVar.OpenTime).TotalSeconds;
                var r1 = _plc.ReadInt16(_plc.PLC21, "D108");
                if (r1.IsSuccess)
                {
                    GlobalVar.Connect1Entity.StatusCode = r1.Content.ToString();
                    GlobalVar.Connect1Entity.Status = StatusJudge(r1.Content, 1).ToString();

                    if (GlobalVar.Connect1Entity.Status == "1")
                    {
                        if (GlobalVar.Connect1Entity.IsError == false)
                        {
                            GlobalVar.Connect1Entity.ErrorCount++;
                            GlobalVar.Connect1Entity.LastErrorTime = DateTime.Now;
                            GlobalVar.Connect1Entity.IsError = true;
                        }
                        else
                        {
                            GlobalVar.Connect1Entity.ErrorTime = (int)(DateTime.Now - GlobalVar.Connect1Entity.LastErrorTime).TotalSeconds;
                        }
                    }
                    else
                    {
                        if (GlobalVar.Connect1Entity.IsError == true)
                        {
                            GlobalVar.Connect1Entity.IsError = false;
                        }
                    }
                }
                else
                {
                    _log.Error($"读取PLC状态失败: 真空箱1{r1.IsSuccess} - {r1.Message}");
                }
            }
            else if (deviceNo == 2) //烤箱
            { //灯号
                GlobalVar.Connect2Entity.RunningTime = (int)(DateTime.Now - GlobalVar.OpenTime).TotalSeconds;
                var r1 = _plc.ReadInt16(_plc.PLC20, "D15176");
                if (r1.IsSuccess)
                {
                    GlobalVar.Connect2Entity.StatusCode = r1.Content.ToString();
                    GlobalVar.Connect2Entity.Status = StatusJudge(r1.Content, 2).ToString();

                    if (GlobalVar.Connect2Entity.Status == "1")
                    {
                        if (GlobalVar.Connect2Entity.IsError == false)
                        {
                            GlobalVar.Connect2Entity.ErrorCount++;
                            GlobalVar.Connect2Entity.LastErrorTime = DateTime.Now;
                            GlobalVar.Connect2Entity.IsError = true;
                        }
                        else
                        {
                            GlobalVar.Connect2Entity.ErrorTime = (int)(DateTime.Now - GlobalVar.Connect2Entity.LastErrorTime).TotalSeconds;
                        }
                    }
                    else
                    {
                        if (GlobalVar.Connect2Entity.IsError == true)
                        {
                            GlobalVar.Connect2Entity.IsError = false;
                        }
                    }
                }
                else
                {
                    _log.Error($"读取PLC状态失败: 烤箱{r1.IsSuccess} - {r1.Message}");
                }
            }


            //return (status, statusCode);
        }

        private void ErrorJudge(bool errorSituation)
        {

        }

        /// <summary>
        /// 根据StatusCode判断Status 
        /// </summary>
        /// <param name="sc"></param>
        /// <returns></returns>
        private int StatusJudge(int sc, int num)
        {
            if (sc == 1)
            {
                //return 1;
                try
                {
                    switch (num)
                    {
                        //故障码
                        case 1: //真空箱
                            //return 1;
                            return _plc.ReadInt16(_plc.PLC21, "D262").Content;
                        case 2: //烤箱
                            //return 1;
                            return _plc.ReadInt16(_plc.PLC20, "D262").Content;
                        default:
                            return 1;
                    }
                }
                catch
                {
                    return 1;
                }

            }
            else
            {
                return 0;
            }
        }


        /// <summary>
        /// stationParameters参数设置
        /// </summary>
        public List<Parameter> ParameterSet(
            string interfaceID,
            string equipType,
            string status,
            string light,
            string statusCode,
            string passQty,
            string failQty,
            string cycleTime,
            string runningTime,
            string waitingTime,
            string selfCheck,
            string inputQty,
            string errorCnt,
            string errorTimes
            )
        {
            return new List<Parameter>()
            {
                new GenericParameter()
                {
                    Name = "InterfaceID",
                    Value = interfaceID
                },
                new GenericParameter()
                {
                    Name = "EquipType",
                    Value = equipType
                },
                new GenericParameter()
                {
                    Name = "Status",
                    Value = status
                },
                new GenericParameter()
                {
                    Name = "Light",
                    Value = light
                },
                new GenericParameter()
                {
                    Name = "StatusCode",
                    Value = statusCode
                },
                new GenericParameter()
                {
                    Name = "PassQty",
                    Value = passQty
                },
                new GenericParameter()
                {
                    Name = "FailQty",
                    Value = failQty
                },
                new GenericParameter()
                {
                    Name = "CycleTime",
                    Value = cycleTime
                },
                new GenericParameter()
                {
                    Name = "RunningTime",
                    Value = runningTime
                },
                new GenericParameter()
                {
                    Name = "WaitingTime",
                    Value = waitingTime
                },
                new GenericParameter()
                {
                    Name = "SelfCheck",
                    Value = selfCheck
                },
                new GenericParameter()
                {
                    Name = "InputQty",
                    Value = inputQty
                },
                new GenericParameter()
                {
                    Name = "ErrorCnt",
                    Value = errorCnt
                },
                new GenericParameter()
                {
                    Name = "ErrorTimes",
                    Value = errorTimes
                },
            };
        }
    }
}
