using FCM0000;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace FPJ0000
{
    public partial class fProjectData : FCOMMON.fBase
    {
        dsPRJ.ProjectsRow dr = null;
        bool EditMode = false;

        public fProjectData(dsPRJ.ProjectsRow pidx_, bool editmode_ = true)
        {
            InitializeComponent();
            this.UseFormSetting = false;
            this.dr = pidx_;
            this.dsPRJ.ProjectsHistory.TableNewRow += ProjectsHistory_TableNewRow;
            this.EditMode = editmode_;
            this.chkCostSave.Checked = pidx_.bCost;
            this.chkFanout.Checked = pidx_.bFanOut;
            this.chkHigh.Checked = pidx_.bHighlight;
            this.chkMajor.Checked = pidx_.bmajoritem;
            this.rtPanelImage.SizeMode = PictureBoxSizeMode.Zoom;
        }
        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            base.OnFormClosed(e);
            if (this.rtPanelImage.Image != null)
                this.rtPanelImage.Image = null;
        }

        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.ToString("yyyy-MM-dd");
        }
        private void fProjectData_Load(object sender, EventArgs e)
        {
            EnsureVisibleAndUsableSize();
            //사용자목록업데이트
            UpdateUserList();

            //공정
            var dt_eetproc = FCOMMON.DBM.getCodeTable("10");
            this.cmbReqProcess.DisplayMember = "Value";
            this.cmbReqProcess.ValueMember = "Value";
            this.cmbReqProcess.DataSource = dt_eetproc;

            //line
            var dt_line = FCOMMON.DBM.getCodeTable("19");
            this.cmbReqLine.DisplayMember = "Value";
            this.cmbReqLine.ValueMember = "Value";
            this.cmbReqLine.DataSource = dt_line;

            //site
            var dt_site = FCOMMON.DBM.getCodeTable("23");
            this.cmbReqSite.DisplayMember = "Value";
            this.cmbReqSite.ValueMember = "Value";
            this.cmbReqSite.DataSource = dt_site;

            //plant
            var dt_plant = FCOMMON.DBM.getCodeTable("24");
            this.cmbReqPlant.DisplayMember = "Value";
            this.cmbReqPlant.ValueMember = "Value";
            this.cmbReqPlant.DataSource = dt_plant;

            //plant
            var dt_package = FCOMMON.DBM.getCodeTable("14");
            this.cmbReqPackage.DisplayMember = "Value";
            this.cmbReqPackage.ValueMember = "Value";
            this.cmbReqPackage.DataSource = dt_package;

            //분류 - 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("13");
            this.cmbReqTeam.DisplayMember = "Value";
            this.cmbReqTeam.ValueMember = "Value";
            this.cmbReqTeam.DataSource = dt_part;

            this.bs.DataSource = dr;
            // this.cmbUser.SelectedValue = dr.championid;

            tbSdate.Text = dr.sdate;
            tbDDate.Text = dr.ddate;
            tbBdate.Text = dr.bdate;
            tbODate.Text = dr.odate;
            tbQdate.Text = dr.qdate;
            tbCdate.Text = dr.cdate;
            tbEdate.Text = dr.edate;
            tbKDate.Text = dr.kdate;


            //주간일지내역을 업데이트
            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 = "";
                AR.UTIL.MsgE(ex.Message);
                //System.Windows.Forms.MessageBox.Show(ex.Message);
            }
            this.cmbReqProcess.Text = dr.process;
            this.cmbState.Text = dr.status;
            this.cmbReqTeam.Text = dr.part;
            this.tbDue.Text = dr.crdue;
            this.nudCRAmount.Value = dr.cramount;

            this.cmbReqSite.Text = dr.ReqSite;
            this.cmbReqPlant.Text = dr.ReqPlant;
            this.cmbReqPackage.Text = dr.ReqPackage;
            this.cmbReqLine.Text = dr.ReqLine;

            rtAft.Text = string.Empty;
            rtBef.Text = string.Empty;
            rtDesc.Text = string.Empty;
            rtBack.Text = string.Empty;
            rtTangil.Text = string.Empty;
            rtIntangle.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;
                toolStripButton8.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;

                    if (dr2.Iseffect_intangibleNull() == false) rtIntangle.Rtf = dr2.effect_intangible;
                    if (dr2.Iseffect_tangibleNull() == false) rtTangil.Rtf = dr2.effect_tangible;
                }
            }

            btIO.Enabled = btPart.Enabled;
            btMailAddr.Enabled = btPart.Enabled;
            btPath.Enabled = btPart.Enabled;
            btSendMail.Enabled = btPart.Enabled;
            tbSFI.Text = dr.sfic.ToString("N2");

            if (dr.IspanelimageNull()) rtPanelImage.Image = null;
            else
            {
                try
                {
                    using (MemoryStream ms = new MemoryStream(dr.panelimage))
                    {
                        rtPanelImage.Image = Image.FromStream(ms);
                    }
                }
                catch (Exception ex)
                {
                    AR.UTIL.MsgE("Panel Image Error\n" + ex.Message);
                }

            }

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

            }
            else
            {
                tbPath.ReadOnly = true;
            }

            bn.Enabled = EditMode;

        }
        void UpdateUserList()
        {
            //담당자목록 - 사용자목록으로 처리한다.  

            var dt = new DSComm.UserListDataTable();
            var taUserList = new dsReportTableAdapters.ProcessUserListTableAdapter();
            var processStr = "%";
            var dtUserList = taUserList.GetData(processStr, FCOMMON.info.Login.gcode);
            var newdrnone = dt.NewUserListRow();
            newdrnone.ID = string.Empty;
            newdrnone.Name = "(없음)";
            newdrnone.IDName = "(없음)";
            newdrnone.Outdate = null;
            newdrnone.Description = string.Empty;
            dt.AddUserListRow(newdrnone);


            var orderlist = dtUserList.OrderBy(t => t.outdate).ToList();
            foreach (dsReport.ProcessUserListRow dr in orderlist)
            {
                //if (String.IsNullOrEmpty(dr.outdate) == false)
                //{
                //    var odt = DateTime.Parse(dr.outdate);
                //    if (odt <= DateTime.Now) continue; //퇴사자제외  211221
                //}
                var newdr = dt.NewUserListRow();
                newdr.ID = dr.id;
                newdr.Name = dr.name;
                newdr.IDName = $"({dr.id}) {dr.name}";
                newdr.Outdate = dr.outdate;
                if (dr.outdate.isEmpty()) newdr.Description = string.Empty;
                else newdr.Description = $"퇴사({dr.outdate})";
                //string cmbdata = string.Format("{1}({0})", dr.id, dr.name);
                //this.cmbUser.Items.Add(cmbdata);
                //Console.WriteLine($"{dr.id},{dr.name}");
                dt.AddUserListRow(newdr);
            }
            this.dSComm.UserList.Clear();
            this.dSComm.UserList.Merge(dt);
            this.dSComm.UserList.AcceptChanges();
        }
        void SelectUserList(string uid)
        {

        }

        bool checkDateValue()
        {
            foreach (Control ctl in panel2.Controls)
            {
                if (ctl is TextBox)
                {
                    var tb = ctl as TextBox;
                    if (tb.Text.isEmpty()) continue;
                    if (DateTime.TryParse(tb.Text, out DateTime dt) == false)
                    {
                        FCOMMON.Util.MsgE($"다음 값은 날짜 형식이 아닙니다.\n입력값 : {tb.Text}\n\n정확한 날짜 데이터로 입력하세요\n" +
                            "예) 2000-01-01");
                        tb.Focus();
                        tb.SelectAll();
                        return false;
                    }
                }
            }
            return true;
        }

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

            oldsta = dr.status;
            this.dr.process = cmbReqProcess.Text;
            this.dr.status = cmbState.Text;
            this.dr.part = cmbReqTeam.Text;
            if (this.rtPanelImage.Image != null)
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    this.rtPanelImage.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Png); // 또는 원하는 포맷
                    this.dr.panelimage = ms.ToArray();
                }
            }
            else
            {
                this.dr.SetpanelimageNull();
            }

            this.dr.ReqLine = cmbReqLine.Text;
            this.dr.ReqSite = cmbReqSite.Text;
            this.dr.ReqPackage = cmbReqPackage.Text;
            this.dr.ReqPlant = cmbReqPlant.Text;

            this.dr.bCost = chkCostSave.Checked;
            this.dr.bHighlight = chkHigh.Checked;
            this.dr.bmajoritem = chkMajor.Checked;
            this.dr.bFanOut = chkFanout.Checked;

            this.dr.sdate = tbSdate.Text;
            this.dr.ddate = tbDDate.Text;
            this.dr.bdate = tbBdate.Text;
            this.dr.odate = tbODate.Text;
            this.dr.qdate = tbQdate.Text;
            this.dr.cdate = tbCdate.Text;
            this.dr.edate = tbEdate.Text;
            this.dr.kdate = tbKDate.Text;
            this.dr.EndEdit();


            if (tbSFI.Text.isEmpty() == false)
            {
                if (float.TryParse(tbSFI.Text, out float sfi))
                {
                    // if (dr.sfi_type == "O")
                    this.dr.sfic = sfi;
                    //else
                    //    this.dr.sfic = sfi; //mfg는 이곳으로
                }
                else
                {
                    FCOMMON.Util.MsgE("SFI 값을 확인할 수 없습니다. 입력하지 않으려면 입력된 문자를 모두 지우세요");
                    return;
                }
            }
            else this.dr.sfic = 0.0;

            //날짜박스의 날짜데이터 검증
            if (checkDateValue() == false) return;

            //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;
            this.dr.effect_tangible = rtTangil.Rtf;
            this.dr.effect_intangible = rtIntangle.Rtf;

            //         var s = "dbo.getUserName2(championid,usermanager) as name_champion," +
            //"dbo.getUserName2(designid,usermain) as name_design," +
            //"dbo.getUserName2(assemblyid,userAssembly) as name_assembly," +
            //"dbo.getUserName2(epanelid,userhw2) as name_epanel," +
            //"dbo.getUserName2(softwareid,usersub) as name_software";

            //if (cmbChampion.SelectedIndex < 1)
            //{
            //    if (dr.userManager.isEmpty() == false) dr.name_champion = $"({dr.userManager})";
            //}
            //else dr.name_champion = cmbChampion.Text.Substring(cmbChampion.Text.IndexOf("(") + 1);
            //dr.name_champion = dr.championid.isEmpty() ? "(" + dr.userManager + ")" : FCOMMON.DBM.use
            //}
            //else
            //{
            //    //직접데이터를 저장한다.
            //    var taq = new dsPRJTableAdapters.QueriesTableAdapter();
            //    var ucnt = taq.UpdateProjectCompleteMessage(rtBack.Rtf, rtDesc.Rtf, rtBef.Rtf, rtAft.Rtf, dr.idx);
            //}

            this.dr.cramount = nudCRAmount.Value;
            this.dr.crdue = tbDue.Text.Trim();
            this.dr.EndEdit();


            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 dsMailTableAdapters.MailFormTableAdapter();// EEEntities();
                var mf = db.GetData(FCOMMON.info.Login.gcode, "PS").FirstOrDefault(); //.MailForm.Where(t => t.gcode == FCOMMON.info.Login.gcode && t.cate == "PS").FirstOrDefault();
                if (mf != null)
                {
                    try
                    {
                        var taMdata = new dsMailTableAdapters.MailDataTableAdapter();
                        var dtMdata = new FPJ0000.dsMail.MailDataDataTable();
                        var mbody = dtMdata.NewMailDataRow();
                        mbody.gcode = FCOMMON.info.Login.gcode;
                        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 = "gw@amkor.co.kr";
                        mbody.pdate = DateTime.Now.ToString("yyyy-MM-dd");
                        mbody.subject = maildataupdate(mf.subject);
                        mbody.body = maildataupdate(mf.body);
                        mbody.wuid = FCOMMON.info.Login.no;
                        mbody.wdate = DateTime.Now;
                        dtMdata.AddMailDataRow(mbody);
                        var cnt = taMdata.Update(dtMdata);
                        if (cnt != 1) FCOMMON.Util.MsgE($"데이터 변경 수치가 1이 아닙니다 값:{cnt}");
                    }
                    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}", tbNameChamp.Text);
            org = org.Replace("{sdate}", tbSdate.Text);
            org = org.Replace("{edate}", tbEdate.Text);
            org = org.Replace("{xdate}", tbDDate.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)
        {
            showfolder();
            //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);
        }

        void showfolder()
        {
            var dr = this.bs.Current as dsPRJ.ProjectsRow;
            if (dr == null) return;
            //var dr = drv.Row as dsPRJ.ProjectsRow;

            var tbPath = dr.path;

            if (tbPath == "") tbPath = "/" + dr.idx.ToString();

            if (tbPath.StartsWith("\\") == false)
            {
                if (tbPath.StartsWith("/")) tbPath = tbPath.Replace("/", "\\");
                else tbPath = "\\" + tbPath;
            }
            //\\10.131.32.29\Data
            var datapath = FCOMMON.DBM.getCodeSvalue("55", "01");
            var serverpath = System.IO.Path.Combine(datapath, "Data", "Project");
            if (System.IO.Directory.Exists(serverpath) == false)
            {
                FCOMMON.Util.MsgE("프로젝트 기본경로가 존재하지 않아 진행할 수 없습니다\n\n" +
                    serverpath);
                return;
            }

            var path = serverpath + tbPath;
            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);
        }


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

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

        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.ToString("yyyy-MM-dd");
            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();
        }

        private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }

        private void dataGridView2_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void linkLabel6_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            SelectDate(tbBdate);
        }

        private void linkLabel7_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            SelectDate(tbQdate);
        }

        private void linkLabel8_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            SelectDate(tbCdate);
        }

        private void toolStripButton8_Click(object sender, EventArgs e)
        {
            var f = new fProjectSchedule(int.Parse(tbIdx.Text), false);
            f.MdiParent = this.MdiParent;
            f.ShowDialog();
        }

        private void linkLabel10_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var url = $"https://scwa.amkor.co.kr/jasmine/view/{textBox12.Text}";
            FCOMMON.Util.RunExplorer(url);
        }

        private void linkLabel11_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {

            int cnt = 1;
            if (dr.Issfi_countNull() == false) cnt = dr.sfi_count;
            else int.TryParse(cntTextBox.Text, out cnt);

            var sfi_type = "O";
            var sfi_count = 0D;
            var sfi_time = 0D;
            var sfi_shiftcount = 0D;
            if (dr.Issfi_typeNull() == false) sfi_type = dr.sfi_type;
            if (dr.Issfi_savecountNull() == false) sfi_count = dr.sfi_savecount;
            if (dr.Issfi_savetimeNull() == false) sfi_time = dr.sfi_savetime;
            if (dr.Issfi_shiftcountNull() == false) sfi_shiftcount = dr.sfi_shiftcount;
            if (sfi_shiftcount == 0) sfi_shiftcount = 4;

            var f = new FCOMMON.fSFI(sfi_type, sfi_time, sfi_count, sfi_shiftcount, cnt);
            if (f.ShowDialog() == DialogResult.OK)
            {
                tbSFI.Text = f.Value.ToString("N2");
                dr.sfi_type = f.radO.Checked ? "O" : "M";
                dr.sfi_count = (int)f.nudCnt.Value; //250904
                if (f.radO.Checked)
                {
                    dr.sfi = f.Value; //office 는 sfi와 sfic 가 동일하다
                    dr.sfi_savetime = (float)f.nudOsavetime.Value;
                }
                else
                {
                    //m 데이터는 sfi가 아닌sfic에 값이 들어간다.  
                    dr.sfi = (float)f.nudSFIMFG.Value;
                    dr.sfi_savetime = (float)f.nudMsavetime.Value;
                }

                dr.sfi_savecount = (float)f.nudMSaveCnt.Value;
                dr.sfi_shiftcount = (float)f.nudShiftCnt.Value;
                dr.EndEdit();
            }

        }

        private void arLabel9_Click(object sender, EventArgs e)
        {

        }

        private void richTextBox1_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 richTextBox2_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 label10_Click(object sender, EventArgs e)
        {
            SelectDate(tbDue);
        }

        private void arLabel2_Click(object sender, EventArgs e)
        {

        }

        private void toolStripButton10_Click(object sender, EventArgs e)
        {
            var img = this.rtPanelImage.Image;
            this.rtPanelImage.Image = null;
            if (img != null) img.Dispose();
            dr.SetpanelimageNull();
        }

        private void toolStripButton9_Click(object sender, EventArgs e)
        {
            var img = this.rtPanelImage.Image;
            using (var od = new OpenFileDialog())
            {
                od.Filter = "image|*.jpg,*.gif,*.png,*.bmp";
                if (od.ShowDialog() == DialogResult.OK)
                {
                    var oldimage = this.rtPanelImage.Image;
                    this.rtPanelImage.Image = Image.FromFile(od.FileName);
                    if (oldimage != null) oldimage.Dispose();
                }

            }
        }

        private void toolStripButton11_Click(object sender, EventArgs e)
        {
            //paste clipboard image data            
            var img = Clipboard.GetImage();
            if (img != null)
            {
                var oldimage = this.rtPanelImage.Image;
                this.rtPanelImage.Image = img;
                if (oldimage != null) oldimage.Dispose();
            }
            
        }
    }
}
