using com.hnshituo.core.webapp.vo;
using Common;
using CoreFS.CA06;
using Infragistics.Win;
using Infragistics.Win.UltraWinToolTip;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;

namespace JC_MeasuringSystem
{
    public partial class FrmLogin : Form
    {
        private CoreAppUser userinfo = new CoreAppUser();
        private ComBaseInfoService comBaseInfoService = new ComBaseInfoService(); //基础数服务

        public CoreAppUser UserInfo
        {
            get { return userinfo; }
            set
            {
                if (userinfo == null)
                {
                    userinfo = value;
                }
            }
        }

        public FrmLogin()
        {
            InitializeComponent();
        }

        public Boolean ShowOnlyOnePopUpMsg = false;
        private UltraToolTipInfo toolTipInfo = new UltraToolTipInfo();

        private void FrmLogincs_Load(object sender, EventArgs e)
        {
            //热送磅班组信息载入cmbMeterGroup
            RESTfulResult<List<ComBaseInfo>> rrComMeterGroop = comBaseInfoService.doQueryBaseList(new ComBaseInfo { validFlag = "1", pBaseCode = "001044" });
            if (rrComMeterGroop.Succeed && rrComMeterGroop.Data != null && rrComMeterGroop.Data.Count > 0)
            {
                ValueList vlist2 = new ValueList();
                foreach (var item in rrComMeterGroop.Data)
                {
                    vlist2.ValueListItems.Add(item.baseCode, item.baseName);
                }
                cmbGroup.ValueList = vlist2;
                cmbGroup.SelectedIndex = 0;
            }
            else
            {
                MessageBox.Show("热送磅班组信息载入失败!"+ rrComMeterGroop.Message);
                return;
            }

            //热送磅班次信息载入cmbMeterClass
            RESTfulResult<List<ComBaseInfo>> rrComMeterClass = comBaseInfoService.doQueryBaseList(new ComBaseInfo { validFlag = "1", pBaseCode = "001043" });
            if (rrComMeterClass.Succeed && rrComMeterClass.Data != null && rrComMeterClass.Data.Count > 0)
            {
                ValueList vlist2 = new ValueList();
                foreach (var item in rrComMeterClass.Data)
                {
                    vlist2.ValueListItems.Add(item.baseCode, item.baseName);
                }
                cmbClass.ValueList = vlist2;
                cmbClass.SelectedIndex = 0;
            }
            else
            {
                MessageBox.Show("热送磅班次信息载入失败!" + rrComMeterClass.Message);
                return;
            }
            this.Show();
            Application.DoEvents();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            Login();
        }

        private void txtUserID_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                txtPassword.Focus();
                txtPassword.Select(0, txtPassword.Text.Length);
            }
        }

        private void txtPassword_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                cmbClass.Focus();
            }
        }

        private void Login()
        {
            try
            {
                userinfo.userid = "";
                if (string.IsNullOrEmpty(txtUserID.Text) || string.IsNullOrEmpty(txtPassword.Text))
                {
                    ShowPopUpMsg("请输入用户名和密码。", txtPassword);
                    return;
                }

                if (string.IsNullOrEmpty(cmbClass.Text) || string.IsNullOrEmpty(cmbGroup.Text))
                {
                    ShowPopUpMsg("请选择班次和班组。", cmbGroup);
                    return;
                }

                //2021年9月24日;进行测试的时候，不进行登录校验

                string strPassWord = txtPassword.Text.ToString();
                strPassWord = encryptHASH(strPassWord);
                CoreRESTfulService icore = new CoreRESTfulService(AppConfigCache.serviceUrl, "");
                RESTfulResult<LoginInfo> lginfo = icore.Login(ConfigurationManager.AppSettings["loginUrl"].ToString().Trim(), txtUserID.Text.ToString(), strPassWord);

                if (lginfo == null || !lginfo.Succeed)
                {
                    MessageBox.Show(this, "登陆失败!\n" + lginfo.Message, "错误");
                    return;
                }
                else
                {
                    #region 获取计量类型

                    string sql = @"SELECT base_code baseCode,base_name baseName,memo FROM Com_Base_Info where p_base_code='001006' and valid_Flag='1'";
                    PbModelDbService<List<ComBaseInfo>> pb = new PbModelDbService<List<ComBaseInfo>>();
                    RESTfulResult<List<ComBaseInfo>> rmType = pb.executeSqlDataWf(sql);
                    if (!rmType.Succeed)
                    {
                        MessageBox.Show(this, "登陆失败!\n连接服务端异常！", "错误");
                        return;
                    }

                    #endregion 获取计量类型
                }

                userinfo.ip = IpAddress.getIp;
                userinfo.islogin = "1";
                userinfo.userid = lginfo.Data.User.UserId;
                userinfo.username = lginfo.Data.User.UserName;
                userinfo.userClass = cmbClass.Text.Trim();
                userinfo.userGroup = cmbGroup.Text.Trim();
                /*
                 * 测试的时候用
                userinfo.ip = IpAddress.getIp;
                userinfo.islogin = "1";
                userinfo.userid = "890997005575393280";
                userinfo.username = "yxd";
                userinfo.userClass = cmbClass.Text.Trim();
                userinfo.userGroup = cmbGroup.Text.Trim();
                */
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("登陆出现异常!\n" + ex.Message);
                return;
            }
        }

        /// <summary>
        /// HASH加密
        /// </summary>
        /// <param name="strPassWord"></param>
        /// <returns></returns>
        private string encryptHASH(string strPassWord)
        {
            SHA1 sha = new SHA1CryptoServiceProvider();
            UTF8Encoding enc = new UTF8Encoding();
            byte[] bpwd = enc.GetBytes(strPassWord);
            byte[] hpwd = sha.ComputeHash(bpwd);
            StringBuilder sb = new StringBuilder();
            foreach (byte bt in hpwd)
            {
                sb.AppendFormat("{0:x2}", bt);
            }
            string spwd = sb.ToString();
            return spwd;
        }

        public void ShowPopUpMsg(string strMsg, Control control)
        {
            if (control == null) return;

            if (control.InvokeRequired)
            {
                control.Invoke(new Action<string, Control>(ShowPopUpMsg), strMsg, control);
            }
            else
            {
                toolTipInfo.ToolTipText = strMsg;
                toolTipInfo.ToolTipTitle = "";
                //toolTipInfo.ToolTipImage = ToolTipImage.None;

                toolTipInfo.ResetAppearance();
                toolTipInfo.Appearance.BackColor = Color.WhiteSmoke;
                toolTipInfo.Appearance.BackColor2 = Color.Yellow;
                toolTipInfo.Appearance.BackGradientStyle = GradientStyle.Circular;
                toolTipInfo.Appearance.ForeColor = Color.Red;
                toolTipInfo.Appearance.FontData.Bold = DefaultableBoolean.True;
                toolTipInfo.Appearance.FontData.SizeInPoints = 16f;
                toolTipInfo.ToolTipTitleAppearance.ForeColor = Color.Navy;

                Rectangle rect = control.Parent.RectangleToScreen(new Rectangle(control.Location, control.Size));
                rect.Height -= 15;
                rect.Width -= 15;

                Point p = new Point(control.Location.X + control.Size.Width - 5, control.Location.Y + control.Height - 5);
                if (p.Y < Screen.PrimaryScreen.WorkingArea.Height - 100)
                {
                    p.Y = control.Location.Y + 5;
                }

                Point screen_pos = control.Parent.PointToScreen(p);

                int delay_time = strMsg.Length / 3 * 1000;

                ToolTipManager1.AutoPopDelay = delay_time < 30000 ? 30000 : delay_time;
                ToolTipManager1.SetUltraToolTip(this, toolTipInfo);
                if (ShowOnlyOnePopUpMsg)
                {
                    ToolTipManager1.HideToolTip();
                }
                ToolTipManager1.ShowToolTip(this, screen_pos);
            }
        }

        /// <summary>
        /// 跳到登陆按钮时进行提示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLogin_Enter(object sender, EventArgs e)
        {
            //btnLogin
        }
    }
}