using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using util = FCOMMON.Util;

using NetOffice;
using Outlook = NetOffice.OutlookApi;
using NetOffice.OutlookApi.Enums;

namespace FEQ0000
{
    public partial class fPurchase : FCOMMON.fBase
    {
        string fn_fpcolsize = "";

        public fPurchase()
        {
            InitializeComponent();
            fn_fpcolsize = util.MakeFilePath(util.CurrentPath, "formSetting", "fp_" + this.Name + ".ini");
            this.dsPurchase.Purchase.TableNewRow += Purchase_TableNewRow;
            this.FormClosing += FPurchase_FormClosing;
            this.FormClosed += __Closed;
            dtSD.KeyDown += dtSD_KeyDown;
            dtED.KeyDown += dtSD_KeyDown;
            //this.dv1.CellFormatting += dv1_CellFormatting;
        }

        private void FPurchase_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (dsPurchase.HasChanges())
            {
                var dlg = FCOMMON.Util.MsgQ("변경된 자료가 있습니다. 화면을 닫을까요? 닫으면 변경된 자료는 손실 됩니다");
                if (dlg != DialogResult.Yes)
                {
                    e.Cancel = true;
                    return;
                }
            }
        }

        void dtSD_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter) return;
            var tb = sender as ToolStripTextBox;
            var input = tb.Text.Trim();
            if (input == "") tb.Text = DateTime.Now.ToShortDateString();
            else
            {
                string dt = string.Empty;
                if (!util.MakeDateString(input, out dt))
                {
                    FCOMMON.Util.MsgE("입력값이 올바르지 않습니다.");
                    tb.SelectAll();
                    tb.Focus();
                    return;
                }
                else
                {
                    tb.Text = dt;
                }
            }
            if (tb == dtSD)
            {
                dtED.Focus();
                dtED.SelectAll();
            }
            else
            {
                btSearch.PerformClick();
                tb.SelectAll();
            }
        }

        void __Closed(object sender, FormClosedEventArgs e)
        {

        }

        void Purchase_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["gcode"] = FCOMMON.info.Login.gcode;
            e.Row["pdate"] = DateTime.Now.ToShortDateString();
            e.Row["wuid"] = FCOMMON.info.Login.no;
            e.Row["wdate"] = DateTime.Now;
            e.Row["pumunit"] = "EA";
            e.Row["state"] = "---";
            e.Row["pumqty"] = 1;
            e.Row["pumprice"] = 0;
            e.Row["pumamt"] = 0;
            e.Row["request"] = FCOMMON.info.Login.nameK;
            e.Row["receive"] = "";// FCOMMON.info.Login.nameK;
        }

        private void __Load(object sender, EventArgs e)
        {
            this.cmDate.SelectedIndex = 0;
            this.tbRequest.Text = string.Empty; //양진원 FCOMMON.info.Login.nameK;
            this.cmbSort.SelectedIndex = 0;
            this.dtSD.Text = DateTime.Now.AddDays(-30).ToShortDateString();
            this.dtED.Text = DateTime.Now.AddDays(10).ToShortDateString();

            //state list
            var stList = FCOMMON.DBM.getCodeList("04");
            this.cmbState.Items.Clear();
            cmbState.Items.Add("-- 전체 --");
            foreach (var item in stList)
                cmbState.Items.Add(item.Value);
            cmbState.Items.Add("<=Received");
            this.cmbState.SelectedIndex = 0;    //all기본 - 양진원
            //this.cmbCr.SelectedIndex = 1;

            //일반사용자의경우에는 상태를 변경하지 못한다.
            int curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.purchase));
            if (curLevel >= 5)
            {
                btSave.Visible = true;
            }
            else
            {
                btSave.Visible = false;
                btViewDel.Visible = false;
                fpSpread1.EditMode = false;
                fpSpread1.Sheets[0].SelectionUnit = FarPoint.Win.Spread.Model.SelectionUnit.Row;
                fpSpread1.EditModePermanent = false;
                fpSpread1.EditModeReplace = false;

                foreach (FarPoint.Win.Spread.Column col in fpSpread1.ActiveSheet.Columns)
                    col.Locked = true;
            }

            if (curLevel < 5)
            {
                집계표ToolStripMenuItem.Visible = false;
            }

            refreshData();

            //열표시여부를 설정
            var adv = FCOMMON.Util.getBit(FCOMMON.info.Login.gpermission, (int)FCOMMON.eGroupPermission.purchase_adv);
            if (adv == false)
            {
                var hidecols = new string[] { "receivename", "receive", "asset", "dept", "manuproc", "process", "cr", "orderno", "manuproc", "project", "projectidx", "edate", "po" };
                foreach (FarPoint.Win.Spread.Column col in fpSpread1_Sheet1.Columns)
                {
                    if (hidecols.Contains(col.DataField.ToLower())) col.Visible = false;
                }
            }
        }


        private void refreshData()
        {

            try
            {
                string state = "%";
                if (cmbState.SelectedIndex > 0) state = cmbState.Text.Split(',')[0];

                string request = "%";
                if (tbRequest.Text.Trim() != "")
                    request = "%" + tbRequest.Text.Trim() + "%";// tbRequest.Text.Substring(1, tbRequest.Text.IndexOf("]") - 1);


                string dateField = "pdate";
                if (cmDate.SelectedIndex == 1) dateField = "indate";
                else if (cmDate.SelectedIndex == 2) dateField = "expdate";


                System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter();
                System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
                cmd.CommandText = " select *,dbo.getusername(request) as requestName,dbo.getusername(receive) as receiveName" +
                                   " from purchase " +
                                   " where gcode='" + FCOMMON.info.Login.gcode + "' and  isnull(" + dateField + ",'') between @sd and @ed ";



                if (btViewDel.Checked == false)
                    cmd.CommandText += " and isnull(isdel,0) = 0";


                if (tbRequest.Text.Trim() != "")
                {
                    cmd.CommandText += " and (isnull(dbo.getusername(request),'') like @req or isnull(dbo.getusername(receive),'') like @req)";
                }


                if (cmbState.SelectedIndex != 0)
                {
                    if (cmbState.Text.ToUpper() == "<=RECEIVED")
                    {
                        cmd.CommandText += " and isnull([state],'') in ('','---','Approving','PR','PO')";
                    }
                    else
                    {
                        cmd.CommandText += " and isnull([state],'') like @st";
                    }
                }
                // else cmd.CommandText += " and (state < '04' or state > '07')";


                if (cmbSort.SelectedIndex == 1) dateField = "edate";
                else if (cmbSort.SelectedIndex == 2) dateField = "sc";

                cmd.CommandText += " ORDER BY " + dateField + " DESC, idx DESC";

                cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@sd", dtSD.Text));
                cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ed", dtED.Text));
                cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@req", request));
                cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@st", state));
                cmd.Connection = this.ta.Connection;
                da.SelectCommand = cmd;

                //read adata
                this.dsPurchase.Purchase.Clear();
                da.Fill(this.dsPurchase.Purchase);
                this.dsPurchase.AcceptChanges();
                showSummary();
                FCOMMON.Util.FPColSizeLoad(ref this.fpSpread1, fn_fpcolsize);
            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }

            FormattingData();
        }
        void FormattingData()
        {
            //삭제컬럼인덱스
            this.fpSpread1.SuspendLayout();
            var delindex = this.fpSpread1.ActiveSheet.Columns["isdel"].Index;
            var statindex = this.fpSpread1.ActiveSheet.Columns["state"].Index;
            var crcfindex = this.fpSpread1.ActiveSheet.Columns["crcf"].Index;
            var prjindex = this.fpSpread1.ActiveSheet.Columns["projectidx"].Index;


            for (int i = 0; i < this.fpSpread1.ActiveSheet.Rows.Count; i++)
            {
                var state = this.fpSpread1.ActiveSheet.GetValue(i, statindex);
                string stateStr = string.Empty;
                if (state != null) stateStr = state.ToString();

                var value = this.fpSpread1.ActiveSheet.GetValue(i, delindex);
                var crcf = this.fpSpread1.ActiveSheet.GetValue(i, crcfindex);

                var str_crcf = string.Empty;
                if (crcf != null) str_crcf = crcf.ToString();


                if (value != null && (Boolean)value)
                {
                    this.fpSpread1.ActiveSheet.Rows[i].BackColor = Color.Red;
                    this.fpSpread1.ActiveSheet.Rows[i].ForeColor = Color.White;
                }
                else
                {
                    //crcf 에 따라서 배경색 변경
                    if (str_crcf != "")
                        this.fpSpread1.ActiveSheet.Rows[i].BackColor = Color.FromArgb(50, Color.PowderBlue);
                    else
                        this.fpSpread1.ActiveSheet.Rows[i].BackColor = Color.White;


                    switch (stateStr.ToLower())
                    {
                        case "cancled":
                            this.fpSpread1.ActiveSheet.Rows[i].ForeColor = Color.Red;
                            break;
                        case "rejected":
                            this.fpSpread1.ActiveSheet.Rows[i].ForeColor = Color.Tomato;
                            break;
                        case "spr":
                            this.fpSpread1.ActiveSheet.Rows[i].ForeColor = Color.Magenta;
                            break;
                        case "---":
                        case "----":
                            this.fpSpread1.ActiveSheet.Rows[i].ForeColor = Color.Blue;
                            break;
                        case "received":
                            this.fpSpread1.ActiveSheet.Rows[i].ForeColor = Color.Gray;
                            break;
                        case "hold":
                            this.fpSpread1.ActiveSheet.Rows[i].ForeColor = Color.HotPink;
                            break;
                        default:
                            this.fpSpread1.ActiveSheet.Rows[i].ForeColor = Color.Black;
                            break;
                    }
                }

                //프로젝트가 걸린데이터는 글자를 bold체로 변경한다.
                var prjdata = this.fpSpread1.ActiveSheet.GetValue(i, prjindex);
                if (prjdata != null)
                {
                    var pidx = (int)this.fpSpread1.ActiveSheet.GetValue(i, prjindex);
                    if (pidx == -1)  //프로젝트가 없다
                    {
                        this.fpSpread1.ActiveSheet.Rows[i].Font = fBase;
                    }
                    else
                    {
                        this.fpSpread1.ActiveSheet.Rows[i].Font = fBold;
                    }
                }
                else this.fpSpread1.ActiveSheet.Rows[i].Font = fBold;


            }
            this.fpSpread1.ResumeLayout();
        }

        Font fBase = new Font("맑은 고딕", 9);
        Font fBold = new Font("맑은 고딕", 9, FontStyle.Bold);

        private void saveData(Boolean prompt)
        {
            this.Validate();
            this.bs.EndEdit();
            try
            {
                var cnt = this.tam.UpdateAll(this.dsPurchase);
                if (prompt) FCOMMON.Util.MsgI(string.Format("{0}건의 자료가 저장 되었습니다.", cnt));
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE("저장 실패\n" + ex.Message);
            }


        }
        void showSummary()
        {
            decimal sum = 0;
            var list = this.dsPurchase.Purchase.Select(this.bs.Filter, "") as dsPurchase.PurchaseRow[];
            sum = list.Sum(t => t.pumamt);
            //foreach (dsPurchase.PurchaseRow dr in this.dsPurchase.Purchase.Rows)
            //if (!dr.IspumamtNull()) sum += dr.pumamt;
            lbSum.Text = sum.ToString("N0");
        }

        private void btSearch_Click(object sender, EventArgs e)
        {
            refreshData();
        }

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

        private void tbRequest_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                btSearch.PerformClick();
        }

        private void btSave_Click(object sender, EventArgs e)
        {
            saveData(true);
        }


        private void lbEnd_Click(object sender, EventArgs e)
        {
            //end date
            var list = FCOMMON.DBM.getGroupList("pdate", "purchase", "pdate >= '" + dtSD.Text + "'", true);
            FCM0000.fLovOneItem f = new FCM0000.fLovOneItem(list);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                dtED.Text = f.Title;
                btSearch.PerformClick();
            }
        }

        private void toolStripLabel3_Click(object sender, EventArgs e)
        {
            //사용자목록처리
            if (tbRequest.Text.Trim() == "")
            {
                tbRequest.Text = FCOMMON.info.Login.nameK;
            }
            else
            {
                tbRequest.Text = string.Empty;
            }

            refreshData();
        }

        private bool getAdminInput
        {
            get
            {
                return FCOMMON.Util.getBit(
                FCOMMON.info.Login.gpermission,
                (int)FCOMMON.eGroupPermission.purchase_adv);
            }
        }

        private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e)
        {
            func_delete();
        }
        void func_add()
        {
            var newdr = this.dsPurchase.Purchase.NewPurchaseRow();

            if (FCOMMON.info.Login.no == "dev")
                newdr.request = "395552";//string.Format("[{0}] {1}", "395552", "김치균");
            else
                newdr.request = FCOMMON.info.Login.no;

            repeat:

            bool repeat = false;
            DialogResult dlg;
            if (getAdminInput == false)
            {
                repeat = false;
                var f = new fPurchase_AddS(newdr);
                dlg = f.ShowDialog();
            }
            else
            {
                var f = new fPurchase_Add(newdr);
                dlg = f.ShowDialog();
                repeat = f.repeatAdd;
            }

            if (dlg == System.Windows.Forms.DialogResult.OK)
            {
                //존재하지 않는 sid 는 추가를 해준다.
                var newidx = AddItemInfoGetIndex(newdr);
                if (newidx != -1)
                {
                    newdr.pumidx = newidx;
                    newdr.EndEdit();
                }

                this.dsPurchase.Purchase.AddPurchaseRow(newdr);

                int cnt = this.ta.Update(newdr);
                if (cnt == 1)
                {
                    if (repeat)
                    {
                        FCOMMON.Util.MsgI("저장 완료\n\n연속 저장 모드이므로 직전에 입력된 자료가 자동으로 설정 됩니다.");

                    }
                    else FCOMMON.Util.MsgI("저장 완료");
                }
                else
                {
                    FCOMMON.Util.MsgE("저장 실패\n\n다시 시도하시고 증상이 반복되면 chikyun.kim@amkor.co.kr 로 문의 주십시요");
                }


                newdr.AcceptChanges();
                if (repeat)
                {
                    var newdro = this.dsPurchase.Purchase.NewPurchaseRow();
                    FCOMMON.Util.CopyData(newdr, newdro);
                    newdro.idx = -1;
                    newdro.wdate = DateTime.Now;
                    newdr = newdro; //change
                    goto repeat;
                }
                else refreshData(); //181210
            }
            else newdr.Delete();



        }
        void func_delete()
        {
            var drv = bs.Current as DataRowView;
            if (drv == null) return;

            int curLevel = Math.Max(FCOMMON.info.Login.level, FCOMMON.DBM.getAuth(FCOMMON.DBM.eAuthType.purchase));
            var dr = drv.Row as dsPurchase.PurchaseRow;
            if (dr.sc != "")
            {
                if (curLevel < 5)
                {
                    FCOMMON.Util.MsgE("일반 사용자는 SC값이 있는 자료를 삭제할 수 없습니다.");
                    return;
                }
            }

            if (dr.request != FCOMMON.info.Login.no)
            {
                if (curLevel < 5)
                {
                    FCOMMON.Util.MsgE("일반 사용자는 타인의 자료를 삭제할 수 없습니다.");
                    return;
                }
            }

            if (curLevel < 5)
            {
                var dlg = FCOMMON.Util.MsgQ("현재 선택된 자료를 삭제하시겠습니까?");
                if (dlg != System.Windows.Forms.DialogResult.Yes) return;
            }
            else 
            {
                var dlg = FCOMMON.Util.MsgQ("현재 선택된 자료를 삭제하시겠습니까?\n저장 버튼을 눌러야 최종 삭제 됩니다");
                if (dlg != System.Windows.Forms.DialogResult.Yes) return;
            }

            bs.RemoveCurrent();

            //일반사용자는 데이터를 바로 삭제한다.
            if (curLevel < 5)
            {
                try
                {
                    int cnt = ta.Update(this.dsPurchase);
                    if (cnt != 1)
                        FCOMMON.Util.MsgE(cnt.ToString() + "건의 자료가 삭제되었습니다.");
                }
                catch (Exception ex)
                {
                    FCOMMON.Util.MsgE("delete error\n" + ex.Message);
                }
            }
        }

        private int AddItemInfoGetIndex(dsPurchase.PurchaseRow newdr)
        {
            //이 시드가 아이템목록에 없다면 추가 하고 idx를 조회한 후 설정해준다.
            if (newdr.sid == "신규") return -1;
            int retval = -1;
            var sid = newdr.sid;
            var iteminfo = FCOMMON.DBM.getItemInfo(sid);
            if (iteminfo.idx < 0)
            {
                FCOMMON.DBM.sItemInfo newitem = new FCOMMON.DBM.sItemInfo();
                newitem.sid = newdr.sid;
                newitem.name = newdr.pumname;
                newitem.price = newdr.pumprice.ToString();
                newitem.model = newdr.pumscale;
                newitem.unit = newdr.pumunit;
                newitem.scale = 1f;
                newitem.supply = newdr.supply;
                newitem.supplyidx = newdr.supplyidx;
                retval = FCOMMON.DBM.addItemInfo(newitem);
            }
            return retval;
        }

        private void copyDataToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void btFind_Click(object sender, EventArgs e)
        {
            var search = tbFind.Text.Trim();
            search = search.Replace("*", "x");
            if (tbFind.Text != search) tbFind.Text = search;
            try
            {
                if (search.isEmpty())
                {
                    this.bs.Filter = "";
                    tbFind.BackColor = Color.White;
                }
                else
                {
                    search = search.Replace("'", "''");
                    string filter = "supply like ? or sid like ? or process like ? or orderno like ? or sc like ? or pumname like ? or pumscale like ? or project like ?";
                    filter = filter.Replace("?", "'%" + search + "%'");
                    this.bs.Filter = filter;
                    tbFind.BackColor = Color.Lime;
                }
                tbFind.SelectAll();
                tbFind.Focus();
                showSummary();
            }
            catch (Exception ex)
            {
                this.tbFind.BackColor = Color.Tomato;
                FCOMMON.Util.MsgE(ex.Message);
            }
        }

        private void tbFind_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) btFind.PerformClick();
        }

        private void editDataToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Func_Edit();
        }
        void Func_Edit()
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var newdr = drv.Row as dsPurchase.PurchaseRow;

            bool repeat = false;
            DialogResult dlg;
            if (getAdminInput == false)
            {
                repeat = false;
                var f = new fPurchase_AddS(newdr);
                dlg = f.ShowDialog();
            }
            else
            {
                var f = new fPurchase_Add(newdr);
                dlg = f.ShowDialog();
                repeat = f.repeatAdd;
            }

            if (dlg == System.Windows.Forms.DialogResult.OK)
            {
                //존재하지 않는 sid 는 추가를 해준다.
                var newidx = AddItemInfoGetIndex(newdr);
                if (newidx != -1)
                {
                    newdr.pumidx = newidx;
                    newdr.EndEdit();
                }
                if (newdr.RowState != DataRowState.Unchanged)
                {
                    this.ta.Update(newdr);
                    newdr.AcceptChanges();
                }
            }
            else newdr.RejectChanges();

        }

        private void autoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FCOMMON.Util.FPColSizeAuto(this.fpSpread1);
            //this.fpSpread1.ActiveSheet.DataAutoSizeColumns = true;

            //for (int i = 0; i < this.fpSpread1.ActiveSheet.Rows.Count; i++)
            //    this.fpSpread1.ActiveSheet.SetRowHeight(i, 25);
            //dv1.AutoResizeColumns();
        }

        private void resetToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (FarPoint.Win.Spread.Column col in this.fpSpread1.ActiveSheet.Columns)
            {
                col.Width = 100;
            }
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FCOMMON.Util.FPColsizeSave(this.fpSpread1, fn_fpcolsize);
        }

        private void loadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FCOMMON.Util.FPColSizeLoad(ref this.fpSpread1, fn_fpcolsize);
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            Func_Edit();
        }


        void dv1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            //if (e.ColumnIndex < 0 || e.RowIndex < 0) return;
            //var state = this.dv1.Rows[e.RowIndex].Cells["dvc_state"].Value.ToString();
            //switch (state)
            //{
            //    case "00":  //입력대기(미확인)
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.ForeColor = Color.Black;
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.LightGray;
            //        break;
            //    case "01":  //파트장 승인 기다림
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.ForeColor = Color.DarkBlue;
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.White;
            //        break;
            //    case "03":  //PO (협력업체 전달)
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.ForeColor = Color.DarkMagenta;
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.White;
            //        break;
            //    case "04":  //자재 수령
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.White;
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.ForeColor = Color.Green;
            //        break;
            //    case "05": //canceld (취소)
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.LightGray;
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.ForeColor = Color.Red;
            //        break;
            //    case "06":  //cancel (취소됨)
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.HotPink;
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.ForeColor = Color.Black;
            //        break;
            //    case "08":  //문의
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.Green;
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.ForeColor = Color.White;
            //        break;
            //    default:
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.White;
            //        this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.ForeColor = Color.Black;
            //        break;
            //}
        }

        private void updateSCToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var dlg = FCOMMON.Util.MsgQ("#SC가 없는 자료에 한하여 일괄 기록을 실행 합니다.");
            if (dlg == System.Windows.Forms.DialogResult.Yes)
            {

            }
        }

        private void exportDataToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sd = new SaveFileDialog();
            sd.Filter = "excel|*.xls";
            sd.FileName = "nrplist.xls";
            if (sd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                fpSpread1.SaveExcel(sd.FileName,
                    FarPoint.Excel.ExcelSaveFlags.SaveAsViewed
                    | FarPoint.Excel.ExcelSaveFlags.SaveAsFiltered
                    | FarPoint.Excel.ExcelSaveFlags.NoFormulas
                    | FarPoint.Excel.ExcelSaveFlags.SaveCustomColumnHeaders);
                FCOMMON.Util.MsgI("다음 파일이 생성 되었습니다.\n\n" + sd.FileName);
            }

        }

        private void 내가등록한자료ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            cmDate.SelectedIndex = 0;
            dtSD.Text = DateTime.Now.AddMonths(-1).ToShortDateString();
            dtED.Text = DateTime.Now.ToShortDateString();
            cmbState.SelectedIndex = 0;
            tbRequest.Text = FCOMMON.info.Login.nameK;
            refreshData();
        }

        private void 금일입고품목ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            cmDate.SelectedIndex = 1; //입고일
            dtSD.Text = DateTime.Now.ToShortDateString();   //당일
            dtED.Text = DateTime.Now.ToShortDateString();
            tbRequest.Text = string.Empty;
            refreshData();
        }

        private void 이번달자료ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            dtSD.Text = DateTime.Now.ToString("yyyy-MM") + "-01";
            dtED.Text = DateTime.Now.ToShortDateString();
            tbRequest.Text = string.Empty;
            refreshData();
        }

        private void btViewDel_Click(object sender, EventArgs e)
        {
            refreshData();
        }


        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        void func_copy()
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsPurchase.PurchaseRow;

            //현재 데이터를 입력하여 신규 추가를 한다.
            var newdr = this.dsPurchase.Purchase.NewPurchaseRow();
            FCOMMON.Util.CopyData((System.Data.DataRow)dr, (System.Data.DataRow)newdr);
            newdr.orderno = string.Empty; //CR값 복사 안하게  210823
            newdr.pdate = DateTime.Now.ToShortDateString();
            newdr.wdate = DateTime.Now;
            newdr.wuid = FCOMMON.info.Login.no;
            newdr.state = "---";
            newdr.request = FCOMMON.info.Login.no;
            newdr.receive = "";// FCOMMON.info.Login.nameK;
            newdr.sc = string.Empty;
            newdr.po = string.Empty;
            newdr.indate = string.Empty;
            newdr.edate = string.Empty;
            newdr.idx = -1;
            newdr.EndEdit();

        repeat:

            bool repeat = false;
            DialogResult dlg;
            if (getAdminInput == false)
            {
                var f = new fPurchase_AddS(newdr);
                dlg = f.ShowDialog();
            }
            else
            {
                var f = new fPurchase_Add(newdr);
                dlg = f.ShowDialog();
                repeat = f.repeatAdd;
            }

            if (dlg == System.Windows.Forms.DialogResult.OK)
            {
                //존재하지 않는 sid 는 추가를 해준다.
                var newidx = AddItemInfoGetIndex(newdr);
                if (newidx != -1)
                {
                    newdr.pumidx = newidx;
                    newdr.EndEdit();
                }

                this.dsPurchase.Purchase.AddPurchaseRow(newdr);
                this.ta.Update(newdr);
                newdr.AcceptChanges();

                if (repeat)
                {
                    var newdro = this.dsPurchase.Purchase.NewPurchaseRow();
                    FCOMMON.Util.CopyData(newdr, newdro);
                    newdro.idx = -1;
                    newdro.wdate = DateTime.Now;
                    newdr = newdro; //change
                    goto repeat;
                }
            }
            else newdr.Delete();
        }

        private void toolStripButton1_Click_2(object sender, EventArgs e)
        {
            func_copy();
        }

        private void 집계표ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Purchase.rPurchase f = new Purchase.rPurchase();
            f.MdiParent = this.MdiParent;
            f.Show();
        }

        private void makeRepeatToolStripMenuItem_Click(object sender, EventArgs e)
        {
            func_copy();
        }

        private void 편집ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Func_Edit();
        }

        private void 삭제ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            func_delete();
        }

        private void 추가ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            func_add();
        }

        private void toolStripButton2_Click_1(object sender, EventArgs e)
        {
            this.Close();
        }

        private void sC검색ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //sc
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var newdr = drv.Row as dsPurchase.PurchaseRow;
            if (newdr.sc.Trim() == "")
            {
                FCOMMON.Util.MsgE("SC값이 없습니다");
                return;
            }
            tbFind.Text = newdr.sc;
            btFind.PerformClick();
        }

        private void cRCF검색ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //crcf
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var newdr = drv.Row as dsPurchase.PurchaseRow;
            if (newdr.orderno.Trim() == "")
            {
                FCOMMON.Util.MsgE("CR/CF값이 없습니다");
                return;
            }
            tbFind.Text = newdr.orderno;
            btFind.PerformClick();
        }

        private void toolStripLabel2_Click(object sender, EventArgs e)
        {
            if (tbFind.Text != "")
            {
                tbFind.Text = "";
                btFind.PerformClick();
            }

        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {

        }

        private void bs_CurrentChanged(object sender, EventArgs e)
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null)
            {
                this.label1.Text = "데이터가 선택되지 않았습니다";
                return;
            }
            var dr = drv.Row as dsPurchase.PurchaseRow;
            this.label1.Text = string.Format("{0}", dr.bigo.Replace("\r", "").Replace("\n", ""));
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {

        }

        string getmaxstr(string src, int len = 30)
        {
            if (src.Length > len) return src.Substring(0, len) + "...";
            else return src;
        }

        List<string> ChangeMailAddress(List<string> userid)
        {
            var db = new DataClasses1DataContext();

            List<string> retval = new List<string>();
            foreach (var id in userid)
            {
                UInt32 userno;
                if (UInt32.TryParse(id, out userno) == true)
                {
                    var user = db.Users.Where(t => t.id == id).FirstOrDefault();
                    if (user != null)
                    {
                        var data = string.Format("{0}<{1}>", user.name, user.email);
                        if (retval.Contains(data) == false)
                            retval.Add(data);
                    }
                }
                else
                {
                    if (retval.Contains(id) == false)
                        retval.Add(id);
                }
            }
            return retval;
        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {


        }

        private void 구매승인양식ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //구매승인양식
            var f = new fPurchaseNRList(this.dsPurchase.Purchase);
            f.Show();

        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            //선택된 줄의 데이터를 생성하낟.
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsPurchase.PurchaseRow;
            string buffer = string.Format("{0}_{1}", dr.pumname.Replace("_", "-"), dr.pumscale.Replace("_", "-"), dr.dept.Replace("_", "-"), dr.manuproc.Replace("_", "-"), dr.asset.Replace("_", "-"));
            Clipboard.SetText(buffer);
            //FCOMMON.Util.MsgI("다음 데이터가 클립보드에 저장됨\n\n" + buffer);  190131
        }

        private void dtSD_DoubleClick(object sender, EventArgs e)
        {
            var tb = sender as ToolStripTextBox;
            var text = tb.Text.Trim();
            var dt = DateTime.Parse(text);
            var f = new FCOMMON.fSelectDay(dt);
            if (f.ShowDialog() == DialogResult.OK)
            {
                tb.Text = f.dtPick.SelectionStart.ToShortDateString();

                var sd = DateTime.Parse(this.dtSD.Text);
                var ed = DateTime.Parse(this.dtED.Text);
                if (ed < sd) this.dtED.Text = sd.ToShortDateString();
            }
        }

        private void 견적서폴더열기ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string path = "\\\\k4fs3201n\\ee1t$\\1. 장비기술1파트\\24_Project & Overhaul 예산 사용 실적\\구매 견적서\\" + DateTime.Now.Year.ToString("0000") + "년";
            FCOMMON.Util.RunExplorer(path);
        }

        private void 엑셀에서가져오기ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var f = new fPurchase_excelimport();
            f.Show();
        }

        private void 입고품목메일전송ToolStripMenuItem_Click(object sender, EventArgs e)
        {

            var db = new DataClasses1DataContext();
            var dr = db.MailForm.Where(t => t.cate == "PC").FirstOrDefault();

            //현재표시데이터중에 수신자목록을 가져온다
            var drows = (dsPurchase.PurchaseRow[])(this.dsPurchase.Purchase.Select(this.bs.Filter, this.bs.Sort));
            var grp_req = drows.Where(t => t.request.isEmpty() == false).GroupBy(t => t.request).Select(t => t.FirstOrDefault().request).ToList();
            var grp_rec = drows.Where(t => t.receive.isEmpty() == false).GroupBy(t => t.receive).Select(t => t.FirstOrDefault().receive).ToList();

            var f = new Purchase.fMailForm();
            if (f.ShowDialog() != DialogResult.OK) return;

            var form_subject = f.tbSubject.Text.Trim();
            var form_body = f.htmlEditor1.Html;
            var form_to = f.tbTo.Text.Trim();
            var form_cc = f.tbCC.Text.Trim();
            var form_bcc = f.tbBcc.Text.Trim();

            List<string> tolist = new List<string>();   //최종받는사람
            List<string> cclist = new List<string>();
            List<string> bcclist = new List<string>();

            //받는사람
            if (form_to.Contains("{요청}") == true) tolist.AddRange(grp_req);
            if (form_to.Contains("{수령}") == true) tolist.AddRange(grp_rec);
            form_to = form_to.Replace("{요청}", "");
            form_to = form_to.Replace("{수령}", "");
            tolist.AddRange(form_to.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
            tolist = ChangeMailAddress(tolist);

            //참조
            if (form_cc.Contains("{요청}") == true) cclist.AddRange(grp_req);
            if (form_cc.Contains("{수령}") == true) cclist.AddRange(grp_rec);
            form_cc = form_cc.Replace("{요청}", "");
            form_cc = form_cc.Replace("{수령}", "");
            cclist.AddRange(form_cc.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
            cclist = ChangeMailAddress(cclist);

            //숨은참조
            if (form_bcc.Contains("{요청}") == true) bcclist.AddRange(grp_req);
            if (form_bcc.Contains("{수령}") == true) bcclist.AddRange(grp_rec);
            form_bcc = form_bcc.Replace("{요청}", "");
            form_bcc = form_bcc.Replace("{수령}", "");
            bcclist.AddRange(form_bcc.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
            bcclist = ChangeMailAddress(bcclist);

            var datestr = DateTime.Now.ToShortDateString();
            if (dtSD.Text == dtED.Text) datestr = dtSD.Text;
            else datestr = dtSD.Text + "~" + dtED.Text;
            form_subject = form_subject.Replace("{DATE}", datestr);

            try
            {
                Outlook.Application outlookApplication = new Outlook.Application();
                var newMail = outlookApplication.CreateItem(OlItemType.olMailItem) as Outlook.MailItem;
                newMail.Display();
                newMail.Subject = form_subject; // this.tbSubject.Text.Trim(); // dr.title;
                newMail.To = string.Join(";", tolist.ToArray());
                newMail.CC = string.Join(";", cclist.ToArray());
                newMail.BCC = string.Join(";", bcclist.ToArray());
                if (f.chkAttach.Checked)
                {
                    var fi = new System.IO.FileInfo(FCOMMON.Util.CurrentPath + "\\Export\\Purchase_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xls");
                    if (fi.Directory.Exists == false) fi.Directory.Create();

                    ///save file
                    fpSpread1.SaveExcel(fi.FullName,
                           FarPoint.Excel.ExcelSaveFlags.SaveAsViewed
                           | FarPoint.Excel.ExcelSaveFlags.SaveAsFiltered
                           | FarPoint.Excel.ExcelSaveFlags.NoFormulas
                           | FarPoint.Excel.ExcelSaveFlags.SaveCustomColumnHeaders);

                    newMail.Attachments.Add(fi.FullName);
                }
                if (f.chkList.Checked)
                {
                    //목록을 본문에 추가한다
                    System.Text.StringBuilder sb = new StringBuilder();
                    sb.AppendLine("<table border='1' cellspacing='0' cellpadding='1'>");
                    sb.AppendLine("<thead>");
                    sb.AppendLine("<td style='text-align:center;background-color: aqua;'>신청</td>");
                    sb.AppendLine("<td style='text-align:center;background-color: aqua;'>요청</td>");
                    sb.AppendLine("<td style='text-align:center;background-color: aqua;'>CR/CF</td>");
                    sb.AppendLine("<td style='text-align:center;background-color: aqua;'>수령</td>");
                    sb.AppendLine("<td style='text-align:center;background-color: aqua;'>SID</td>");
                    sb.AppendLine("<td style='text-align:center;background-color: aqua;'>품명</td>");
                    sb.AppendLine("<td style='text-align:center;background-color: aqua;'>규격</td>");
                    sb.AppendLine("<td style='text-align:center;background-color: aqua;'>수량</td>");
                    sb.AppendLine("<td style='text-align:center;background-color: aqua;'>단가</td>");
                    sb.AppendLine("<td style='text-align:center;background-color: aqua;'>금액</td>");
                    sb.AppendLine("<td style='text-align:center;background-color: aqua;'>공급</td>");
                    sb.AppendLine("</thead>");
                    sb.AppendLine("<tbody>");

                    var col_신청 = fpSpread1_Sheet1.Columns["pdate"].Index;
                    var col_요청 = fpSpread1_Sheet1.Columns["requestName"].Index;
                    var col_CRLF = fpSpread1_Sheet1.Columns["crcf"].Index;

                    var col_수령 = fpSpread1_Sheet1.Columns["receiveName"].Index;
                    var col_SID = fpSpread1_Sheet1.Columns["sid"].Index;
                    var col_품명 = fpSpread1_Sheet1.Columns["pumname"].Index;
                    var col_규격 = fpSpread1_Sheet1.Columns["pumscale"].Index;
                    var col_수량 = fpSpread1_Sheet1.Columns["pumqty"].Index;
                    var col_단가 = fpSpread1_Sheet1.Columns["pumprice"].Index;
                    var col_금액 = fpSpread1_Sheet1.Columns["pumamt"].Index;
                    var col_공급 = fpSpread1_Sheet1.Columns["supply"].Index;
                    var col_비고 = fpSpread1_Sheet1.Columns["bigo"].Index;


                    for (int i = 0; i < this.fpSpread1_Sheet1.RowCount; i++)
                    {
                        var v신청 = fpSpread1_Sheet1.Cells[i, col_신청].Value;
                        var v요청 = fpSpread1_Sheet1.Cells[i, col_요청].Value;
                        var vCRCF = fpSpread1_Sheet1.Cells[i, col_CRLF].Value;

                        var v수령 = fpSpread1_Sheet1.Cells[i, col_수령].Value;
                        var vSID = fpSpread1_Sheet1.Cells[i, col_SID].Value;
                        var v품명 = fpSpread1_Sheet1.Cells[i, col_품명].Value;
                        var v규격 = fpSpread1_Sheet1.Cells[i, col_규격].Value;
                        var v수량 = fpSpread1_Sheet1.Cells[i, col_수량].Value;
                        var v단가 = fpSpread1_Sheet1.Cells[i, col_단가].Value;
                        var v금액 = fpSpread1_Sheet1.Cells[i, col_금액].Value;
                        var v공급 = fpSpread1_Sheet1.Cells[i, col_공급].Value;
                        var v비고 = fpSpread1_Sheet1.Cells[i, col_비고].Value;

                        var s신청 = String.Empty;
                        var s요청 = String.Empty;
                        var sCRCF = String.Empty;
                        var s수령 = String.Empty;
                        var sSID = String.Empty;
                        var s품명 = String.Empty;
                        var s규격 = String.Empty;
                        var s수량 = "0";
                        var s단가 = "0";
                        var s금액 = "0";
                        var s입고 = String.Empty;
                        var s공급 = String.Empty;
                        var s비고 = String.Empty;

                        if (v신청 != null) s신청 = v신청.ToString();
                        if (v요청 != null) s요청 = v요청.ToString();
                        if (vCRCF != null) sCRCF = vCRCF.ToString();
                        if (v수령 != null) s수령 = v수령.ToString();
                        if (vSID != null) sSID = vSID.ToString();
                        if (v품명 != null) s품명 = v품명.ToString();
                        if (v규격 != null) s규격 = v규격.ToString();
                        if (v수량 != null) s수량 = v수량.ToString();
                        if (v단가 != null) s단가 = v단가.ToString();
                        if (v금액 != null) s금액 = v금액.ToString();
                        if (v공급 != null) s공급 = v공급.ToString();

                        sb.AppendLine("<tr>");
                        sb.AppendLine("<td>" + getmaxstr(s신청) + "</td>");
                        sb.AppendLine("<td>" + getmaxstr(s요청) + "</td>");
                        sb.AppendLine("<td>" + getmaxstr(sCRCF) + "</td>");
                        sb.AppendLine("<td>" + getmaxstr(s수령) + "</td>");
                        sb.AppendLine("<td>" + getmaxstr(sSID) + "</td>");
                        sb.AppendLine("<td>" + getmaxstr(s품명) + "</td>");
                        sb.AppendLine("<td>" + getmaxstr(s규격) + "</td>");
                        sb.AppendLine("<td style='text-align:center'>" + int.Parse(s수량).ToString("N0") + "</td>");
                        sb.AppendLine("<td style='text-align:right'>" + int.Parse(s단가).ToString("N0") + "</td>");
                        sb.AppendLine("<td style='text-align:right'>" + int.Parse(s금액).ToString("N0") + "</td>");
                        sb.AppendLine("<td>" + getmaxstr(s공급) + "</td>");

                        sb.AppendLine("</tr>");
                    }
                    sb.AppendLine("</tbody>");
                    sb.AppendLine("</table>");
                    form_body += sb.ToString();
                }

                //newMail.BodyFormat = OlBodyFormat.olFormatHTML;
                form_body = form_body.Replace("{DATE}", datestr);
                newMail.HTMLBody = form_body + newMail.HTMLBody; //
            }
            catch (Exception ex)
            {
                util.MsgE("전송실패\n\n" + ex.Message + "\n\n" +
                    "아웃룩의 설정이 정상인지 확인하세요");
            }
        }

        private void toolStripButton3_Click_1(object sender, EventArgs e)
        {
            var fn = System.IO.Path.Combine(FCOMMON.Util.CurrentPath, "PurcManual.pdf");
            if (System.IO.File.Exists(fn))
            {
                FCOMMON.Util.RunExplorer(fn);
            }
            else FCOMMON.Util.MsgE("설명서 파일(manual.pdf)이 없습니다. 개발자 문의 해주세요(chikyun.kim@amkor.co.kr)");
        }

        private void fpSpread1_EditModeOff(object sender, EventArgs e)
        {
            if (fpSpread1_Sheet1.Columns["pumqty"].Index == fpSpread1_Sheet1.ActiveColumnIndex)
            {
                var drv = this.bs.Current as DataRowView;
                var dr = drv.Row as dsPurchase.PurchaseRow;
                dr.pumamt = dr.pumqty * dr.pumprice;
                dr.EndEdit();
            }
            else if (fpSpread1_Sheet1.Columns["pumprice"].Index == fpSpread1_Sheet1.ActiveColumnIndex)
            {
                var drv = this.bs.Current as DataRowView;
                var dr = drv.Row as dsPurchase.PurchaseRow;
                dr.pumamt = dr.pumqty * dr.pumprice;
                dr.EndEdit();
            }
        }
    }
}
