using BO.Utils;
using BWP.WinFormControl;
using Forks.JsonRpc.Client;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ButcherManageClient
{
  public partial class Login : Form
  {
    bool rpcFacadeInited = false;

    void IniteRpcFacade()
    {
      if (rpcFacadeInited)
        return;
      if (string.IsNullOrEmpty(ButcherAppContext.Context.UrlConfig.ServerUrl))
        throw new Exception("请先设置服务器地址");
      RpcFacade.Init(ButcherAppContext.Context.UrlConfig.ServerUrl, "B3ButcherManageClient");
      rpcFacadeInited = true;
    }

    public Login()
    {
      InitializeComponent();
      userNameTxt.Text = ButcherAppContext.Context.UserConfig.UserName;
      pwdTxt.Text = "123";
    }

    private void settingBtn_Click(object sender, EventArgs e)
    {
      var f = new SettingForm(rpcFacadeInited);
      f.ShowDialog();
    }

    private async void loginBtn_Click(object sender, EventArgs e)
    {
      var username = userNameTxt.Text.Trim();
      var pwd = pwdTxt.Text;
      if (string.IsNullOrEmpty(username))
        throw new Exception("请输入用户名");
      IniteRpcFacade();
      ButcherAppContext.Context.UserConfig.PWD = pwd;
      if (LoginRpcUtil.TestConnection(1000))
      {
        await Task.Factory.StartNew(() => RpcFacade.Login(username, pwd));
        LoginRpcUtil.FillUserEmpInfo(username, ButcherAppContext.Context.UserConfig);
        ButcherAppContext.Context.Save();
        ButcherAppContext.Context.UserConfig.Connection = true;
      }
      else
      {
        if (ButcherAppContext.Context.UserConfig.Role != "定级员")
          throw new Exception("无法连接到服务器");
        if (username != ButcherAppContext.Context.UserConfig.UserName)
          throw new Exception("离线状态请保持与上次用户名一致");
        ButcherAppContext.Context.UserConfig.Connection = false;
      }
      var form = AfterLoginUtil.CreateForm(ButcherAppContext.Context.UserConfig.Role);
//      var form = AfterLoginUtil.CreateForm("配货员");
      if (form == null)
        throw new Exception("权限不符");
      form.FormClosing += delegate { SubFormClosing(); };
      form.Show();
      Hide();
    }

    void SubFormClosing()
    {
      foreach (Form form in Application.OpenForms)
      {
        if (form is Login)
        {
          form.Show();
          return;
        }
      }
    }

    private void closeBtn_Click(object sender, EventArgs e)
    {
      Application.Exit();
    }

    private void userNameTxt_Click(object sender, EventArgs e)
    {
      IniteRpcFacade();
      var keyBoard = new NumberPad();
      if (keyBoard.ShowDialog() == true)
      {
        string errorInfo;
        userNameTxt.Text = LoginRpcUtil.GetUserNameByCode(keyBoard.Result, out errorInfo);
        if (string.IsNullOrEmpty(userNameTxt.Text))
          throw new Exception("工号输入错误");
        if (!string.IsNullOrEmpty(errorInfo))
          MessageBox.Show(errorInfo);
      }
    }

    private void pwdTxt_Click(object sender, EventArgs e)
    {
      var keyBoard = new VirtualKeyPad();
      if (keyBoard.ShowDialog() == true)
        pwdTxt.Text = keyBoard.Result;
    }

    const string serUri = "http://172.28.1.194:7799/AutoUpdate/ClientVersion.xml";
    const string puKey = "c756e02cedb42a33f78091a466411bde8447d854";
    private void AutoUpdate()
    {
      if (!File.Exists("AutoUpdate.exe"))
        return;
      var versionInfo = new ClientVersion();
      if (File.Exists("ClientVersion.xml"))
        versionInfo = XmlUtil.DeserializeFromFile<ClientVersion>();
      if (string.IsNullOrEmpty(versionInfo.ServerUrl))
        versionInfo.ServerUrl = serUri;

      HttpWebRequest req = (HttpWebRequest)WebRequest.Create(versionInfo.ServerUrl);
      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)
        return;

      System.Diagnostics.Process.Start(Path.Combine(Application.StartupPath, "AutoUpdate.exe"), puKey);
      Application.Exit();
    }

    private void Login_Load(object sender, EventArgs e)
    {
      AutoUpdate();
    }
  }
}
