using System;
using System.IO;
using System.Management;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Input;
using XHWK.WKTool.DAL;

namespace XHWK.WKTool
{
    /// <summary>
    /// KeyVerification.xaml 的交互逻辑
    /// </summary>
    /*
     输入code 调认证服务，成功跳登录 并且调用添加历史接口，失败继续输code
         */
    public partial class KeyVerification
    {
        private readonly XHApi _registerController = new XHApi();
        private int _serverReturnCode;

        public KeyVerification()
        {
            InitializeComponent();
            Topmost = true;
            WindowStartupLocation = WindowStartupLocation.CenterScreen;

            Console.WriteLine(@"初始化KeyVerification");
        }

        private void Window_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
        {
            DragMove();
        }

        private void btnEnd_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(TxbKey.Text))
            {
                MessageWindow.Show("密匙未输入");
                return;
            }

            _projectcode = TxbKey.Text.Trim();
            if (_projectcode.Length > 8)
            {
                MessageWindow.Show("密匙输入过长");
                TxbKey.Text = _projectcode.Substring(0, 8);
                return;
            }
            App.BackgroundWorkerHelper.RunWorkerAsync(InvokeActivationAddServering, InvokeActivationAddServerCompate);
        }

        private string _projectcode = string.Empty;

        /// <summary>
        /// 认证服务-调用
        /// </summary>
        /// <returns>
        /// </returns>
        private object InvokeActivationAddServering()
        {
            string device = "pcwk";
            string mac = GetMacAddress();
            _serverReturnCode = _registerController.ActivationAdd(mac, device, _projectcode);
            return App.ServerMsg;
        }

        /// <summary>
        /// 认证服务-返回结果
        /// </summary>
        /// <returns>
        /// </returns>
        public void InvokeActivationAddServerCompate(object obj)
        {
            if (_serverReturnCode == 0)
            {
                MessageWindow.Show("产品激活成功");
                App.BackgroundWorkerHelper.RunWorkerAsync(InvokeActivationAddHistoryServering, InvokeActivationAddHistoryServerCompate);
                Dispatcher.Invoke
                (
                    () =>
                    {
                        Hide();
                        CreateAMicroLessonWindow win = new CreateAMicroLessonWindow();
                        //win.Topmost = true;
                        win.Show();
                        Thread.Sleep(200);
                        Close();
                    }
                );
            }
            else
            {
                MessageWindow.Show(App.ServerMsg);
            }
        }

        /// <summary>
        /// 激活信息--添加激活历史-调用
        /// </summary>
        /// <returns>
        /// </returns>
        private object InvokeActivationAddHistoryServering()
        {
            _serverReturnCode = _registerController.ActivationAddHistory();
            return App.ServerMsg;
        }

        /// <summary>
        /// 激活信息--添加激活历史-返回结果
        /// </summary>
        /// <returns>
        /// </returns>
        public void InvokeActivationAddHistoryServerCompate(object obj)
        {
            if (!Directory.Exists(App.DataPath))
            {
                Directory.CreateDirectory(App.DataPath);
            }
            string applicationData = App.DataPath + "signatureTime.txt";
            string currentTime = DateTime.Now.ToLongDateString(); //当前时间
            File.WriteAllText(applicationData, currentTime, Encoding.Default); //存放签名验证日期
        }

        /// <summary>
        /// 获取本机MAC地址
        /// </summary>
        /// <returns>
        /// 本机MAC地址
        /// </returns>
        public static string GetMacAddress()
        {
            try
            {
                string strMac = string.Empty;
                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (var o in moc)
                {
                    var mo = (ManagementObject)o;
                    if ((bool)mo["IPEnabled"])
                    {
                        strMac = mo["MacAddress"].ToString();
                    }
                }

                return strMac;
            }
            catch
            {
                return "unknown";
            }
        }

        private void close_click(object sender, RoutedEventArgs e)
        {
            CloseAction();
        }

        private void CloseAction()
        {
            App.myloading.Show();
            new Thread(o => { Dispatcher.Invoke(() => { Environment.Exit(0); }); }).Start();
        }
    }
}
