using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Windows.Forms;

namespace MesWork
{
    /// <summary>
    /// 登录页面 — 全屏背景图 + 右侧白色登录卡片
    /// </summary>
    public partial class Frm_Login : Form
    {
        /// <summary>
        /// 背景图片缓存
        /// </summary>
        private Image _bgImage;

        public Frm_Login()
        {
            InitializeComponent();
            DoubleBuffered = true;
            LoadBackgroundImage();
            LoadIcon();
        }

        /// <summary>
        /// 加载任务栏图标
        /// </summary>
        private void LoadIcon()
        {
            IconHelper.ApplyIcon(this);
        }

        /// <summary>
        /// 加载背景图片（从 Resources 目录）
        /// </summary>
        private void LoadBackgroundImage()
        {
            try
            {
                string bgPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources", "login_bg.png");
                if (File.Exists(bgPath))
                    _bgImage = Image.FromFile(bgPath);
            }
            catch { /* 图片加载失败时使用渐变背景兜底 */ }
        }

        /// <summary>
        /// 绘制背景：优先使用背景图，否则渐变兜底
        /// </summary>
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            var g = e.Graphics;
            g.SmoothingMode = SmoothingMode.AntiAlias;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            if (_bgImage != null)
            {
                // 全屏铺满背景图
                g.DrawImage(_bgImage, 0, 0, ClientSize.Width, ClientSize.Height);

                // 右侧半透明白色蒙层（让登录卡片区域更清晰）
                using (var overlay = new SolidBrush(Color.FromArgb(180, 255, 255, 255)))
                {
                    g.FillRectangle(overlay, ClientSize.Width / 2, 0, ClientSize.Width / 2, ClientSize.Height);
                }
            }
            else
            {
                // 渐变兜底
                using (var brush = new LinearGradientBrush(
                    ClientRectangle,
                    Color.FromArgb(30, 58, 95),
                    Color.FromArgb(240, 244, 248),
                    LinearGradientMode.Horizontal))
                {
                    g.FillRectangle(brush, ClientRectangle);
                }
            }

            // 底部版本信息（放在右下角白色区域，确保清晰可读）
            using (var font = new Font("微软雅黑", 9F))
            using (var brush = new SolidBrush(Color.FromArgb(160, 120, 120, 120)))
            {
                string ver = "v1.0.0  |  潍柴动力 · 称重数据采集分析管理系统";
                var sz = g.MeasureString(ver, font);
                g.DrawString(ver, font, brush, ClientSize.Width - sz.Width - 20, ClientSize.Height - 36);
            }
        }

        /// <summary>
        /// 窗口大小变化时重新定位登录卡片到右半区中央
        /// </summary>
        protected override void OnResize(EventArgs e)
        {
            base.OnResize(e);
            if (pnl_Card != null)
            {
                // 卡片放在右半区的中心位置
                int rightHalfCenter = ClientSize.Width / 2 + ClientSize.Width / 4;
                pnl_Card.Location = new Point(
                    rightHalfCenter - pnl_Card.Width / 2,
                    (ClientSize.Height - pnl_Card.Height) / 2);
            }
        }

        /// <summary>
        /// 卡片圆角绘制
        /// </summary>
        private void pnl_Card_Paint(object sender, PaintEventArgs e)
        {
            var panel = (Panel)sender;
            int radius = 12;
            var rect = new Rectangle(0, 0, panel.Width - 1, panel.Height - 1);
            using (var path = new GraphicsPath())
            {
                path.AddArc(rect.X, rect.Y, radius * 2, radius * 2, 180, 90);
                path.AddArc(rect.Right - radius * 2, rect.Y, radius * 2, radius * 2, 270, 90);
                path.AddArc(rect.Right - radius * 2, rect.Bottom - radius * 2, radius * 2, radius * 2, 0, 90);
                path.AddArc(rect.X, rect.Bottom - radius * 2, radius * 2, radius * 2, 90, 90);
                path.CloseFigure();
                panel.Region = new Region(path);
            }
        }

        // ====================================================================
        // 登录逻辑
        // ====================================================================

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            if (MesWorkForm.Curr_UserName == "") Application.Exit();
            else DialogResult = DialogResult.Cancel;
        }

        private void btn_Login_Click(object sender, EventArgs e)
        {
            if (txt_LoginID.Text.Trim() == "")
            {
                lbl_Msg.Text = "⚠ 用户名不能为空";
                lbl_Msg.Visible = true;
                return;
            }

            // 调用新的用户管理表登录验证
            var res = User_Login(txt_LoginID.Text.Trim(), txt_userPassword.Text, out string name, out string perm);
            if (res)
            {
                MesWorkForm.Curr_LoginID = txt_LoginID.Text.Trim();
                MesWorkForm.Curr_UserPassWord = txt_userPassword.Text;
                MesWorkForm.Curr_UserName = name;

                B_DB_Opera.LoginState_Save(MesWorkForm.Curr_LoginID, MesWorkForm.Curr_UserName, perm);

                // 记录登录日志
                try { B_DB_Opera.SaveLog_Request(MesWorkForm.Curr_Station, Log_Type.ZK_Login, "", Log_FromAndTo.ZK, Log_FromAndTo.ZK, $"用户[{name}({txt_LoginID.Text.Trim()})]登录系统", out long _); } catch { }

                DialogResult = DialogResult.OK;
            }
            else
            {
                lbl_Msg.Text = "⚠ 登录失败，请检查用户名和密码";
                lbl_Msg.Visible = true;
            }
        }

        /// <summary>
        /// 调用 用户管理_登录验证 SP
        /// </summary>
        private bool User_Login(string userName, string pwd, out string name, out string permission)
        {
            name = "";
            permission = "";
            try
            {
                var sp = "用户管理_登录验证";
                var parms = new System.Data.SqlClient.SqlParameter[]
                {
                    new System.Data.SqlClient.SqlParameter("@用户名", userName),
                    new System.Data.SqlClient.SqlParameter("@密码", pwd)
                };
                SqlOperation.ExecuteStoredProcedure(sp, parms, out System.Data.DataTable dt, out string err);
                if (dt != null && dt.Rows.Count > 0)
                {
                    name = dt.Rows[0]["姓名"].ToString();
                    permission = dt.Rows[0]["权限"].ToString();
                    return true;
                }
            }
            catch (Exception ex)
            {
                MesWorkForm.WriteLog_Info("Login", $"登录异常：{ex.Message}", ex);
            }
            return false;
        }

        /// <summary>
        /// 回车切换焦点：用户名 → 密码
        /// </summary>
        private void txt_LoginID_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) { txt_userPassword.Focus(); e.SuppressKeyPress = true; }
        }

        /// <summary>
        /// 回车触发登录：密码 → 登录
        /// </summary>
        private void txt_userPassword_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) { btn_Login_Click(sender, e); e.SuppressKeyPress = true; }
        }

        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            _bgImage?.Dispose();
            base.OnFormClosed(e);
        }
    }
}
