using Aitex.Common.Util;
using Aitex.Core.RT.ConfigCenter;
using Aitex.Core.RT.DataCenter;
using Aitex.Core.RT.Log;
using Aitex.Core.Util;
using PunkHPX8_Core;
using MECF.Framework.Common.CommonData;
using MECF.Framework.Common.CommonData.PowerSupplier;
using MECF.Framework.Common.Device.PowerSupplier;
using MECF.Framework.Common.Device.Wago;
using MECF.Framework.Common.Net;
using MECF.Framework.Common.Utilities;
using MECF.Framework.Simulator.Core.Driver;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Xml.Linq;
namespace PunkHPX8_Simulator.Devices
{
    public class PowerSupplierSocketSimulator : SocketDeviceSimulator
    {
        private const short POWER_CONTROL_ADDRESS = 0x0113;
        private const short STEP_PERIOD_ADDRESS = 0x1400;
        private const short STEP_PERIOD_START_ADDRESS = 0x1640;
        private const short GOLD_CURRENT_SETTING_ADDRESS = 0x6102;
        private const short GOLD_STEP_PERIOD_ADDRESS = 0x77D0;
        private const short GOLD_STEP_PERIOD_START_ADDRESS = 0x7C50;
        /// 
        /// 电源状态(00-cv输出,01-cc输出)
        /// 
        private const short POWER_STATUS_ADDRESS = 0x0200;
        Dictionary _powerSupplierDic = new Dictionary();
        private IByteTransform byteTransform = new BigEndianByteTransformBase();
        private List _powerSupplierDatas = new List();
        private byte _startStep = 1;
        private byte _endStep = 255;
        private byte _cycle = 1;
        private byte _currentStep = 0;
        private int _currentLength = 0;
        private DateTime _currentTime = DateTime.Now;
        private bool _isGoldPower = false;
        private int _currentSetScale;
        private System.Timers.Timer _timer;
        /// 
        /// 记录每次设置的电流值
        /// 
        private byte[] _powerSupplierSetPoint = new byte[4];
        public PowerSupplierSocketSimulator(int port):base(port)
        {
            PowerSupplierData powerSupplierData1 = new PowerSupplierData();
            powerSupplierData1.Current = 0;
            powerSupplierData1.Voltage = 56000;
            _powerSupplierDic[1] = powerSupplierData1;
            PowerSupplierData powerSupplierData2 = new PowerSupplierData();
            powerSupplierData2.Current = 0;
            powerSupplierData2.Voltage = 2000;
            _powerSupplierDic[2] = powerSupplierData2;
            PowerSupplierData powerSupplierData3 = new PowerSupplierData();
            powerSupplierData3.Current = 0;
            powerSupplierData3.Voltage = 3000;
            _powerSupplierDic[3] = powerSupplierData3;
            PowerSupplierData powerSupplierData4 = new PowerSupplierData();
            powerSupplierData4.Current = 0;
            powerSupplierData4.Voltage = 4000;
            _powerSupplierDic[4] = powerSupplierData4;
            _timer = new System.Timers.Timer();
            _timer.Interval = 1000;
            _timer.Elapsed += Timer_Elapsed;
            InitializeParamater(port);
        }
        private void InitializeParamater(int port)
        {
            try
            {
                string oldXmlPath = PathManager.GetCfgDir();
                string newXmlPath = oldXmlPath.Replace("PunkHPX8_Simulator", "PunkHPX8_RT") + "Devices\\PowerSupplierCfg-Simulator.xml";
                PowerSupplierDeviceConfigCfg cfg = CustomXmlSerializer.Deserialize(new FileInfo(newXmlPath));
                if (cfg != null)
                {
                    foreach (PowerSupplierDeviceConfig config in cfg.PowerSupplierDeviceConfigs)
                    {
                        if(config.Port != port)
                        {
                            continue;
                        }
                        else
                        {
                            foreach (PowerSupplierDevice device in config.Devices)
                            {
                                if (device != null)
                                {
                                    if (config.Type == 1 && device.UnitSetScale > device.UnitScale) //金槽电源
                                    {
                                        _currentSetScale = device.UnitSetScale / device.UnitScale;
                                    }
                                    else
                                    {
                                        _currentSetScale = device.UnitScale / device.UnitSetScale;
                                    }
                                }
                                break;
                            }
                            break;
                        } 
                    }
                }
            }
            catch
            {
                LOG.WriteLog(eEvent.ERR_POWERSUPPLIER, "PowerSupplier", "Load power supplier xml failed");
            }
        }
        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if(_currentStep>=_cycle*_endStep)
            {
                _timer.Stop();
            }
            if(DateTime.Now.Subtract(_currentTime).TotalSeconds>=_currentLength)
            {
                _currentStep++;
                if (_currentStep >= _cycle * _endStep)
                {
                    _powerSupplierDic[1].Current = 0;
                    _timer.Stop();
                    return;
                }
                _currentTime = DateTime.Now;
                _currentLength = (int)(_powerSupplierDatas[_currentStep].Hour * 3600 + _powerSupplierDatas[_currentStep].Minute * 60 +
                    _powerSupplierDatas[_currentStep].Second);
                if (_isGoldPower)
                {
                    _powerSupplierDic[1].Current = (int)(_powerSupplierDatas[_currentStep].Current);
                }
                else
                {
                    _powerSupplierDic[1].Current = (int)(_powerSupplierDatas[_currentStep].Current * _currentSetScale);
                }
            }
        }
        protected override void ProcessUnsplitMessage(byte[] data)
        {
            short flag = byteTransform.TransInt16(data, 0);
            byte channel = data[6];
            byte command = data[7];
            if(!_powerSupplierDic.ContainsKey(channel))
            {
                OnWriteMessage(CreateError(flag,channel, command, 0x02));
                return;
            }
            if (command == 0x03)//读取
            {
                short startAddress = byteTransform.TransInt16(data, 8);
                short registerCount = byteTransform.TransInt16(data, 10);
                if (startAddress == 0x201)
                {
                    byte[] bytes = new byte[2*registerCount];
                    Array.Copy(byteTransform.GetBytes(_powerSupplierDic[channel].Voltage), 0, bytes, 0, 4);
                    Array.Copy(byteTransform.GetBytes(_powerSupplierDic[channel].Current), 0, bytes, 4, 4);
                    OnWriteMessage(CreateReadResponse(flag, channel, command, registerCount, bytes));
                    return;
                }
                else if (startAddress == 0x0110)
                {
                    byte[] bytes = new byte[2];
                    bytes[0] = 0;
                    bytes[1] = _powerSupplierDic[channel].Enabled?(byte)1:(byte)0;
                    OnWriteMessage(CreateReadResponse(flag, channel, command, registerCount, bytes));
                    return;
                }
                else if (startAddress == POWER_STATUS_ADDRESS)
                {
                    byte[] bytes = new byte[2];
                    bytes[0] = 0;
                    bytes[1] = (byte)_powerSupplierDic[channel].PowerStatus;
                    OnWriteMessage(CreateReadResponse(flag, channel, command, registerCount, bytes));
                    return;
                }
                else if (startAddress == 0x0101)
                {
                    byte[] bytes = new byte[2];
                    Array.Copy(byteTransform.GetBytes(_powerSupplierDic[channel].CurrentSetting), 0, bytes, 0, bytes.Length);
                    OnWriteMessage(CreateReadResponse(flag, channel, command, registerCount, bytes));
                    return;
                }
                else if(startAddress == GOLD_CURRENT_SETTING_ADDRESS)
                {
                    _isGoldPower = true;
                    OnWriteMessage(CreateReadResponse(flag, channel, command, registerCount, _powerSupplierSetPoint));
                    return;
                }
                else if (startAddress == 0X80)
                {
                    byte[] bytes = new byte[2];
                    bytes[0] = 0;
                    bytes[1] = _powerSupplierDic[channel].OutputSwitchControl;
                    OnWriteMessage(CreateReadResponse(flag, channel, command, registerCount, bytes));
                    return;
                }
                else if (startAddress == 0x0111)
                {
                    byte[] bytes = new byte[2];
                    bytes[0] = 0;
                    bytes[1] = (byte)_powerSupplierDic[channel].RunModel;
                    OnWriteMessage(CreateReadResponse(flag, channel, command, registerCount, bytes));
                    return;
                }
                else if (startAddress == POWER_CONTROL_ADDRESS)
                {
                    byte[] bytes = new byte[2];
                    bytes[0] = 0;
                    bytes[1] = (byte)_powerSupplierDic[channel].PowerControl;
                    OnWriteMessage(CreateReadResponse(flag, channel, command, registerCount, bytes));
                    return;
                }
                else
                {
                    OnWriteMessage(CreateError(flag, channel, command, 03));
                }
            }
            else if (command == 0x06)//设置
            {
                short startAddress = byteTransform.TransInt16(data, 8);
                short value = byteTransform.TransInt16(data, 10);
                if(startAddress==0x0110)
                {
                    UpdateChannelEnable(flag, channel, command, startAddress, data[11]);
                    if (_powerSupplierDic[channel].Enabled)
                    {
                        if (_powerSupplierDic[channel].RunModel == 1)
                        {
                            if (_isGoldPower)
                            {
                                int count = byteTransform.TransInt32(_powerSupplierSetPoint, 0);
                                _powerSupplierDic[channel].Current = count / _currentSetScale;
                            }
                            else
                            {
                                _powerSupplierDic[channel].Current = _powerSupplierDic[channel].CurrentSetting * _currentSetScale;
                            }
                        }
                    }
                    else
                    {
                        _powerSupplierDic[channel].Current = 0;
                    }
                }
                else if (startAddress == 0x0101)
                {
                    UpdateChannelCurrent(flag,channel, command, startAddress, value);
                }
                else if (startAddress == POWER_CONTROL_ADDRESS)
                {
                    UpdateChannelPowerControl(flag, channel, command, startAddress, data[11]);
                }
                else if(startAddress== 0x0111)
                {
                    UpdateChannelRunModel(flag, channel, command, startAddress, data[11]);
                }
                else
                {
                    byte[] errorByt = CreateError(flag, channel, command, 03);
                    OnWriteMessage(errorByt);
                    return;
                }
            }
            else if(command==0x10) //写多个寄存器
            {
                short startAddress = byteTransform.TransInt16(data, 8);
                short length = byteTransform.TransInt16(data, 10);
                if (startAddress == STEP_PERIOD_ADDRESS)
                {
                    _powerSupplierDatas.Clear();
                    int listCount = length / 6;
                    for(int i=0;i
        /// 可用性
        /// 
        private bool _enabled;
        public short VoltageSetting { get { return _voltageSetting; } set { _voltageSetting = value; } }
        public short CurrentSetting { get { return _currentSetting; } set { _currentSetting = value;  } }
        public byte OutputSwitchControl { get { return _outputSwitchControl; } set { _outputSwitchControl = value; } }
        public int Voltage { get { return _voltage; } set { _voltage = value;  } }
        public int Current { get { return _current; } set { _current = value;  } }
        public short PowerStatus { get { return _powerStatus; } set { _powerStatus = value; } }
        public short PowerControl { get { return _powerControl; } set { _powerControl = value; } }
        public short RunModel { get { return _runModel; } set { _runModel = value; } }
        public bool Enabled { get { return _enabled; } set { _enabled = value; } }
    }
    public class PowerSupplierStepPeriodData 
    {
        #region 内部变量
        private double _voltage;
        private double _current;
        private ushort _hour;
        private ushort _minute;
        private ushort _second;
        private ushort _microsecond;
        #endregion
        #region 属性
        public double Voltage { get { return _voltage; } set { _voltage = value;  } }
        public double Current { get { return _current; } set { _current = value; } }
        public ushort Hour { get { return _hour; } set { _hour = value; } }
        public ushort Minute { get { return _minute; } set { _minute = value; } }
        public ushort Second { get { return _second; } set { _second = value; } }
        public ushort Microsecond { get { return _microsecond; } set { _microsecond = value; } }
        #endregion
    }
}