using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Project._Common
{
    public partial class fUserList : FCOMMON.fBase
    {
        public fUserList()
        {
            InitializeComponent();
            this.dsMSSQL.Users.TableNewRow += Users_TableNewRow;
            this.FormClosed += __Closed;
            
        }

        void __Closed(object sender, FormClosedEventArgs e)
        {
            var form = this as Form;
            Pub.SetFormStatus(ref form, this.Name, false);
        }

        void Users_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["wuid"] = FCOMMON.info.Login.no;
            e.Row["wdate"] = DateTime.Now;
            e.Row["password"] = Pub.MakePasswordEnc("0");
            e.Row["level"] = 1;
            e.Row["dept"] = cmbdept.Text;
        }

        private void __Load(object sender, EventArgs e)
        {
            var form = this as Form;
            Pub.SetFormStatus(ref form, this.Name, true);
            this.Show();
            Application.DoEvents();

            this.cmbdept.Text = FCOMMON.info.Login.dept;

            //if (FCOMMON.info.Login.level > 4)
            //{
            //    this.dvc_id.Visible = true;
            //    this.btDevel.Visible = true;
            //    this.dv1.EditMode = DataGridViewEditMode.EditOnKeystrokeOrF2;
            //}
            //else
            //{
            //    this.dv1.EditMode = DataGridViewEditMode.EditProgrammatically;
            //    this.dv1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            //    this.btDevel.Visible = true;
            //    this.textBox1.Enabled = false;
            //    this.dvc_id.Visible = true;
            //    this.dvc_level.Visible = false;
            //    this.usersBindingNavigatorSaveItem.Enabled = false;
            //    this.bindingNavigatorAddNewItem.Enabled = false;
            //    this.bindingNavigatorDeleteItem.Enabled = false;

            //}

            //부서목록 업데이트
            var db = new EEEntitiesMain();
            var GrpList = db.UserGroup.Where(t => t.gcode != null && t.permission != null && t.gcode != "" && t.permission > 0);

            //var tagrp = new dsMSSQLTableAdapters.UserGroupTableAdapter();
            //var grplist = tagrp.GetData();

            this.cmbdept.Items.Clear();

            //var deptList = FCOMMON.DBM.getGroupList("dept", "users");
            foreach (var item in GrpList)
                this.cmbdept.Items.Add(item.dept);

            this.cmbdept.Text = FCOMMON.info.Login.dept;
            btRef.PerformClick();

            fpSpread1.EditMode = false;
            

        }


        private void iDChangeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsMSSQL.UsersRow;

            var f = new fNewID(dr.id);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                var newid = f.tbIDN.Text.Trim();
                if (this.dsMSSQL.Users.Select("id='" + newid + "'").Length != 0)
                {
                    Util.MsgE("Exist id - error");
                    return;
                }
                else
                {
                    this.Validate();
                    this.bs.EndEdit();
                    dr.id = newid;
                    dr.EndEdit();
                    this.bs.EndEdit();
                }
            }
        }

        private void passwordChangeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsMSSQL.UsersRow;
            var currentPassword = dr.password;

            _Common.fNewPassword f = new fNewPassword(dr.id);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                var encpassO = Pub.MakePasswordEnc(f.tbPassO.Text);
                var encpassN = Pub.MakePasswordEnc(f.tbPass1.Text);
                if (currentPassword != encpassO)
                {
                    Util.MsgE("Old password error");
                    return;
                }
                else
                {
                    this.Validate();
                    this.bs.EndEdit();
                    dr.password = encpassN;
                    dr.EndEdit();
                    this.bs.EndEdit();
                }
            }
        }

        private void mailToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsMSSQL.UsersRow;
            if (dr.email.isEmpty()) return;
            string cmd = "mailto:" + dr.email;
            Util.RunExplorer(cmd);
        }

        private void 한글이름분리ToolStripMenuItem_Click(object sender, EventArgs e)
        {

            foreach (dsMSSQL.UsersRow dr in this.dsMSSQL.Users.Rows)
            {
                var name = dr.name;
                var newname = name.Split(' ')[0];
                dr.name = newname;
                dr.EndEdit();
            }
        }

        private void btRef_Click(object sender, EventArgs e)
        {
            RefreshList();


        }

        void RefreshList()
        {
            //read data
            if (tbProcess.Text.Trim() == "") tbProcess.Text = "%";
            this.dsMSSQL.Users.Clear();

            //var db = new EEEntitiesMain();
            //IQueryable<vGroupUser> userlist = null; // db.vGroupUser.Where(t => t.dept == this.cmbdept.Text && t.processs.Contains(tbProcess.Text.Trim())).ToList();
            //if (tbProcess.Text.Trim() != "" && tbProcess.Text.Trim() != "%")
            //    userlist = db.vGroupUser.Where(t => t.dept == this.cmbdept.Text && t.processs.Contains(tbProcess.Text.Trim()));
            //else
            //    userlist = db.vGroupUser.Where(t => t.dept == this.cmbdept.Text);

            //var ll = userlist.ToArray();

            //this.bs.DataSource = userlist;


            this.ta.Fill(this.dsMSSQL.vGroupUser, FCOMMON.info.Login.gcode, tbProcess.Text.Trim());
            this.dsMSSQL.Users.AcceptChanges();
            this.bs.Sort = "useuserstate desc,usejobreport desc";
        }
        private void autoResizeColumnToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e)
        {
            //삭제
        }

        private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
        {
            //추가
            var f = new fAddNewUser(this.cmbdept.Text.Trim(),string.Empty);
            if (f.ShowDialog() == DialogResult.OK)
            {
                RefreshList();
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            try
            {
                this.Validate();
                this.bs.EndEdit();
                var cnt = this.ta.Update(this.dsMSSQL.vGroupUser);
                if (cnt < 1)
                {
                    FCOMMON.Util.MsgE("저장된 자료가 없습니다");
                }
                else
                {
                    FCOMMON.Util.MsgI($"{cnt} 건의 자료가 추가/변경/삭제 되었습니다");
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            //추가
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsMSSQL.vGroupUserRow;


            var f = new fAddNewUser(this.cmbdept.Text.Trim(),dr.id);
            if (f.ShowDialog() == DialogResult.OK)
            {
                RefreshList();
            }
        }
    }
}
