using DynStatDisk.App.Com;
using DynStatDisk.App.Model;
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;

namespace DynStatDisk.App
{
    public partial class FrmUserManage : Form
    {
        private string CurrentMachineName = string.Empty;

        private string CurrentUserLevel = "用户";

        public FrmUserManage(string Level)
        {
            InitializeComponent();
            CurrentUserLevel = Level;
        }

        //单例模式
        private static FrmUserManage frm = null;
        public static FrmUserManage CreateInstrance(string Level)
        {
            if (frm == null || frm.IsDisposed)
            {
                frm = new FrmUserManage(Level);
            }
            return frm;
        }

        //FSQL实例
        //static IFreeSql Fsql;
        private List<TbUser> InitialLoadList = new List<TbUser>();
        private long SelectedId;

        /// <summary>
        /// 实例化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmUserManage_Load(object sender, EventArgs e)
        {
            if (ConfigHelper.GetValue("Location") == "KP")
            {
                CurrentMachineName = "动静盘安装-KP";
            }
            else
            {
                CurrentMachineName = "动静盘安装-G";
            }

            //获取程序的配置信息
            var SqlCon = ConfigHelper.GetValue("connecting");

            //Fsql = new FreeSql.FreeSqlBuilder()
            //         .UseConnectionString(FreeSql.DataType.SqlServer, SqlCon)
            //         .UseAutoSyncStructure(true) //自动同步实体结构到数据库
            //         .Build(); //请务必定义成 Singleton 单例模式

            LoadComboxBoxData();
            listView1.Columns.Clear();
            LoadListView1Column();
            LoadData();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtName.Text.Trim()) &&
                !string.IsNullOrEmpty(txtPwd.Text.Trim()) &&
                !string.IsNullOrEmpty(cbxLevel.SelectedItem.ToString().Trim()))
            {
                var ReturnData = FSqlContext.FDb.Insert<TbUser>(
                    new TbUser()
                    {
                        UserName = txtName.Text.Trim(),
                        Password = txtPwd.Text.Trim(),
                        AccessLevel = cbxLevel.SelectedItem.ToString().Trim(),
                        MachineName = CurrentMachineName
                    }
                    ).ExecuteInserted();

                LoadData();
            }
            else
            {
                MessageBox.Show("有空的数据存在", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (CurrentUserLevel == "管理员")
            {
                FSqlContext.FDb.Update<TbUser>()
                   .Set(a => a.UserName, txtName.Text.Trim())
                   .Set(a => a.Password, txtPwd.Text.Trim())
                   .Set(a => a.AccessLevel, cbxLevel.SelectedItem.ToString().Trim())
                   .Where(a => a.Id == SelectedId)
                   .ExecuteAffrows();

                LoadData();
            }
            else
            {
                MessageBox.Show("你没有权限编辑！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (DialogResult.OK == MessageBox.Show("你确定要删除当前选中的数据行？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information))
            {
                FSqlContext.FDb.Delete<TbUser>(SelectedId).ExecuteAffrows();

                LoadData();
            }
        }

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


        private void LoadListView1Column()
        {
            ColumnHeader h0 = new ColumnHeader();
            ColumnHeader h1 = new ColumnHeader();
            ColumnHeader h2 = new ColumnHeader();
            ColumnHeader h3 = new ColumnHeader();
            ColumnHeader h4 = new ColumnHeader();
            ColumnHeader h5 = new ColumnHeader();
            ColumnHeader h6 = new ColumnHeader();
            ColumnHeader h7 = new ColumnHeader();
            ColumnHeader h8 = new ColumnHeader();
            ColumnHeader h9 = new ColumnHeader();
            ColumnHeader h10 = new ColumnHeader();
            ColumnHeader h11 = new ColumnHeader();
            ColumnHeader h12 = new ColumnHeader();
            ColumnHeader h13 = new ColumnHeader();

            h1.TextAlign = HorizontalAlignment.Center;
            h2.TextAlign = HorizontalAlignment.Center;
            h3.TextAlign = HorizontalAlignment.Center;
            h4.TextAlign = HorizontalAlignment.Center;
            h5.TextAlign = HorizontalAlignment.Center;
            h6.TextAlign = HorizontalAlignment.Center;
            h7.TextAlign = HorizontalAlignment.Center;
            h8.TextAlign = HorizontalAlignment.Center;
            h9.TextAlign = HorizontalAlignment.Center;
            h10.TextAlign = HorizontalAlignment.Center;
            h11.TextAlign = HorizontalAlignment.Center;
            h12.TextAlign = HorizontalAlignment.Center;
            h13.TextAlign = HorizontalAlignment.Center;

            h0.Width = 10;
            h1.Width = 200;
            h2.Width = 200;
            h3.Width = 120;
            h4.Width = 160;
            h5.Width = 0;
            h6.Width = 100;
            h7.Width = 100;
            h8.Width = 70;
            h9.Width = 40;
            h10.Width = 100;
            h11.Width = 100;
            h12.Width = 100;
            h13.Width = 0;

            h0.Text = "";
            h1.Text = "用户名";
            h2.Text = "密码";
            h3.Text = "级别";
            h4.Text = "创建时间";
            h5.Text = "";
            h6.Text = "活塞精加工号长度";
            h7.Text = "活塞整框个数";
            h8.Text = "曲轴精加工号长度";
            h9.Text = "曲轴整框个数";
            h10.Text = "活塞油沟";
            h11.Text = "吸油管压入";
            h12.Text = "创建时间";
            h13.Text = "";
            //h14.Text = "";

            listView1.Columns.AddRange(new ColumnHeader[] { h0, h1, h2, h3, h4, h5 });
            listView1.View = View.Details;
        }

        private void InsertlistView1Result(long guid, string UserName, string Pwd, string Level, DateTime dateTime)
        {
            ListViewItem lvi = new ListViewItem();
            lvi.ImageIndex = 0;
            lvi.Text = "";
            lvi.SubItems.Add(UserName.ToString());
            lvi.SubItems.Add(Pwd.ToString());
            lvi.SubItems.Add(Level.ToString());
            lvi.SubItems.Add(dateTime.ToString("yyyy-MM-dd HH:mm:ss"));
            lvi.SubItems.Add(guid.ToString());
            this.listView1.Items.Add(lvi);
        }

        private void LoadData()
        {
            listView1.Items.Clear();
            //InitialLoadList.Clear();
            //加载数据
            if (CurrentUserLevel == "管理员")
            {
                InitialLoadList = FSqlContext.FDb.Select<TbUser>().Where(a => a.MachineName == CurrentMachineName).ToList();
            }
            else
            {
                InitialLoadList = FSqlContext.FDb.Select<TbUser>().Where(a => a.MachineName == CurrentMachineName && a.AccessLevel == CurrentUserLevel).ToList();
            }

            if (InitialLoadList.Count > 0)
            {
                var data = InitialLoadList.OrderBy(a => a.CreateTime).ToList();
                foreach (var item in data)
                {
                    InsertlistView1Result(item.Id,
                        item.UserName,
                        item.Password,
                        item.AccessLevel,
                        item.CreateTime
                      );
                }

            }
        }


        private void LoadComboxBoxData()
        {
            this.cbxLevel.Items.Clear();

            this.cbxLevel.Items.Add("用户");//赋值
            this.cbxLevel.SelectedIndex = 0;//设置下标

            this.cbxLevel.Items.Add("管理员");//赋值
            this.cbxLevel.SelectedIndex = 1;//下标

            this.cbxLevel.SelectedIndex = 1;//默认显示LHK

        }

        private void listView1_SelectedIndexChanged_1(object sender, EventArgs e)
        {
            if (listView1.SelectedIndices.Count > 0 && listView1.SelectedIndices != null && listView1.FocusedItem != null)
            {
                txtName.Text = listView1.FocusedItem.SubItems[1].Text;
                txtPwd.Text = listView1.FocusedItem.SubItems[2].Text;
                //cbxLevel.SelectedItem = listView1.FocusedItem.SubItems[3].Text;

                switch (listView1.FocusedItem.SubItems[3].Text)
                {
                    case "用户":
                        cbxLevel.SelectedIndex = 0;
                        break;
                    case "管理员":
                        cbxLevel.SelectedIndex = 1;
                        break;
                    default:
                        break;
                }
                var guid = listView1.FocusedItem.SubItems[5].Text;
                SelectedId = long.Parse(guid);

            }
        }

        //private void btnAddUser_Click(object sender, EventArgs e)
        //{
        //    if (string.IsNullOrEmpty(txtAddUserName.Text))
        //    {
        //        MessageBox.Show("用户名没有输入！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        //        return;
        //    }
        //    if (string.IsNullOrEmpty(txtPassword.Text))
        //    {
        //        MessageBox.Show("密码没有输入！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        //        return;
        //    }

        //    var ListUser = Fsql.Select<TbUser>().Where(a => a.UserName == txtAddUserName.Text.Trim()).ToList();
        //    if (ListUser.Count() == 0)
        //    {
        //        Fsql.Insert<TbUser>(new TbUser()
        //        {
        //            UserName = txtAddUserName.Text.Trim(),
        //            Password = txtPassword.Text.Trim(),
        //            AccessLevel = UserInfo,
        //            MachineName = CurrentMachineName
        //        }).ExecuteAffrows();


        //        MessageBox.Show("添加用户成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

        //        txtAddUserName.Text = "";
        //        txtPassword.Text = "";

        //        this.Close();
        //    }
        //    else
        //    {
        //        MessageBox.Show("当前用户已经存在！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        //    }
        //}

        //private void cbxManager_CheckStateChanged(object sender, EventArgs e)
        //{
        //    if (cbxManager.CheckState == CheckState.Checked)
        //    {
        //        UserInfo = "管理员";
        //    }
        //    else
        //    {
        //        UserInfo = "用户";
        //    }
        //}
    }
}
