using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
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;
            this.KeyDown += (s1, e1) =>
            {
                if (e1.KeyCode == Keys.Escape) this.Close();
            };
            this.tbFind.KeyDown += (s1, e1) =>
            {
                if (e1.KeyCode == Keys.Enter) SearchKey();
            };
        }
        void SearchKey()
        {
            var txt = tbFind.Text.Trim();
            if (txt.isEmpty())
            {
                bs.Filter = "";
                tbFind.BackColor = Color.White;
            }
            else
            {
                var cols = new string[] { "id", "name", "email", "tel" };
                var filter = string.Join(" like '%{0}%' or ", cols) + " like '%{0}%'";
                filter = string.Format(filter, txt);
                try
                {
                    bs.Filter = filter;
                    tbFind.BackColor = Color.Lime;
                }
                catch 
                {
                    bs.Filter = "";
                    tbFind.BackColor = Color.Tomato;
                }
            }
            tbFind.Focus();
            tbFind.SelectAll();
        }

        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)
        {
            EnsureVisibleAndUsableSize();
            var form = this as Form;
            Pub.SetFormStatus(ref form, this.Name, true);
            this.Show();
            Application.DoEvents();

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

            //일반사용자의경우에는 상태를 변경하지 못한다.
            int curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.account));
            btAdd.Enabled = curLevel >= 5;

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


            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;

            //화면좌표문제 복구 - 211221
            if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal;
            if (this.RestoreBounds.X + this.RestoreBounds.Width < 300 && this.RestoreBounds.X < 0)
                this.Location = new Point(0, 0);
        }


        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";
            arDatagridView1.AutoResizeColumns();
        }
        private void autoResizeColumnToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

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

        private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
        {
            Func_add();
        }
        void Func_add()
        {

            //일반사용자의경우에는 상태를 변경하지 못한다.
            int curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.account));
            if (curLevel < 5)
            {
                FCOMMON.Util.MsgE("사용자 등록 권한이 없습니다");
                return;
            }

            //추가
            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)
        {
            Func_Edit();
        }
        void Func_Edit()
        {

            //추가
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsMSSQL.vGroupUserRow;


            //일반사용자의경우에는 상태를 변경하지 못한다.
            int curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.account));
            if (curLevel < 5)
            {
                if (dr.id != FCOMMON.info.Login.no)
                {
                    FCOMMON.Util.MsgE("타인의 계정은 편집할 수 없습니다");
                    return;
                }
            }


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

        private void btDel_Click(object sender, EventArgs e)
        {
            func_del();
        }
        void func_del()
        {
            //일반사용자의경우에는 상태를 변경하지 못한다.
            int curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.account));
            if (curLevel < 5)
            {
                FCOMMON.Util.MsgE("계정 관리자만 사용할 수 있습니다");
                return;
            }

            //추가
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsMSSQL.vGroupUserRow;
            var dlg = FCOMMON.Util.MsgQ($"사원번호:{dr.id} 정보를 삭제할까요?");
            if (dlg != DialogResult.Yes) return;

            //그룹사용자목록에서 삭제만 하면 됨
            var db = new dsMSSQLTableAdapters.EETGW_GroupUserTableAdapter();// EEEntitiesMain();
            var dr_user = db.GetbyID(dr.gcode, dr.id).FirstOrDefault();
            //var dr_user = db.EETGW_GroupUser.Where(t => t.uid == dr.id).FirstOrDefault();
            if (dr_user != null)
            {
                dr_user.Delete();// db.EETGW_GroupUser.Remove(dr_user);
                var cnt = db.Update(dr_user);
                FCOMMON.Util.MsgI($"{cnt}건의 자료가 삭제 되었습니다");
            }
            RefreshList();
        }
    }
}
