using Model;
using Permission;
using PlcUiForm;
using Sunny.UI;
using Sunny.UI.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using User = Model.User;
namespace YangjieTester.用户管理
{
    [FormDescriptionAttribute("用户注册")]
    public partial class SignUpForm : PlcBaseForm
    {
        public SignUpForm()
        {
            InitializeComponent();
        }
        private void FormSignIn_Load(object sender, EventArgs e)
        {
            cobLevel.Items.Clear();
            cobLevel.DataSource=new List<PermissionLevel>() {  PermissionLevel.操作工, PermissionLevel.工程师, PermissionLevel.技术员, PermissionLevel.管理员};
            if (cobLevel.Items.Count > 0)
                cobLevel.SelectedIndex = 0;
        }

        bool GetInputUser(out User user)
        {
            string name = txtUsername.Text.Trim();
            string password1 = txtPassword1.Text.Trim();
            string password2 = txtPassword2.Text.Trim();
            var level = (PermissionLevel)cobLevel.SelectedItem;
            if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(password1) && !string.IsNullOrEmpty(password2))
            {
                if (password1.Equals(password2))
                {
                    user = new Model.User(name, password1, level);
                    return true;
                }
            }
            user = null;
            return false;
        }

        private void btnSignUp_Click(object sender, EventArgs e)
        {
            if (GetInputUser(out User user))
            {
                if(user.PermissionLevel>= AppSession.CurrentUser.PermissionLevel)
                {
                    MessageBox.Show($"新注册的用户权限必须低于当前用户权限等级：{AppSession.CurrentUser.PermissionLevel}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if(UserService.RegisterUser(user,out string err))
                {

                    MessageBox.Show("注册成功","",MessageBoxButtons.OK,MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show($"注册失败:{err}","提示",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                }
            }
            else
            {
                MessageBox.Show($"输入信息错误", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}
