using DM_Weight.Common;
using DM_Weight.msg;
using DM_Weight.Port;
using DM_Weight.util;
using log4net;
using log4net.Repository.Hierarchy;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
namespace DM_Weight.ViewModels
{
    public class FridgeOnlyWindowViewModel : BindableBase, IRegionMemberLifetime, INavigationAware
    {
        private readonly ILog logger = LogManager.GetLogger(typeof(FridgeOnlyWindowViewModel));
        //温度区间
        private string _temperatureRange = CommonClass.ReadAppSetting("temperatureRange").ToString();
        public string TemperatureRange
        {
            get => _temperatureRange;
            set
            {
                SetProperty(ref _temperatureRange, value);
            }
        }
        //温度不在范围超时时间
        private string _outRangeTime = CommonClass.ReadAppSetting("OutRangeTime").ToString();
        public string OutRangeTime
        {
            get => _outRangeTime; set
            {
                SetProperty(ref _outRangeTime, value);
            }
        }
        private float defaultValue = Convert.ToSingle(CommonClass.ReadAppSetting("temperatureValue"));
        //温度值
        private float _temperatureValue = Convert.ToSingle(CommonClass.ReadAppSetting("temperatureValue"));
        public float TemperatureValue
        {
            get => _temperatureValue;
            set => SetProperty(ref _temperatureValue, value);
        }
        /// 
        /// 根据冰箱温度控制保存按钮是否可点击
        /// 
        private bool _isInvalid;
        public bool IsInvalid
        {
            get => _isInvalid;
            set
            {
                SetProperty(ref _isInvalid, value);
                BtnIsEnable = !IsInvalid;
            }
        }
        /// 
        /// 根据冰箱温度控制保存按钮是否可用
        /// 
        private bool _btnIsEnable = true;
        public bool BtnIsEnable
        {
            get => _btnIsEnable;
            set => SetProperty(ref _btnIsEnable, value);
        }
        //冰箱状态:true关1;false开0
        private bool _fridgeState;
        public bool FridgeState
        {
            get => _fridgeState;
            set => SetProperty(ref _fridgeState, value);
        }
        //报警状态:true关1;false开0
        private bool _alarmState;
        public bool AlarmState
        {
            get => _alarmState;
            set => SetProperty(ref _alarmState, value);
        }
        private float retTemperature = Convert.ToSingle(ConfigurationManager.AppSettings["temperatureValue"]);
        private PortUtil _portUtil;
        IEventAggregator _eventAggregator;
        public FridgeOnlyWindowViewModel(PortUtil portUtil, IEventAggregator eventAggregator)
        {
            _portUtil = portUtil;
            _eventAggregator = eventAggregator;
        }
        /// 
        /// 保存按钮
        /// 
        public DelegateCommand SaveCommand { get => new DelegateCommand(SaveAction, () => !IsInvalid); }
        public bool KeepAlive => false;
        private async void SaveAction()
        {
            try
            {
                _portUtil.FridgeOperate = true;
                //设置温度值验证不通过则直接返回不保存
                //获取冰箱温度
                //if (_fridgeState != _defaultLoginMode.Equals(1))
                //{
                //    ConfigurationManager.RefreshSection("FridgeState");
                //发送冰箱使能/失能指令
                if (FridgeState)
                {
                    await _portUtil.FridgeOff(1);
                    Thread.Sleep(100);
                    CommonClass.SaveAppSetting("FridgeState", "1");
                    //Configuration _configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    //_configuration.AppSettings.Settings["FridgeState"].Value = "1";
                    //_configuration.Save();
                    //ConfigurationManager.RefreshSection("FridgeState");
                }
                else
                {
                    await _portUtil.FridegOpen(1);
                    Thread.Sleep(100);
                    CommonClass.SaveAppSetting("FridgeState", "0");
                    //Configuration _configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    //_configuration.AppSettings.Settings["FridgeState"].Value = "0";
                    //_configuration.Save();
                    //ConfigurationManager.RefreshSection("FridgeState");
                    //冰箱打开定时获取冰箱温度
                    _eventAggregator.GetEvent().Publish();
                }
                //发送警报使能/失能指令
                if (AlarmState)
                {
                    await _portUtil.FridgeAlarmOff(1);
                    Thread.Sleep(100);
                    CommonClass.SaveAppSetting("AlarmState", "1");
                    //Configuration _configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    //_configuration.AppSettings.Settings["AlarmState"].Value = "1";
                    //_configuration.Save();
                    //ConfigurationManager.RefreshSection("AlarmState");
                }
                else
                {
                    await _portUtil.FridgeAlarmOn(1);
                    Thread.Sleep(100);
                    CommonClass.SaveAppSetting("AlarmState", "0");
                    //Configuration _configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    //_configuration.AppSettings.Settings["AlarmState"].Value = "0";
                    //_configuration.Save();
                    //ConfigurationManager.RefreshSection("AlarmState");
                }
                //设定冰箱1温度区间
                //string[] range = ConfigurationManager.AppSettings["temperatureRange"].Split('-');
                string[] newRange = TemperatureRange.Split('-');
                if (newRange.Length >= 2)
                {
                    bool bMix = float.TryParse(newRange[0], out float Min);
                    bool bMax = float.TryParse(newRange[1], out float Max);
                    if (bMix && bMax)
                    {
                        if (Min != Convert.ToSingle(newRange[0]))
                        {
                            //设定冰箱温度最小值
                            await _portUtil.FridgeMinSetting(Convert.ToSingle(newRange[0]),1);
                            Thread.Sleep(100);
                        }
                        if (Max != Convert.ToSingle(newRange[1]))
                        {
                            Thread.Sleep(100);
                            //设定冰箱温度最大值
                            await _portUtil.FridgeMaxSetting(Convert.ToSingle(newRange[1]), 1);
                            Thread.Sleep(100);
                        }
                    }
                    //Configuration _configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    //_configuration.AppSettings.Settings["TemperatureRange"].Value = c;
                    //_configuration.Save();
                    //ConfigurationManager.RefreshSection("TemperatureRange");
                    CommonClass.SaveAppSetting("TemperatureRange", TemperatureRange);
                }
                //超时时间
                if (OutRangeTime != null)
                {
                    //Configuration _configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    //_configuration.AppSettings.Settings["OutRangeTime"].Value = OutRangeTime;
                    //_configuration.Save();
                    //ConfigurationManager.RefreshSection("OutRangeTime");
                    CommonClass.SaveAppSetting("OutRangeTime", OutRangeTime);
                }
                _portUtil.FridgeOperate = false;
                AlertMsg alertMsg = new AlertMsg
                {
                    Message = $"保存成功",
                    Type = MsgType.SUCCESS
                };
                _eventAggregator.GetEvent().Publish(alertMsg);
            }
            catch (Exception ex)
            {
                AlertMsg alertMsg = new AlertMsg
                {
                    Message = $"保存异常{ex.ToString}",
                    Type = MsgType.ERROR
                };
                _eventAggregator.GetEvent().Publish(alertMsg);
                _portUtil.FridgeOperate = false;
            }
        }
        //手动实现调用配置的逻辑 规避修改配置文件后不起作用的问题
        //public int ReadAppSetting(string key)
        //{
        //    string xPath = "/configuration/appSettings//add[@key='" + key + "']";
        //    XmlDocument doc = new XmlDocument();
        //    string exeFileName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
        //    doc.Load(exeFileName + ".dll.config");
        //    XmlNode node = doc.SelectSingleNode(xPath);
        //    logger.Info($"xPath:{xPath} exeFileName:{exeFileName} ReadAppSetting key:{key} value:{node.Attributes["value"].Value}");
        //    return Convert.ToInt32(node.Attributes["value"].Value);
        //}
        public void ConfirmNavigationRequest(NavigationContext navigationContext, Action continuationCallback)
        {
        }
        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            FridgeState =CommonClass.ReadAppSetting("FridgeState").Equals("1");
            AlarmState = CommonClass.ReadAppSetting("AlarmState").Equals("1");
            GetTemperature();
        }
        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }
        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
        }
        //获取冰箱温度值,如有更改则保存更改
        private async Task GetTemperature()
        {
            //float retT = await _portUtil.GetFridgeTemperature();
        }
    }
}