using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;

namespace FPJ0000
{
    public partial class fProjectData : FCOMMON.fBase
    {
        dsPRJ.ProjectsRow dr = null;
        public fProjectData(dsPRJ.ProjectsRow pidx_)
        {
            InitializeComponent();
            this.UseFormSetting = false;
            this.dr = pidx_;
            this.dsPRJ.ProjectsHistory.TableNewRow += ProjectsHistory_TableNewRow;
        }

        void ProjectsHistory_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["wuid"] = FCOMMON.info.Login.no;
            e.Row["wdate"] = DateTime.Now;
            e.Row["pidx"] = this.dr.idx;
            e.Row["div"] = "";
            e.Row["remark"] = string.Empty;
            e.Row["pdate"] = DateTime.Now.ToShortDateString();
        }
        private void fProjectData_Load(object sender, EventArgs e)
        {
            //상태
            var dt_eetproc = FCOMMON.DBM.getCodeTable("10");
            this.cmbProcess.DisplayMember = "Value";
            this.cmbProcess.ValueMember = "Value";
            this.cmbProcess.DataSource = dt_eetproc;

            //분류 - 190903 - -제거 210329(박성민)
            //var dt_cate = FCOMMON.DBM.getCodeTable("20", "code");
            ////.cmbCate.DisplayMember = "Value";
            //this.cmbCate.ValueMember = "Value";
            //this.cmbCate.DataSource = dt_cate;

            //공정
            var dt_status = FCOMMON.DBM.getCodeTable("01");
            this.cmbState.DisplayMember = "Value";
            this.cmbState.ValueMember = "Value";
            this.cmbState.DataSource = dt_status;

            //파트
            var dt_part = FCOMMON.DBM.getCodeTable("11");
            this.cmbPart.DisplayMember = "Value";
            this.cmbPart.ValueMember = "Value";
            this.cmbPart.DataSource = dt_part;

            this.bs.DataSource = dr;


            //주간일지내역을 업데이트
            refresh_History();

            //일업무현황 업데이트
            this.taHistD.Fill(this.dsPRJ.EETGW_ProjecthistoryD, this.dr.idx);

            try
            {
                //if (dr.idx >= 0)
                //    this.taSchedule.Fill(this.dsPRJ.ProjectsSchedule, this.dr.idx);
            }
            catch (System.Exception ex)
            {
                rtBack.Text = rtDesc.Text = rtAft.Text = rtBef.Text = "";

                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
            this.cmbProcess.Text = dr.process;
            this.cmbState.Text = dr.status;
            this.cmbPart.Text = dr.part;
            //this.cmbCate.Text = dr.category;
            this.tbDue.Text = dr.crdue;

            rtAft.Text = string.Empty;
            rtBef.Text = string.Empty;
            rtDesc.Text = string.Empty;
            rtBack.Text = string.Empty;

            //신규데이터는 추가정보를 바로 저장할 수 없다.
            if (dr.RowState == DataRowState.Detached || dr.RowState == DataRowState.Deleted)
            {
                FCOMMON.Util.MsgI("신규자료는 저장을 하기 전에는 파트리스트/IO맵/주간업무등의 서브데이터를 추가할 수 없습니다.");
                btPart.Enabled = false;
                linkLabel1.Enabled = false;
                tbPath.Enabled = false;
                btPart.Enabled = false;
                btIO.Enabled = false;
                btMailAddr.Enabled = false;
                btSendMail.Enabled = false;
                tabControl2.Enabled = false;

           

            }
            else
            {
                //디비에서 조회한다.
                var dtMessage = ta.GetbyIDX(dr.idx);
                if(dtMessage.Rows.Count > 0)
                {
                    var dr2 = dtMessage.Rows[0] as dsPRJ.ProjectsRow;
                    if (string.IsNullOrEmpty(dr2.CMP_After) == false) rtAft.Rtf = dr2.CMP_After;
                    if (string.IsNullOrEmpty(dr2.CMP_Before) == false) rtBef.Rtf = dr2.CMP_Before;
                    if (string.IsNullOrEmpty(dr2.CMP_Description) == false) rtDesc.Rtf = dr2.CMP_Description;
                    if (string.IsNullOrEmpty(dr2.CMP_Background) == false) rtBack.Rtf = dr2.CMP_Background;
                }
                
            }

            btIO.Enabled = btPart.Enabled;
            //btWeek.Enabled = btPart.Enabled;
            btMailAddr.Enabled = btPart.Enabled;
            btPath.Enabled = btPart.Enabled;
            btSendMail.Enabled = btPart.Enabled;

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

            }
            else
            {
                tbPath.ReadOnly = true;
            }
        }

        string oldsta = string.Empty;
        private void btSave_Click(object sender, EventArgs e)
        {

            oldsta = dr.status;
            this.dr.process = cmbProcess.Text;
            this.dr.status = cmbState.Text;
            this.dr.part = cmbPart.Text;
            //this.dr.category = cmbCate.Text;

            //신규데이터일때에만 완료 자료를 처리한다.
            //if(this.dr.RowState == DataRowState.Detached || dr.RowState == DataRowState.Deleted)
            //{
                this.dr.CMP_After = rtAft.Rtf;
                this.dr.CMP_Before = rtBef.Rtf;
                this.dr.CMP_Description = rtDesc.Rtf;
                this.dr.CMP_Background = rtBack.Rtf;
            //}
            //else
            //{
            //    //직접데이터를 저장한다.
            //    var taq = new dsPRJTableAdapters.QueriesTableAdapter();
            //    var ucnt = taq.UpdateProjectCompleteMessage(rtBack.Rtf, rtDesc.Rtf, rtBef.Rtf, rtAft.Rtf, dr.idx);
            //}
            
            this.dr.crdue = tbDue.Text.Trim();


            this.Validate();
            this.bs.EndEdit();
            this.bsHistWeek.EndEdit();
            this.bsHistDay.EndEdit();
            this.bsTodo.EndEdit();
            this.taToDo.Update(this.dsPRJ.EETGW_ProjectToDo);
            this.taHist.Update(this.dsPRJ.ProjectsHistory);
            this.taHistD.Update(this.dsPRJ.EETGW_ProjecthistoryD);

            //상태가 변경되면 메일을 전송한다  210216
            if (oldsta != dr.status && dr.RowState != DataRowState.Detached)
            {
                var db = new EEEntities();
                var mf = db.MailForm.Where(t => t.gcode == FCOMMON.info.Login.gcode && t.cate == "PS").FirstOrDefault();
                if (mf != null)
                {
                    try
                    {
                        var mbody = new MailData();
                        mbody.tolist = mf.tolist;
                        mbody.bcc = mf.bcc;
                        mbody.cc = mf.cc;
                        mbody.project = dr.pidx;
                        mbody.gcode = FCOMMON.info.Login.gcode;
                        mbody.cate = mf.cate;
                        mbody.fromlist = "chikyun.kim@amkor.co.kr";
                        mbody.pdate = DateTime.Now.ToShortDateString();
                        mbody.subject = maildataupdate(mf.subject);
                        mbody.body = maildataupdate(mf.body);
                        mbody.wuid = FCOMMON.info.Login.no;
                        mbody.wdate = DateTime.Now;
                        db.MailData.Add(mbody);
                        db.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        FCOMMON.Util.MsgE("상태변경 메일 전송 실패" + ex.Message);
                    }
                }
            }
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            //this.tableAdapterManager.UpdateAll(this.dsPRJ);
        }

        string maildataupdate(string org)
        {
            org = org.Replace("{pname}", nameTextBox.Text);
            org = org.Replace("{pidx}", tbIdx.Text);
            org = org.Replace("{old}", oldsta);
            org = org.Replace("{new}", dr.status);
            org = org.Replace("{champion}", userManagerTextBox.Text);
            org = org.Replace("{sdate}", tbSdate.Text);
            org = org.Replace("{edate}", tbEdate.Text);
            org = org.Replace("{xdate}", tbXdate.Text);
            org = org.Replace("{odate}", tbODate.Text);
            return org;
        }


        private void btMailAddr_Click(object sender, EventArgs e)
        {
            fMailList f = new fMailList(this.dr.idx);
            f.ShowDialog();
        }

        private void btPath_Click(object sender, EventArgs e)
        {
            string path = tbPath.Text.Trim();
            if (path == "")
            {
                path = "\\10.131.32.33\\Data\\Projects\\";
                path += tbIdx.Text;
                tbPath.Text = path;
            }
            var dlg = FCOMMON.Util.MsgQ("다음 폴더를 표시할까요?\n\n" +
                path);
            if (dlg == System.Windows.Forms.DialogResult.Yes)
                FCOMMON.Util.RunExplorer(path);
        }

        private void btPart_Click(object sender, EventArgs e)
        {
            var f = new fPartList(dr.idx);
            f.ShowDialog();
        }

        private void btIO_Click(object sender, EventArgs e)
        {
            var f = new fProjectIOMap(dr.idx);
            f.ShowDialog();
        }

        private void btWeek_Click(object sender, EventArgs e)
        {

        }

        private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e)
        {
            var drv = this.bsHistWeek.Current as DataRowView;
            if (drv == null) return;
            var dlg = FCOMMON.Util.MsgQ("선택된 업무현황을 삭제하시겠습니까?" +
                "\n\n메일이 발송 완료된 경우 발송된 메일은 삭제되지 않습니다.");
            if (dlg == System.Windows.Forms.DialogResult.Yes)
                this.bsHistWeek.RemoveCurrent();
        }

        private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
        {
            var newdr = this.dsPRJ.ProjectsHistory.NewProjectsHistoryRow();
            var f = new fHistAdd(newdr);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                bsHistWeek.EndEdit();
                this.dsPRJ.ProjectsHistory.AddProjectsHistoryRow(newdr);
            }
            else newdr.Delete();
        }

        private void btSendMail_Click(object sender, EventArgs e)
        {
            List<int> prjlist = new List<int>();
            prjlist.Add(int.Parse(this.tbIdx.Text));
            fMailSend f = new fMailSend(prjlist);
            f.ShowDialog();
            refresh_History();
        }

        void refresh_History()
        {
            try
            {
                if (dr.idx >= 0)
                    this.taHist.Fill(this.dsPRJ.ProjectsHistory, this.dr.idx);
            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
        }

        private void btwEdit_Click(object sender, EventArgs e)
        {
            var drv = this.bsHistWeek.Current as DataRowView;
            if (drv == null) return;

            var newdr = drv.Row as dsPRJ.ProjectsHistoryRow;
            var f = new fHistAdd(newdr);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                newdr.EndEdit();
            }
        }

        private void dataGridView1_DoubleClick(object sender, EventArgs e)
        {
            btwEdit.PerformClick();
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (tbPath.Text == "") tbPath.Text = "/" + tbIdx.Text;

            if (tbPath.Text.StartsWith("\\") == false)
            {
                if (tbPath.Text.StartsWith("/")) tbPath.Text = tbPath.Text.Replace("/", "\\");
                else tbPath.Text = "\\" + tbPath.Text;
            }

            var serverpath = Properties.Settings.Default.SharePath + "\\Project";
            if (System.IO.Directory.Exists(serverpath) == false)
            {
                FCOMMON.Util.MsgE("프로젝트 기본경로가 존재하지 않아 진행할 수 없습니다\n\n" +
                    serverpath);
                return;
            }

            var path = serverpath + tbPath.Text;
            if (System.IO.Directory.Exists(path) == false)
            {
                try
                {
                    System.IO.Directory.CreateDirectory(path);

                    string[] subdir = new string[] { "Source", "Document", "Draw", "Estimate" };
                    foreach (var dir in subdir)
                        System.IO.Directory.CreateDirectory(path + "\\" + dir);

                }
                catch (Exception eX)
                {
                    FCOMMON.Util.MsgE("프로젝트 저장소 생성실패\n" + eX.Message);
                    return;
                }
            }

            FCOMMON.Util.RunExplorer(path);
        }
        void SelectDate(TextBox ctl)
        {
            DateTime dt;
            var dateStr = ctl.Text.Trim();
            if (dateStr == "") dateStr = DateTime.Now.ToShortDateString();
            else
            {
                if (DateTime.TryParse(dateStr, out dt)) dateStr = dt.ToShortDateString();
                else
                {
                    FCOMMON.Util.MsgE("날짜 형식으로 변환할 수 없는 문자열 입니다.\n" +
                        "기준일자가 금일로 변경 됩니다");
                    dateStr = DateTime.Now.ToShortDateString();
                }
            }
            dt = DateTime.Parse(dateStr);
            var f = new FCOMMON.fSelectDay(dt);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                ctl.Text = f.dtPick.SelectionStart.ToShortDateString();
            }
        }
        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            SelectDate(tbSdate);
        }

        private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            SelectDate(tbXdate);
        }

        private void linkLabel4_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            SelectDate(tbEdate);
        }

        private void linkLabel5_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            SelectDate(tbODate);
        }

        private void bs_CurrentChanged(object sender, EventArgs e)
        {

        }

        private void rtBack_Click(object sender, EventArgs e)
        {

        }

        private void rtBack_DoubleClick(object sender, EventArgs e)
        {
            var rt = sender as System.Windows.Forms.RichTextBox;
            var f = new Note.fTextEditor(rt.Rtf);
            if (f.ShowDialog() == DialogResult.OK)
                rt.Rtf = f.richTextBoxEx1.Rtf;
        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            //일업무현황 추가
            var newdr = this.dsPRJ.EETGW_ProjecthistoryD.NewEETGW_ProjecthistoryDRow();
            newdr.wuid = FCOMMON.info.Login.no;
            newdr.wdate = DateTime.Now;
            newdr.pidx = this.dr.idx;
            newdr.pdate = DateTime.Now.ToShortDateString();
            var f = new fHistAddDay(newdr);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.bsHistDay.EndEdit();
                this.dsPRJ.EETGW_ProjecthistoryD.AddEETGW_ProjecthistoryDRow(newdr);
            }
            else newdr.Delete();
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            var drv = this.bsHistDay.Current as DataRowView;
            if (drv == null) return;

            var newdr = drv.Row as dsPRJ.EETGW_ProjecthistoryDRow;
            var f = new fHistAddDay(newdr);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                newdr.EndEdit();
            }
        }

        private void toolStripButton7_Click(object sender, EventArgs e)
        {
            var drv = this.bsHistDay.Current as DataRowView;
            if (drv == null) return;
            var dlg = FCOMMON.Util.MsgQ("선택된 일 업무 현황을 삭제하시겠습니까?");
            if (dlg == System.Windows.Forms.DialogResult.Yes)
                this.bsHistDay.RemoveCurrent();
        }



    }
}
