using ButcherFactory.BO.Utils;
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using WinFormControl;

namespace ButcherFactory.Login
{
  /// <summary>
  /// Login.xaml 的交互逻辑
  /// </summary>
  public partial class Login : Window
  {
    public Login()
    {
      InitializeComponent();
#if DEBUG
      pwdInput.Password = BO.Utils.AppContext.ConnectInfo.ServerMode == 0 ? "123" : "";
#endif

      try
      {
        userNameInput.Text = BO.Utils.AppContext.Worker.Name;
        if (!string.IsNullOrEmpty(BO.Utils.AppContext.Worker.Name))
          pwdInput.Focus();
      }
      catch { }
      this.Loaded += Login_Loaded;
    }

    private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
      this.DragMove();
    }

    private async void LoginBtn_Click(object sender, RoutedEventArgs e)
    {
      try
      {
        loginBtn.IsEnabled = false;
        if (string.IsNullOrEmpty(BO.Utils.AppContext.ConnectInfo.SqlConnection))
          throw new Exception("请设置数据库地址！");
        var username = userNameInput.Text.Trim();
        var pwd = pwdInput.Password;
        if (string.IsNullOrEmpty(username))
          throw new Exception("请输入用户名");
        LoginUtil.InitRpcFacade();
        if (LoginUtil.TestConnection(1000))
        {
          await Task.Factory.StartNew(() => LoginUtil.Login(username, pwd, BO.Utils.AppContext.ConnectInfo.ServerMode));
        }
        else
        {
          if (BO.Utils.AppContext.ConnectInfo.ServerMode == 1)
            throw new Exception("网络错误");
          if (BO.Utils.AppContext.Worker.Name != username || string.Join("", LoginUtil.EncodePwd(pwd)) != string.Join("", BO.Utils.AppContext.Worker.Password))
            throw new Exception("离线时只能使用上次登录信息登录");
        }

        var form = FormUtil.CreateFrom();
        if (form == null)
          throw new Exception("权限不符");
        form.FormClosed += delegate
        {
          this.Show();
        };

        form.Show();
        Hide();
      }
      catch(Exception ex) { throw new Exception (ex.Message); }
      finally
      {
        loginBtn.IsEnabled = true;
      }
    }

    private void ExistBtn_Click(object sender, RoutedEventArgs e)
    {
      App.Current.Shutdown();
    }

    private void UserNameTextBoxClick(object sender, MouseButtonEventArgs e)
    {
      LoginUtil.InitRpcFacade();
      var keyBoard = new NumberPad();
      if (keyBoard.ShowDialog() == true)
      {
        if (!LoginUtil.TestConnection(1000))
        {
          if (string.IsNullOrEmpty(BO.Utils.AppContext.Worker.Name))
            throw new Exception("请检查网络");
          throw new Exception("离线时无法切换用户");
        }
        userNameInput.Text = LoginUtil.GetWorkerNameByCode(keyBoard.Result);
      }
    }

    private void PwdTextBoxClick(object sender, MouseButtonEventArgs e)
    {
      var keyBoard = new VirtualKeyPad();
      if (keyBoard.ShowDialog() == true)
        pwdInput.Password = keyBoard.Result;
    }

    const string serUri = "http://172.28.1.194:7799/AutoUpdate/ClientVersion.xml";
    const string puKey = "c756e02cedb42a33f78091a466411bde8447d854";

    void Login_Loaded(object sender, RoutedEventArgs e)
    {
      if (!File.Exists("ButcherFactory.AutoUpdate.exe"))
        return;
      var versionInfo = new ClientVersion();
      if (File.Exists("ClientVersion.xml"))
      {
        versionInfo = XmlUtil.DeserializeFromFile<ClientVersion>("ClientVersion.xml");
        versionLbl.Text = versionInfo.Version;
      }
      if (string.IsNullOrEmpty(versionInfo.ServerUrl))
        versionInfo.ServerUrl = serUri;

      HttpWebRequest req = (HttpWebRequest)WebRequest.Create(versionInfo.ServerUrl);
      req.Timeout = 5000;
      HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
      if (resp.StatusCode != HttpStatusCode.OK)
        return;

      var down = new System.Net.WebClient();
      var serverVersion = XmlUtil.XmlDeserializeObject<ClientVersion>(down.DownloadString(versionInfo.ServerUrl));
      if (versionInfo.Version != serverVersion.Version)
        updateImg.Visibility = Visibility.Visible;
    }

    private void UpdateBtn_Click(object sender, MouseButtonEventArgs e)
    {
      System.Diagnostics.Process.Start("ButcherFactory.AutoUpdate.exe", puKey);
      App.Current.Shutdown();
    }

    private void SetBtn_Click(object sender, MouseButtonEventArgs e)
    {
      if (!File.Exists("ButcherFactory.Tools.exe"))
        return;
      System.Diagnostics.Process.Start("ButcherFactory.Tools.exe");
    }
  }
}
