using DM_Weight.Common;
using DM_Weight.msg;
using DM_Weight.Port;
using DM_Weight.util;
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.Windows;
using System.Xml;
namespace DM_Weight.ViewModels
{
    public class FridgeWindowViewModel : BindableBase, IRegionMemberLifetime, INavigationAware
    {
        //温度区间
        private string _temperatureRange = CommonClass.ReadAppSetting("temperatureRange").ToString();
        public string TemperatureRange
        {
            get => _temperatureRange;
            set
            {
                SetProperty(ref _temperatureRange, value);
                //更新配置文件中冰箱温度区间
                CommonClass.SaveAppSetting("temperatureRange", _temperatureRange);
            }
        }
        //冰箱2温度区间
        private string _temperatureRange2 = CommonClass.ReadAppSetting("temperatureRange2").ToString();
        public string TemperatureRange2
        {
            get => _temperatureRange2;
            set
            {
                SetProperty(ref _temperatureRange2, value);
                //更新配置文件中冰箱温度区间
                CommonClass.SaveAppSetting("temperatureRange2", _temperatureRange2);
            }
        }
        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关;false开
        private bool _fridgeState;
        public bool FridgeState
        {
            get => _fridgeState;
            set => SetProperty(ref _fridgeState, value);
        }
        //报警状态:true关;false开
        private bool _alarmState;
        public bool AlarmState
        {
            get => _alarmState;
            set => SetProperty(ref _alarmState, value);
        }
        //冰箱2状态:true关;false开
        private bool _fridgeState2;
        public bool FridgeState2
        {
            get => _fridgeState2;
            set => SetProperty(ref _fridgeState2, value);
        }
        //冰箱2报警状态:true关;false开
        private bool _alarmState2;
        public bool AlarmState2
        {
            get => _alarmState2;
            set => SetProperty(ref _alarmState2, value);
        }
        private int _defaultLoginMode;//1开0关
        private int _defaultAlarmMode;//1开0关
        private float retTemperature = Convert.ToSingle(ConfigurationManager.AppSettings["temperatureValue"]);
        private PortUtil _portUtil;
        IEventAggregator _eventAggregator;
        public FridgeWindowViewModel(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", "0");
                }
                else
                {
                    await _portUtil.FridegOpen(1);
                    Thread.Sleep(100);
                    CommonClass.SaveAppSetting("FridgeState", "1");
                }
                //冰箱2  发送冰箱使能/失能指令
                if (_fridgeState2)
                {
                    await _portUtil.FridgeOff(2);
                    Thread.Sleep(100);
                    CommonClass.SaveAppSetting("FridgeState2", "0");
                }
                else
                {
                    await _portUtil.FridegOpen(2);
                    Thread.Sleep(100);
                    CommonClass.SaveAppSetting("FridgeState2", "1");
                }
                //}
                //温度报警设定
                //if (AlarmState != _defaultAlarmMode.Equals(1))
                //{
                //发送警报使能/失能指令
                if (_alarmState)
                {
                    await _portUtil.FridgeAlarmOff(1);
                    Thread.Sleep(100);
                    CommonClass.SaveAppSetting("AlarmState", "0");
                }
                else
                {
                    await _portUtil.FridgeAlarmOn(1);
                    Thread.Sleep(100);
                    CommonClass.SaveAppSetting("AlarmState", "1");
                }
                //冰箱2 发送警报使能/失能指令
                if (_alarmState2)
                {
                    await _portUtil.FridgeAlarmOff(2);
                    Thread.Sleep(100);
                    CommonClass.SaveAppSetting("AlarmState2", "0");
                }
                else
                {
                    await _portUtil.FridgeAlarmOn(2);
                    Thread.Sleep(100);
                    CommonClass.SaveAppSetting("AlarmState2", "1");
                }
                //}
                //if (retTemperature != TemperatureValue)
                //{
                //    //设定冰箱温度
                //    await _portUtil.SetFridgeTemperature(TemperatureValue);
                //    CommonClass.SaveAppSetting("temperatureValue", TemperatureValue.ToString());
                //}
                //设定冰箱1温度区间
                string[] range = ConfigurationManager.AppSettings["temperatureRange"].Split('-');
                string[] newRange = TemperatureRange.Split('-');
                if (range.Length >= 2)
                {
                    bool bMix = float.TryParse(range[0], out float Min);
                    bool bMax = float.TryParse(range[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);
                        }
                    }
                }
                //设定冰箱2温度区间
                string[] range2 = ConfigurationManager.AppSettings["temperatureRange2"].Split('-');
                string[] newRange2 = TemperatureRange2.Split('-');
                if (range2.Length >= 2)
                {
                    bool bMix = float.TryParse(range2[0], out float Min);
                    bool bMax = float.TryParse(range2[1], out float Max);
                    if (bMix && bMax)
                    {
                        if (Min != Convert.ToSingle(newRange2[0]))
                        {
                            //设定冰箱温度最小值
                            await _portUtil.FridgeMinSetting(Convert.ToSingle(newRange2[0]), 2);
                            Thread.Sleep(100);
                        }
                        if (Max != Convert.ToSingle(newRange2[1]))
                        {
                            Thread.Sleep(100);
                            //设定冰箱温度最大值
                            await _portUtil.FridgeMaxSetting(Convert.ToSingle(newRange2[1]), 2);
                            Thread.Sleep(100);
                        }
                    }
                }
                _portUtil.FridgeOperate = false;
                AlertMsg alertMsg = new AlertMsg
                {
                    Message = $"保存成功",
                    Type = MsgType.SUCCESS
                };
                _eventAggregator.GetEvent().Publish(alertMsg);
                //_fridgeState = ReadAppSetting("FridgeState").Equals(1);
                //_defaultLoginMode = ReadAppSetting("FridgeState");
                //_defaultAlarmMode = ReadAppSetting("AlarmState");
                //_alarmState = ReadAppSetting("AlarmState").Equals(1);
                //_temperatureRange = CommonClass.ReadAppSetting("temperatureRange");
                //_temperatureValue = Convert.ToSingle(CommonClass.ReadAppSetting("temperatureValue"));
            }
            catch (Exception ex)
            {
                AlertMsg alertMsg = new AlertMsg
                {
                    Message = $"保存异常{ex.ToString}",
                    Type = MsgType.ERROR
                };
                _eventAggregator.GetEvent().Publish(alertMsg);
                _portUtil.FridgeOperate = false;
            }
        }
        public FridgeWindowViewModel()
        {
        }
        //手动实现调用配置的逻辑 规避修改配置文件后不起作用的问题
        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);
            return Convert.ToInt32(node.Attributes["value"].Value);
        }
        public void ConfirmNavigationRequest(NavigationContext navigationContext, Action continuationCallback)
        {
        }
        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            _fridgeState = ReadAppSetting("FridgeState").Equals(0);
            _defaultLoginMode = ReadAppSetting("FridgeState");
            _defaultAlarmMode = ReadAppSetting("AlarmState");
            _alarmState = ReadAppSetting("AlarmState").Equals(0);
            GetTemperature();
        }
        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }
        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
        }
        //public void OnNavigatedTo(NavigationContext navigationContext)
        //{
        //    GetTemperature();
        //}
        //public bool IsNavigationTarget(NavigationContext navigationContext)
        //{
        //    return true;
        //}
        //public void OnNavigatedFrom(NavigationContext navigationContext)
        //{
        //}
        //获取冰箱温度值,如有更改则保存更改
        private async Task GetTemperature()
        {
            //float retT = await _portUtil.GetFridgeTemperature();
        }
    }
}