using HandyControl.Controls;
using HandyControl.Tools.Extension;
using Microsoft.Win32;
using Ping9719.WpfEx.Mvvm;
using QRCoder;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media.Imaging;
using WCS.Model;
using 智慧物流软件系统.Api;
using 智慧物流软件系统.Views.Controls;
using static System.Net.WebRequestMethods;

namespace 智慧物流软件系统.ViewModel
{
    public class SetViewModel : BindableBase
    {
        public SetViewModel()
        {
            IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());

            IPList = host.AddressList
                 .Where(ipAddress => ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork && !IPAddress.IsLoopback(ipAddress))
                 .Select(t => t.ToString()).ToList();
            if (IPList != null && IPList.Count > 0)
            { 
                SelectedIP = IPList[0];
            }
        }


        private List<int> SaveLoginCountData_ = new List<int> { 3, 5, 7, 10 };
        //记忆最大数量下拉框
        public List<int> SaveLoginCountData { get => SaveLoginCountData_; set { SetProperty(ref SaveLoginCountData_, value); } }

        private Dictionary<int, string> LogTimeData_ = new Dictionary<int, string>()
        {
            { 30,"一月"},{ 91,"三月"},{ 182,"半年"},{ 365,"一年"},{ 1095,"三年"},{ -1,"永久"},
        };
        //日志缓存时间下拉框
        public Dictionary<int, string> LogTimeData { get => LogTimeData_; set { SetProperty(ref LogTimeData_, value); } }


        #region 页面输入信息
        private List<string> ipList;
        public List<string> IPList
        {
            get => ipList;
            set { SetProperty(ref ipList, value); }
        }

        private string selectedIP;
        public string SelectedIP
        {
            get => selectedIP;
            set { SetProperty(ref selectedIP, value); }
        }



        private List<string> scannerComList;
        public List<string> ScannerComList
        {
            get { return scannerComList; }
            set
            {
                SetProperty(ref scannerComList, value);
            }
        }

        private string selectedScannerCom;
        public string SelectedScannerCom
        {
            get { return selectedScannerCom; }
            set
            {
                SetProperty(ref selectedScannerCom, value);
            }
        }


        private List<string> comList;
        public List<string> COMList
        {
            get { return comList; }
            set
            {
                SetProperty(ref comList, value);
            }
        }

        private string selectedCOM;
        public string SelectedCOM
        {
            get { return selectedCOM; }
            set
            {
                SetProperty(ref selectedCOM, value);
            }
        }




        private bool Powerboot_;
        public bool Powerboot { get => Powerboot_; set { SetProperty(ref Powerboot_, value); } }

        private bool StartupFull_;
        public bool StartupFull { get => StartupFull_; set { SetProperty(ref StartupFull_, value); } }

        private bool IsSaveLogin_;
        public bool IsSaveLogin { get => IsSaveLogin_; set { SetProperty(ref IsSaveLogin_, value); } }

        private int SaveLoginCount_;
        public int SaveLoginCount { get => SaveLoginCount_; set { SetProperty(ref SaveLoginCount_, value); } }

        private int SaveLogDay_;
        public int SaveLogDay { get => SaveLogDay_; set { SetProperty(ref SaveLogDay_, value); } }
        #endregion

        /// <summary>
        /// 刷新界面
        /// </summary>
        public void Update()
        {
            #region 加载配置项
            try
            {
                LocalFile.UpdateConfig();
                ScannerComList = LocalFile.Config.ScannerComList;
                Powerboot = LocalFile.Config.Sys.Powerboot;
                StartupFull = LocalFile.Config.Sys.StartupFull;
                IsSaveLogin = LocalFile.Config.Sys.IsSaveLogin;
                SaveLoginCount = LocalFile.Config.Sys.SaveLoginCount;
                SaveLogDay = LocalFile.Config.Sys.SaveLogDay;
            }
            catch (Exception ex)
            {
                Growl.Info($"获取配置失败。{ex.Message}");
            }
            #endregion

            #region 加载串口列表
            RefreshCOMList();
            #endregion
        }

        public ICommand SaveCommand { get => new DelegateCommand(Save); }
        /// <summary>
        /// 保存
        /// </summary>
        public void Save()
        {
            try
            {
                LocalFile.Config.Sys.Powerboot = Powerboot;
                LocalFile.Config.Sys.StartupFull = StartupFull;
                LocalFile.Config.Sys.IsSaveLogin = IsSaveLogin;
                LocalFile.Config.Sys.SaveLoginCount = SaveLoginCount;
                LocalFile.Config.Sys.SaveLogDay = SaveLogDay;
                LocalFile.Config.ScannerComList = ScannerComList;
                LocalFile.SaveConfig();
                Growl.Success($"保存成功。");

                RunPowerboot(Powerboot);
            }
            catch (Exception ex)
            {
                LocalFile.UpdateConfig();
                Growl.Error($"保存失败。{ex.Message}");
            }
        }

        private void RunPowerboot(bool isPowerboot)
        {
            try
            {
                if (isPowerboot)
                {
                    RegistryKey rgkRun = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                    if (rgkRun == null)
                        rgkRun = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");

                    rgkRun.SetValue(Path.GetFileNameWithoutExtension(LocalFile.AppName), "\"" + Path.Combine(LocalFile.AppDir, LocalFile.AppName) + "\"");
                }
                else
                {
                    RegistryKey rgkRun = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                    if (rgkRun == null)
                        rgkRun = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");

                    rgkRun.DeleteValue(Path.GetFileNameWithoutExtension(LocalFile.AppName), false);
                }
            }
            catch (Exception ex)
            {
                Logs.Write(ex);
            }
        }


        public ICommand AddCOMCommand { get => new DelegateCommand(AddCOM); }
        public void AddCOM()
        {
            //是否已选择COM号
            if (SelectedCOM == null)
            {
                Growl.Warning("请选择串口！");
                return;
            }
            //列表中是否存在
            var isExsist = ScannerComList.Where(t => t == SelectedCOM).Any();
            if (isExsist)
            {
                Growl.Warning($"已存在扫码枪{SelectedCOM}！");
                return;
            }
            //添加
            ScannerComList.Add(SelectedCOM);
            ScannerComList = ScannerComList.ToList();
        }

        public ICommand DeleteCOMCommand { get => new DelegateCommand(DeleteCOM); }
        public void DeleteCOM()
        {
            //是否已选择COM号
            if (SelectedScannerCom == null)
            {
                Growl.Warning("请在下方选择串口！");
                return;
            }

            ScannerComList.RemoveAll(t => t == SelectedScannerCom);
            ScannerComList = ScannerComList.ToList();
        }

        public ICommand RefreshCOMListCommand { get => new DelegateCommand(RefreshCOMList); }
        public void RefreshCOMList()
        {
            try
            {
                COMList = SerialPort.GetPortNames().ToList();
            }
            catch
            {
            }
        }


        public ICommand AppQRCodeCommand { get => new DelegateCommand(AppQRCode); }
        public void AppQRCode()
        {
            try
            {
                #region 获取最新版App名称
                var Result = ApiHelp.GetDataFromHttp<ResponseCommon>(LocalFile.Config.ApiIpHost + "fileDownload/getLatestAppName", null, "GET");
                if (Result != null && Result.Code == 200)
                {
                    //拼凑url
                    var downLoadUrl = $"http://{SelectedIP}:8888/" + $"fileDownload/downloadApp?fileName={Result.Data}";
                    //生成二维码
                    var qrCodeImage = GenerateQRCode(downLoadUrl);
                    //展示二维码
                    Dialog.Show(new ImageDialog(qrCodeImage));

                }
                else if (Result != null)
                {
                    Growl.Warning(Result.Message);
                }
                else
                {
                    Growl.Warning("调用接口失败！");
                }
                #endregion
            }
            catch
            {
            }
        }

        public BitmapImage GenerateQRCode(string data)
        {
            QRCodeGenerator qrGenerator = new QRCodeGenerator();
            QRCodeData qrCodeData = qrGenerator.CreateQrCode(data, QRCodeGenerator.ECCLevel.Q);
            QRCode qrCode = new QRCode(qrCodeData);
            Bitmap qrCodeImage = qrCode.GetGraphic(20, Color.Black, Color.White, true);
            // 将System.Drawing.Bitmap转换为System.Windows.Media.Imaging.BitmapImage  
            using (var memoryStream = new MemoryStream())
            {
                // 假设Bitmap的Save方法支持Png格式（通常是这样）  
                qrCodeImage.Save(memoryStream, ImageFormat.Png);
                memoryStream.Position = 0;
                var bitmapImage = new BitmapImage();
                bitmapImage.BeginInit();
                bitmapImage.StreamSource = memoryStream;
                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapImage.EndInit();

                // 返回BitmapImage  
                return bitmapImage;
            }
        }
    }
}
