using FCOMMON;
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 fAddNewUser : fBase // FCOMMON.fBase
    {
        string p_dept = string.Empty;
        string p_id = string.Empty;
        short deflevel = 1;
        public fAddNewUser(string dept, string id, short _deflevel = 1)
        {
            InitializeComponent();
            p_dept = dept;
            p_id = id;
            this.deflevel = _deflevel;

            this.tbDept.Text = dept;
            this.StartPosition = FormStartPosition.CenterScreen;
            this.tbId.Text = id;

            //자료를 불러와서 먼저 불러온다
            if (id.isEmpty() == false)
            {
                tbId.Enabled = false;
                button1.Enabled = false;
                btChangePW.Enabled = true;


                var taUser = new dsMSSQLTableAdapters.UsersTableAdapter();// EEEntitiesMain();
                var taGUser = new dsMSSQLTableAdapters.EETGW_GroupUserTableAdapter();
                var db_user = taUser.GetID(id).FirstOrDefault();// db.Users.Where(t => t.id == id).FirstOrDefault();
                var db_guser = taGUser.GetbyID(FCOMMON.info.Login.gcode, id).FirstOrDefault();// db.EETGW_GroupUser.Where(t => t.gcode == FCOMMON.info.Login.gcode && t.uid == id).FirstOrDefault();
                if (db_user != null)
                {
                    tbNameK.Text = db_user.name;
                    tbNameE.Text = db_user.nameE;
                    tbDept.Text = db_user.dept;
                    tbEmail.Text = db_user.email;
                    tbTel.Text = db_user.tel;
                    tbHp.Text = db_user.hp;
                    tbDateIn.Text = db_user.indate;
                    tbDateO.Text = db_user.outdate;
                    tbGrade.Text = db_user.grade;
                    tbMemo.Text = db_user.memo;

                }
                if (db_guser != null)
                {
                    tbProcess.Text = db_guser.Process;
                    tbState.Text = db_guser.state;

                    //this.chkJobReport.Checked = (db_guser.useJobReport == null ? false : (bool)db_guser.useJobReport);
                    this.chkJobReport.Checked = (db_guser.IsuseJobReportNull() ? false : (bool)db_guser.useJobReport);
                    this.chkUseState.Checked = (db_guser.IsuseUserStateNull() ? false : (bool)db_guser.useUserState);
                    this.chkExceptHoly.Checked = (db_guser.IsexceptHolyNull() ? false : (bool)db_guser.exceptHoly);
                }

                this.Text = "사용자 정보 변경";
            }
            else
            {
                this.Text = "사용자 정보 추가";
                btChangePW.Enabled = false;
            }

        }


        private void fUserInfo_Load(object sender, EventArgs e)
        {
            EnsureVisibleAndUsableSize();
            int curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.account));

            if (this.deflevel < 1)
            {
                chkExceptHoly.Visible = false;
                chkJobReport.Visible = false;
                chkUseState.Visible = false;

                chkExceptHoly.Checked = false;
                chkJobReport.Checked = false; ;
                chkUseState.Checked = false;
            }
            else
            {
                chkExceptHoly.Enabled = curLevel > 4;
                chkJobReport.Enabled = curLevel > 4;
                chkUseState.Enabled = curLevel > 4;
            }

        }
        private void button1_Click(object sender, EventArgs e)
        {
            //입력한 id확인해서 잇으면 해당 자료를 표시해준다.
            var id = this.tbId.Text.Trim();
            if (id.isEmpty())
            {
                FCOMMON.Util.MsgE("id를 입력하세요");
                this.tbId.SelectAll();
                this.tbId.Focus();
                return;
            }

            var db = new dsMSSQLTableAdapters.UsersTableAdapter();// EEEntitiesMain();
            var dr_user = db.GetID(id).FirstOrDefault();//.Where(t => t.id == id).FirstOrDefault();
            if (dr_user == null)
            {
                FCOMMON.Util.MsgE("등록된 자료가 없습니다");
                tbNameK.Focus();
            }
            else
            {
                tbNameK.Text = dr_user.name;
                tbNameE.Text = dr_user.nameE;
                if (tbDept.Text.isEmpty()) tbDept.Text = dr_user.dept;
                tbEmail.Text = dr_user.email;
                tbTel.Text = dr_user.tel;
                tbHp.Text = dr_user.hp;
                tbDateIn.Text = dr_user.indate;
                tbDateO.Text = dr_user.outdate;
                tbGrade.Text = dr_user.grade;
                tbMemo.Text = dr_user.memo;
                tbProcess.Text = string.Empty;

                //부서가잇다면 해당 부서에서 해당 사용자의 공정을 찾는다
                if (tbDept.Text.isEmpty() == false)
                {
                    var tagGUser = new dsMSSQLTableAdapters.vGroupUserTableAdapter();
                    var drGrp = tagGUser.GetOnlyID(id).FirstOrDefault();// db.vGroupUser.Where(t => t.id == id).FirstOrDefault();
                    if (drGrp != null)
                    {
                        tbProcess.Text = drGrp.processs;
                    }
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Validate();
            //var db = new EEEntitiesMain();

            //해당 그룹에 데이터를 추가한다.
            //var drDept = db.UserGroup.Where(t => t.dept == tbDept.Text).FirstOrDefault();
            //if (drDept == null)
            //{
            //    FCOMMON.Util.MsgE("해당 부서정보가 존재하지 않습니다\n\n부서를 신규로 추가할 수는 없습니다\n관리자에 문의하세요");
            //    return;
            //}
            var gcode = FCOMMON.info.Login.gcode;
            var uid = (p_id.isEmpty() ? tbId.Text.Trim() : p_id);
            //if (FCOMMON.info.Login.no.isEmpty()) FCOMMON.info.Login.no = uid;


            //해당 그룹에 해당 사용자가 존재하는지 확이한다.
            var taUserGrp = new dsMSSQLTableAdapters.EETGW_GroupUserTableAdapter();
            var dtUserGrp = taUserGrp.GetData(gcode);
            var drGuser = dtUserGrp.Where(t => t.uid == uid).FirstOrDefault();
            if (drGuser != null)
            {
                drGuser.Process = this.tbProcess.Text.Trim();
                drGuser.state = this.tbState.Text.Trim();
                if (deflevel > 0)
                {
                    drGuser.useJobReport = chkJobReport.Checked;
                    drGuser.useUserState = chkUseState.Checked;
                    drGuser.exceptHoly = chkExceptHoly.Checked;
                }
                if (drGuser.level == 0)
                {
                    int curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.account));
                    if (curLevel >= 5)
                    {
                        FCOMMON.Util.MsgI($"해당 계정이 활성화 됩니다.");
                        drGuser.level = 1;
                    }
                    else
                    {
                        FCOMMON.Util.MsgE($"이미 존재하는 사용자 정보입니다\n" +
                    "아직 관리자 승인이 되지 않은 상태입니다\n" +
                    "계정관리자 통해서 계정을 활성화를 하세요");
                    }


                }
                else FCOMMON.Util.MsgI($"이미 존재하는 사용자 정보입니다\n" + "기존 정보가 업데이트 됩니다");
            }
            else
            {
                //불러온경우
                if (tbId.Enabled == false)
                {
                    FCOMMON.Util.MsgE("사용자 ID정보가 없어 진행할 수 없습니다");
                    return;
                }

                drGuser = dtUserGrp.NewEETGW_GroupUserRow();
                drGuser.wuid = FCOMMON.info.Login.no;
                drGuser.wdate = DateTime.Now;
                drGuser.gcode = gcode;
                drGuser.level = this.deflevel;
                drGuser.uid = this.tbId.Text.Trim();
                drGuser.state = this.tbState.Text.Trim();
                drGuser.Process = this.tbProcess.Text.Trim();
                //drGuser.useJobReport = this.chkJobReport.Checked;
                drGuser.useJobReport = this.chkJobReport.Checked;
                drGuser.useUserState = this.chkUseState.Checked;
                drGuser.exceptHoly = this.chkExceptHoly.Checked;

                dtUserGrp.AddEETGW_GroupUserRow(drGuser);
            }


            //사용자 목록에 없다면 추가한다
            var tauser = new dsMSSQLTableAdapters.UsersTableAdapter();
            var dtuser = tauser.GetID(uid);
            var drUser = dtuser.FirstOrDefault();
            if (drUser == null)
            {
                drUser = dtuser.NewUsersRow();
                drUser.wuid = FCOMMON.info.Login.no;
                drUser.wdate = DateTime.Now;
                drUser.gcode = gcode;
                drUser.level = this.deflevel;
                drUser.id = tbId.Text.Trim();
                drUser.password = newpassword;// "B6589FC6AB0DC82CF12099D1C2D40AB994E8410C"; //기본값0

                drUser.name = tbNameK.Text.Trim();
                drUser.nameE = tbNameE.Text.Trim();
                drUser.dept = this.tbDept.Text.Trim();
                drUser.email = tbEmail.Text;
                drUser.tel = tbTel.Text;
                drUser.hp = tbHp.Text;
                drUser.indate = tbDateIn.Text;
                drUser.outdate = tbDateO.Text;
                drUser.memo = tbMemo.Text;
                drUser.processs = tbProcess.Text;
                drUser.grade = tbGrade.Text.Trim();
                dtuser.AddUsersRow(drUser);
            }

            else
            {
                if (string.IsNullOrEmpty(drUser.password)) //암호가 아에없다면 기본 0으로 설정
                    drUser.password = "B6589FC6AB0DC82CF12099D1C2D40AB994E8410C";
                else if (newpassword.isEmpty() == false)
                    drUser.password = newpassword;// "B6589FC6AB0DC82CF12099D1C2D40AB994E8410C";

                drUser.name = tbNameK.Text.Trim();
                drUser.nameE = tbNameE.Text.Trim();
                drUser.dept = this.tbDept.Text.Trim();
                drUser.email = tbEmail.Text;
                drUser.tel = tbTel.Text;
                drUser.hp = tbHp.Text;
                drUser.indate = tbDateIn.Text;
                drUser.outdate = tbDateO.Text;
                drUser.memo = tbMemo.Text;
                drUser.processs = tbProcess.Text;
                drUser.grade = tbGrade.Text.Trim();
                drUser.EndEdit();

            }

            try
            {
                var cnt1 = taUserGrp.Update(dtUserGrp);
                var cnt2 = tauser.Update(dtuser);

                if (cnt1 + cnt2 != 2)
                {
                    FCOMMON.Util.MsgE("저장에 문제가 생겼습니다\n관리자에게 문의 하시기 바랍니다");
                }
                taUserGrp.Dispose();
                tauser.Dispose();

                this.DialogResult = DialogResult.OK;
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE("save error\n" + ex.Message);
            }


        }

        private void chkUserSt_CheckedChanged(object sender, EventArgs e)
        {

        }

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

        string newpassword = "";//"B6589FC6AB0DC82CF12099D1C2D40AB994E8410C"; //기본값 0
        private void btChangePW_Click(object sender, EventArgs e)
        {
            var f = new fNewPassword(this.tbId.Text);
            if (f.ShowDialog() == DialogResult.OK)
            {
                int curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.account));

                var opass = Pub.MakePasswordEnc(f.tbPassO.Text);

                //해당 그룹에 해당 사용자가 존재하는지 확이한다.
                var gcode = FCOMMON.info.Login.gcode;
                var uid = tbId.Text;
                var db = new dsMSSQLTableAdapters.UsersTableAdapter();// EEEntitiesMain();
                var drUser = db.GetID(uid).FirstOrDefault();// .Users.SingleOrDefault(t => t.id == uid);
                if (drUser != null)
                {
                    if (curLevel < 5 && opass.Equals(drUser.password) == false)
                    {
                        Util.MsgE("기존 암호가 일치하지 않습니다");
                        return;
                    }
                }
                else
                {
                    Util.MsgE("사용자 정보가 없어 처리할 수 없습니다");
                    return;
                }

                newpassword = Pub.MakePasswordEnc(f.newpassword);
                Util.MsgI($"암호가 변경되었습니다.[저장] 버튼을 누르면 적용 됩니다");
            }
        }
    }
}
