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.Dialog
{
    public partial class fLogin : Form
    {
        public fLogin()
        {
            InitializeComponent();
            this.tbID.KeyDown += (s1, e1) => { if (e1.KeyCode == Keys.Enter) tbPW.Focus(); };
            this.tbPW.KeyDown += (s1, e1) => { if (e1.KeyCode == Keys.Enter) btLogin.PerformClick(); };
            this.KeyPreview = true;
            this.KeyDown += (s1, e1) => {
                if (e1.KeyCode == Keys.Escape) this.Close();
            };
        }
        private void fLogin_Load(object sender, EventArgs e)
        {
            var list = Pub.setting.lastid.Split(';');
            foreach (var item in list)
                if (item != "") tbID.Items.Add(item);
            if (tbID.Items.Count > 0) tbID.SelectedIndex = 0;

            var dlist = Pub.setting.lastdept.Split(';');
            foreach (var item in dlist)
                if (item != "") this.cmbDept.Items.Add(item);
            if (cmbDept.Items.Count > 0) cmbDept.SelectedIndex = 0;

            this.Show();
            Application.DoEvents();

            if (this.tbID.Text.isEmpty() == false) tbPW.Focus();
            else tbID.Focus();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            
            if (this.tbID.Text.isEmpty())
            {
                tbID.Focus();
                return;
            }
            if(this.tbPW.Text.isEmpty())
            {
                tbPW.Focus();
                return;
            }

            List<string> idlist = new List<string>();
            idlist.Add(tbID.Text.Trim());
            foreach (var item in this.tbID.Items)
                if (idlist.Contains(item) == false) idlist.Add(item.ToString());

            List<string> deptlist = new List<string>();
            deptlist.Add(cmbDept.Text.Trim());
            foreach (var item in this.cmbDept.Items)
                if (deptlist.Contains(item) == false) deptlist.Add(item.ToString());

            //180605
            var vuserlist = "";
            foreach (var item in idlist)
                vuserlist += ";" + item;

            var vdeptlist = "";
            foreach(var item in deptlist)
                vdeptlist += ";" + item;

            Pub.setting.lastid = vuserlist;// tbID.Text.Trim();
            Pub.setting.lastdept = vdeptlist;
            Pub.setting.Save();

            var encpass = Pub.MakePasswordEnc(tbPW.Text.Trim());
            var ta = new dsMSSQLTableAdapters.UsersTableAdapter();
            try
            {
                var users = ta.GetIDPW(encpass, tbID.Text.Trim());                
                if (users.Rows.Count != 1)
                {
                    users = ta.GetByNamePw(tbID.Text.Trim(), encpass);
                    if(users.Rows.Count != 1)
                    {
                        Util.MsgE("입력한 사용자 계정이 존재하지 않습니다");
                        tbPW.SelectAll();
                        tbPW.Focus();
                        return;
                    }
                }

                //이사용자의 부서 코드확인
                var userdr = users.Rows[0] as dsMSSQL.UsersRow;
                if (userdr.level < 9 && userdr.dept != cmbDept.Text)
                {
                    Util.MsgE("입력한 사용자는 지정한 부서에 접속할 권한이 없습니다");
                    return;
                }

                FCOMMON.info.Login.no = userdr.id;
                FCOMMON.info.Login.nameK = userdr.name;
                FCOMMON.info.Login.dept = cmbDept.Text;
                FCOMMON.info.Login.level = userdr.level;
                FCOMMON.info.Login.email = userdr.email;
                FCOMMON.info.Login.nameE = userdr.nameE;
                FCOMMON.info.Login.hp = userdr.hp;
                FCOMMON.info.Login.tel = userdr.tel;
                FCOMMON.info.Login.title = userdr.ads_title;
                var gcode = FCOMMON.DBM.ExecuteScalar("select isnull(gcode,'NOGCODE') from UserGroup where dept ='" + cmbDept.Text + "'");
                var gperm = FCOMMON.DBM.ExecuteScalar("select isnull(permission,0) from UserGroup where dept ='" + cmbDept.Text + "'");
                FCOMMON.info.Login.gcode = gcode;
                FCOMMON.info.Login.process = userdr.processs;
                FCOMMON.info.Login.permission = 0;
                FCOMMON.info.Login.gpermission = int.Parse(gperm);

                DialogResult = DialogResult.OK;
            }catch (Exception ex)
            {
                Util.MsgE("데이터베이스 조회 실패 다음 오류 메세지를 참고하세요.\n\n"+ ex.Message + "\n\n증상이 동일 할 경우 서버가 접속가능한지 먼저 확인하세요");
                DialogResult = System.Windows.Forms.DialogResult.Cancel;
            }
            
        }

        private void label3_Click(object sender, EventArgs e)
        {
            
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var f = new Dialog.fSelectDept();
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (cmbDept.Items.Contains(f.deptName) == false)
                    cmbDept.Items.Add(f.deptName);
                cmbDept.Text = f.deptName;
            }
        }

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            FCOMMON.Util.RunExplorer("mailto:chikyun.kim@amkor.co.kr");
        }
    }
}
