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

namespace FPJ0000
{
    public partial class fPartList : FCOMMON.fBase
    {
        string fn_fpcolsize = "";
        int ProjectIndex = -1;


        int colidx_itemname = -1;
        int colidx_item = -1;
        int colidx_qty = -1;
        int colidx_amt = -1;
        int colidx_price = -1;
        int colidx_model = -1;
        int colidx_supply = -1;
        int colidx_supplyidx = -1;
        int colidx_sid = -1;


        public fPartList(int idx_)
        {
            InitializeComponent();

            fn_fpcolsize = System.IO.Path.Combine(
                AppDomain.CurrentDomain.BaseDirectory,
                "formSetting",
                "fp_" + this.Name + ".ini");

            this.ProjectIndex = idx_;
            this.FormClosed += fPartList_FormClosed;
            this.KeyDown += fPartList_KeyDown;
            this.dsPRJ.ProjectsPart.TableNewRow += ProjectsPart_TableNewRow;
        }

        void ProjectsPart_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["wuid"] = FCOMMON.info.Login.no;
            e.Row["wdate"] = DateTime.Now;
            e.Row["Project"] = this.ProjectIndex;
        }

        void fPartList_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape) this.Close();
            else if (e.KeyCode == Keys.F5) searchpmp();
        }

        void fPartList_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.FormClosed -= fPartList_FormClosed;
            this.KeyDown -= fPartList_KeyDown;
            this.dsPRJ.ProjectsPart.TableNewRow -= ProjectsPart_TableNewRow;


            //정렬방식 저장값 저장하기
            var SetFile = util.CurrentPath + "FormSetting.xml";
            arUtil.XMLHelper xml = new arUtil.XMLHelper(SetFile);
            if (xml.Exist() == false) xml.CreateFile();

            if (radSortGrp.Checked)
                xml.set_Data("partlist", "sort", "0");
            else
                xml.set_Data("partlist", "sort", "1");
            xml.Save();
        }



        private void fPartList_Load(object sender, EventArgs e)
        {
            //정렬방식 저장값 불러오기
            var SetFile = util.CurrentPath + "FormSetting.xml";
            arUtil.XMLHelper xml = new arUtil.XMLHelper(SetFile);
            if (xml.Exist() == false) xml.CreateFile();
            if (xml.get_Data("partlist", "sort", "0") == "0") radSortGrp.Checked = true;
            else radSortNo.Checked = true;

            //열번호찾기
            foreach (FarPoint.Win.Spread.Column col in this.fpSpread1.ActiveSheet.Columns)
            {
                string colname = col.DataField.ToLower();
                if (colname == "itemmodel") colidx_model = col.Index;
                else if (colname == "itemname") colidx_itemname = col.Index;
                else if (colname == "item") colidx_item = col.Index;
                else if (colname == "qty") colidx_qty = col.Index;
                else if (colname == "price") colidx_price = col.Index;
                else if (colname == "amt") colidx_amt = col.Index;
                else if (colname == "itemsupplyidx") colidx_supplyidx = col.Index;
                else if (colname == "itemsupply") colidx_supply = col.Index;
                else if (colname == "itemsid") colidx_sid = col.Index;
            }
            this.Show();
            Application.DoEvents();
            RefreshData();



        }
        void RefreshData()
        {
            if (dsPRJ.HasChanges())
            {
                var dlg = FCOMMON.Util.MsgQ("변경 사항이 있습니다. 갱신하면 변경 내용이 손실 됩니다.\n지금 갱신 하겠습니까?");
                if (dlg != System.Windows.Forms.DialogResult.Yes) return;
            }

            try
            {
                //프로젝트 정보 채우기
                this.ta.FillByIDX(this.dsPRJ.Projects, this.ProjectIndex);


                //order by 절은 다시 생성한다.
                var SSQl = " SELECT  * FROM ProjectsPart " +
                           " WHERE Project  = @prj";
                if (radSortGrp.Checked) SSQl += " order by itemgroup,option1,no,itemname";
                else SSQl += " order by no";

                this.dsPRJ.ProjectsPart.Clear();
                var cmd = new System.Data.SqlClient.SqlCommand(SSQl, taPart.Connection);
                cmd.Parameters.Add("prj", SqlDbType.Int).Value = this.ProjectIndex;
                var da = new System.Data.SqlClient.SqlDataAdapter(cmd);
                da.Fill(this.dsPRJ.ProjectsPart);
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE(ex.Message);
            }

            //로딩후에 sid 와 suuply 를 조회해준다.
            //foreach (dsPRJ.ProjectsPartRow dr in this.dsPRJ.ProjectsPart.Rows)
            //{
            //    if (dr.IsItemNull() || dr.Item < 0) continue;
            //    var iteminfo = FCOMMON.DBM.getItemInfo(dr.Item);
            //    if (iteminfo.idx != -1)
            //    {
            //        dr.SID = iteminfo.sid;
            //        //dr.Supply = iteminfo.supply;
            //    }
            //}
            //this.dsPRJ.AcceptChanges();
            RefreshSum();
            FPUtil.ColSizeLoad(ref this.fpSpread1, fn_fpcolsize);
            FormattingData();
        }
        void FormattingData()
        {
            //삭제컬럼인덱스
            this.fpSpread1.SuspendLayout();
            var delindex = this.fpSpread1.ActiveSheet.Columns["sid"].Index;
            var col_pmp = this.fpSpread1.ActiveSheet.Columns["pmp"].Index;
            var col_buy = this.fpSpread1.ActiveSheet.Columns["buy"].Index;
            for (int i = 0; i < this.fpSpread1.ActiveSheet.Rows.Count; i++)
            {
                var value = this.fpSpread1.ActiveSheet.GetValue(i, delindex);
                var str_crcf = string.Empty;
                if (value != null) str_crcf = value.ToString();

                if (string.IsNullOrEmpty(str_crcf))
                {
                    //sid값이 없다
                    this.fpSpread1.ActiveSheet.Rows[i].BackColor = Color.FromArgb(240, 240, 240);
                }
                else
                {
                    this.fpSpread1.ActiveSheet.Rows[i].BackColor = Color.White;
                }
                this.fpSpread1.ActiveSheet.Cells[i, delindex].BackColor = Color.FromArgb(240,240, 250);
                this.fpSpread1.ActiveSheet.Cells[i, col_pmp].BackColor = Color.FromArgb(240, 240, 240);
                this.fpSpread1.ActiveSheet.Cells[i, col_buy].BackColor = Color.FromArgb(200,200,255);
            }


            this.fpSpread1.ResumeLayout();
        }

        void RefreshSum()
        {
            decimal sum = 0;
            foreach (dsPRJ.ProjectsPartRow dr in this.dsPRJ.ProjectsPart.Rows)
            {
                if (dr.RowState == DataRowState.Deleted || dr.RowState == DataRowState.Detached) continue;
                sum += dr.amt;
            }
            lbSum.Text = sum.ToString("N0");
        }


        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.bs.EndEdit();
            this.bsPart.EndEdit();
            try
            {
                var cnt = this.tam.UpdateAll(this.dsPRJ);
                FCOMMON.Util.MsgI(cnt.ToString() + "건의 자료가 업데이트 되었습니다.");
                this.dsPRJ.AcceptChanges();
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE(ex.Message);
            }

        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            var f = new rPartList(this.ProjectIndex);
            f.Show();
        }


        private void exportListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sd = new SaveFileDialog();
            sd.Filter = "excel|*.xls";
            var fn = nameTextBox.Text.Trim();
            if (textBox1.Text.Trim() != "") fn += "_" + textBox1.Text.Trim();
            sd.FileName = fn + ".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);
            }

            //dv1.ExportData("partlist.csv");
        }


        private void autoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            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)
        {
            FPUtil.ColsizeSave(this.fpSpread1, fn_fpcolsize);
        }

        private void loadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FPUtil.ColSizeLoad(ref this.fpSpread1, fn_fpcolsize);
        }

        private void fpSpread1_EditModeOff(object sender, EventArgs e)
        {
            int Colidx = this.fpSpread1.ActiveSheet.ActiveColumnIndex;
            int Rowidx = this.fpSpread1.ActiveSheet.ActiveRowIndex;

            var taItem = new FCM0000.dsMSSQLTableAdapters.ItemsTableAdapter();

            switch (this.fpSpread1.ActiveSheet.Columns[Colidx].DataField.ToLower())
            {
                case "supplyname":
                    var valuen1 = fpSpread1.ActiveSheet.Cells[Rowidx, Colidx].Value;//.Rows[Rowidx].Cells[e.ColumnIndex].Value;
                    if (valuen1 != null)
                    {
                        string inputtext1 = valuen1.ToString().Trim();
                        if (inputtext1 != "")
                        {
                            FCM0000.fLovSupply f = new FCM0000.fLovSupply(inputtext1);
                            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                            {
                                fpSpread1.ActiveSheet.Cells[Rowidx, colidx_supply].Value = f.Title;
                                fpSpread1.ActiveSheet.Cells[Rowidx, colidx_supplyidx].Value = f.Index;
                            }
                            else
                            {
                                //fpSpread1.ActiveSheet.Cells[Rowidx, colidx_supply].Value = string.Empty;
                                fpSpread1.ActiveSheet.Cells[Rowidx, colidx_supplyidx].Value = -1;
                            }
                        }
                    }
                    break;
                case "itemname":
                    var valuen = fpSpread1.ActiveSheet.Cells[Rowidx, Colidx].Value;//.Rows[Rowidx].Cells[e.ColumnIndex].Value;
                    if (valuen != null)
                    {
                        string inputtext = valuen.ToString().Trim();
                        if (inputtext != "")
                        {
                            //검색을 실행해서 보여준다.
                            var SearchDT = taItem.GetSearch("%" + inputtext + "%", FCOMMON.info.Login.gcode);
                            if (SearchDT == null || SearchDT.Rows.Count < 1)
                            {
                                //FCOMMON.Util.MsgE("검색 결과가 없습니다.");
                                fpSpread1.ActiveSheet.ActiveColumnIndex += 2;
                                return;
                            }
                            else
                            {
                                //검색된 결과를 표시해서 보여준다.
                                var f = new FCM0000.fLovItem("%" + inputtext + "%");
                                if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                                {
                                    //var c = fpSpread1.ActiveSheet.Columns["sdf"];

                                    fpSpread1.ActiveSheet.Cells[Rowidx, colidx_item].Value = f.item;
                                    fpSpread1.ActiveSheet.Cells[Rowidx, colidx_itemname].Value = f.itemName;

                                    fpSpread1.ActiveSheet.Cells[Rowidx, colidx_sid].Value = f.SID;
                                    fpSpread1.ActiveSheet.Cells[Rowidx, colidx_supplyidx].Value = f.itemSupplyidx;
                                    fpSpread1.ActiveSheet.Cells[Rowidx, colidx_supply].Value = f.itemSupply;


                                    if (f.itemmodel != "")
                                        fpSpread1.ActiveSheet.Cells[Rowidx, colidx_model].Value = f.itemmodel;

                                    if (f.itemprice != 0)
                                        fpSpread1.ActiveSheet.Cells[Rowidx, colidx_price].Value = f.itemprice;

                                    var valueq1 = fpSpread1.ActiveSheet.Cells[Rowidx, colidx_qty].Value;
                                    var valuep1 = fpSpread1.ActiveSheet.Cells[Rowidx, colidx_price].Value;

                                    Int32 iQty = 0;
                                    decimal iPrice = 0;
                                    if (valueq1 != null && valueq1.ToString() != "") iQty = (Int32)valueq1;
                                    if (valuep1 != null && valuep1.ToString() != "") iPrice = (decimal)valuep1;
                                    decimal iAmt = iQty * iPrice;
                                    fpSpread1.ActiveSheet.Cells[Rowidx, colidx_amt].Value = iAmt;
                                }
                            }
                        }
                    }
                    break;
                case "price":
                case "qty":
                    var valueq = fpSpread1.ActiveSheet.Cells[Rowidx, colidx_qty].Value;
                    var valuep = fpSpread1.ActiveSheet.Cells[Rowidx, colidx_price].Value;

                    Int32 iQty1 = 0;
                    decimal iPrice1 = 0;
                    if (valueq != null && valueq.ToString() != "") iQty1 = (Int32)valueq;
                    if (valuep != null && valuep.ToString() != "") iPrice1 = (decimal)valuep;

                    var amt = iQty1 * iPrice1;
                    fpSpread1.ActiveSheet.Cells[Rowidx, colidx_amt].Value = amt;
                    //dv1.Rows[e.RowIndex].Cells["dvc_amt"].Value = amt;
                    RefreshSum();
                    break;

            }
        }

        private void btRefresh_Click(object sender, EventArgs e)
        {
            RefreshData();
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            var f = new fProjectPartImport(ProjectIndex);
            f.ShowDialog();
            this.RefreshData();
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            var chg = this.dsPRJ.ProjectsPart.GetChanges();
            if (chg != null)
            {
                FCOMMON.Util.MsgE("변경된 자료가 있습니다. \n 해당 자료를 먼저 저장하세요");
                return;
            }

            var f = new fProjectPartToPurchase(ProjectIndex);
            f.ShowDialog();
        }

        private void tbFind_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                var search = tbFind.Text.Trim();
                var ColumnList = new string[] { "ItemName", "ItemModel", "ItemSupply", "ItemManu", "ItemSid" };
                var Filter = "";
                if (search != "")
                {
                    foreach (var item in ColumnList)
                    {
                        if (Filter != "") Filter += " or ";
                        Filter += item + " like '%{0}%'";
                    }
                }
                try
                {
                    if (Filter != "")
                    {
                        this.bsPart.Filter = string.Format(Filter, search.Replace("'", "''"));
                        tbFind.BackColor = Color.Lime;
                    }
                    else
                    {
                        this.bsPart.Filter = "";
                        tbFind.BackColor = SystemColors.Window;
                    }
                }
                catch
                {
                    this.bsPart.Filter = "";
                    tbFind.BackColor = Color.HotPink;
                }
                this.tbFind.SelectAll();
                this.tbFind.Focus();
            }
        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            var range = this.fpSpread1_Sheet1.GetSelection(0);
            util.MsgE("준비중");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            RefreshData();
        }

        private void toolStripButton5_Click_1(object sender, EventArgs e)
        {
            var dlg = FCOMMON.Util.MsgQ("재고 확인을 실행하시겠습니까?\n재고 확인 완료 후에는 구매수량값이 업데이트 됩니다");
            if (dlg != DialogResult.Yes) return;

            //pmp데이터에서 모두 업데이트 한다
            //컬럼명 qty, qty_pmp, qty_buy

            List<DatabaseManager.sPMPdata> retval = new List<DatabaseManager.sPMPdata>();
            var cn = DatabaseManager.getCn();
            try
            {
                cn.Open();
            }
            catch (Exception ex)
            {
                util.MsgE("데이터베이스 연결 실패\n" + ex.Message);
                return;
            }


            System.Data.SqlClient.SqlDataReader rdr = null;
            System.Data.SqlClient.SqlCommand cmd = null;
            var basesql1 = "select isnull(SIDNo,'') ,isnull(PartName,'') ,isnull(PartNo,'') , isnull(CurrentQty,0)   from SPMaster where SIDNo = '{0}'";
            var basesql2 = "select isnull(SIDNo,'') ,isnull(PartName,'') ,isnull(PartNo,'') , isnull(CurrentQty,0)   from SPMaster where PartNo = '{0}'";
            cmd = new System.Data.SqlClient.SqlCommand("", cn);

            var cnt_ok = 0;
            var cnt_no = 0;
            var cnt_ng = 0;
            var cnt_reduce = 0;
            foreach (dsPRJ.ProjectsPartRow dr in this.dsPRJ.ProjectsPart.Rows)
            {
                if (dr.RowState == DataRowState.Detached || dr.RowState == DataRowState.Deleted) continue;

                var qty = dr.qty; //파트리스트수량
                var model = string.IsNullOrEmpty(dr.ItemModel) ? dr.ItemName : dr.ItemModel;

                //검색 sql 생성
                string sql = "";
                if (string.IsNullOrEmpty(dr.ItemSid) == true) sql = string.Format(basesql2, model);
                else sql = string.Format(basesql1, dr.ItemSid);
                cmd.CommandText = sql;

                rdr = cmd.ExecuteReader();
                List<DatabaseManager.sPMPdata> db = new List<DatabaseManager.sPMPdata>();
                while (rdr.Read())
                {
                    //데이터를 가져온다
                    var v_sidno = rdr[0];
                    var v_name = rdr[1];
                    var v_no = rdr[2];
                    var v_qty = rdr[3];

                    var newdr = new DatabaseManager.sPMPdata();
                    if (v_sidno != DBNull.Value) newdr.sid = v_sidno.ToString();
                    if (v_name != DBNull.Value) newdr.partname = v_name.ToString();
                    if (v_no != DBNull.Value) newdr.partno = v_no.ToString();
                    if (v_qty != DBNull.Value) newdr.qty = int.Parse(v_qty.ToString());
                    db.Add(newdr);
                }
                rdr.Close();

                //데이터가 여러개있다면 해당 데이터를 표시한다
                if (db.Count > 1)
                {
                    cnt_ng += 1;
                    dr.qtyjago = "{" + db.Count.ToString() + "}";
                    dr.qtybuy = qty;
                }
                else if (db.Count == 1 && db[0].qty != 0)
                {
                        cnt_ok += 1;
                        dr.qtyjago = db[0].qty.ToString(); //재고수량
                        dr.qtybuy = Math.Max(qty - db[0].qty, 0);
                        cnt_reduce += (qty - dr.qtybuy);
                    
                }
                else
                {
                    //pmp에 자료 없다
                    cnt_no += 1;
                    dr.qtyjago = "--";
                    dr.qtybuy = qty;
                }
                dr.EndEdit();
            }


            if (cmd != null) cmd.Dispose();
            if (rdr != null) rdr.Close();

            cn.Close();
            cn.Dispose();

            var msg = string.Format("PMP 검색결과 현황\n" +
                "검색완료 : {0}\n" +
                "복수확인 : {1}\n" +
                "확인불가 : {2}\n" +
                "신규 구매 감소 : {3}", cnt_ok, cnt_ng, cnt_no, cnt_reduce);
            FCOMMON.Util.MsgI(msg);
        }

        void searchpmp()
        {
            //PMP조회
            var drv = this.bsPart.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsPRJ.ProjectsPartRow;

            //검색어
            var title = string.IsNullOrEmpty(dr.ItemModel) ? dr.ItemName : dr.ItemModel;
            if (string.IsNullOrEmpty(dr.ItemSid) == false) title = dr.ItemSid;

            var f = new fSPMaster(title);
            if (f.ShowDialog() == DialogResult.OK)
            {
                var pmp = f.qty; //pmp재고
                var req = f.qty;
                var buy = Math.Max(req - pmp, 0);
                dr.qtyjago = pmp.ToString();
                dr.qtybuy = buy;
                dr.EndEdit();
            }
        }
        private void pMP조회ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void toolStripButton7_Click(object sender, EventArgs e)
        {
            searchpmp();

        }
    }
}
