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

namespace FCM0000
{
    public partial class fItems : FCOMMON.fBase
    {
        string fn_fpcolsize = "";
        public fItems()
        {
            InitializeComponent();
            Properties.Settings.Default["gwcs"] = FCOMMON.info.CS;

            fn_fpcolsize = System.IO.Path.Combine(FCOMMON.Util.CurrentPath, "formSetting", "fp_" + this.Name + ".ini");
            this.FormClosed += fItems_FormClosed;
            this.dsMSSQL.Items.TableNewRow += Items_TableNewRow;
        }

        void fItems_FormClosed(object sender, FormClosedEventArgs e)
        {
        }
        
        private void fItems_Load(object sender, EventArgs e)
        {
            EnsureVisibleAndUsableSize();
            var cateList = FCOMMON.DBM.getGroupTable("cate", "Items", "isnull(cate,'') <> ''");
            this.cmbCate.Items.Clear();
            this.cmbCate.Items.Add("-- All --");
            foreach (var item in cateList)
                cmbCate.Items.Add(item.Key);
            this.cmbCate.SelectedIndex = 0;
            this.cmbMode.SelectedIndex = 0;
            //this.Show();
            //Application.DoEvents();

            //공급처 목록을 업데이트 함
            var taCustom = new dsMSSQLTableAdapters.CustomsTableAdapter();
            var customData = taCustom.GetData(FCOMMON.info.Login.gcode);
            //var colSupply = this.fpSpread1_Sheet1.Columns["supply"];
            //var cy = colSupply.CellType as FarPoint.Win.Spread.CellType.ComboBoxCellType;
            //List<string> items = new List<string>();
            //List<string> itemData = new List<string>();
            //foreach (var item in customData)
            //{
            //    items.Add(item.name);
            //    itemData.Add(item.idx.ToString());
            //}
            //cy.Items = items.ToArray();
            //cy.ItemData = itemData.ToArray();
            //cy.EditorValueChanged += cy_EditorValueChanged;


            this.cmbSort.SelectedIndex = 0;
            tbSearch.Focus();
        }

        void cy_EditorValueChanged(object sender, EventArgs e)
        {
            //공급처를 변경했으므로 그 상호도 선택하게 해준다.
            var supplyidx = this.fpSpread1_Sheet1.ActiveCell.Value;
            var supplyname = this.fpSpread1_Sheet1.ActiveCell.Text;
            var supname = this.fpSpread1_Sheet1.Columns["supplyname"];
            fpSpread1_Sheet1.SetValue(this.fpSpread1_Sheet1.ActiveRowIndex, supname.Index, supplyname);
        }

        void refreshData()
        {
            //refresh data
            string cateSearch = "%";
            if (cmbCate.SelectedIndex > 0) cateSearch = cmbCate.Text;
            if (cmbMode.SelectedIndex == 0)
            {
                var skey = tbSearch.Text.Trim();
                if (skey == "") skey = "%";
                else
                {
                    if (skey.StartsWith("%") == false) skey = "%" + skey;
                    if (skey.EndsWith("%") == false) skey += "%";
                }

                this.ta.FillNoImage(this.dsMSSQL.Items, FCOMMON.info.Login.gcode, cateSearch, skey);
            }
            else
                this.ta.FillDupCheck(this.dsMSSQL.Items, FCOMMON.info.Login.gcode, cateSearch);

            FPUtil.ColSizeLoad(ref this.fpSpread1, fn_fpcolsize);

            tbFind.Text = string.Empty;
            tbFind.BackColor = Color.White;
        }

        void Items_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["wuid"] = FCOMMON.info.Login.no;
            e.Row["wdate"] = DateTime.Now;
            e.Row["gcode"] = FCOMMON.info.Login.gcode;
            if (this.cmbCate.SelectedIndex > 0) e.Row["cate"] = this.cmbCate.Text.Trim();
        }
        private void itemsBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.bs.EndEdit();


            var dlg = FCOMMON.Util.MsgQ("변경된 사항을 저장 하시겠습니까?");
            if (dlg != System.Windows.Forms.DialogResult.Yes) return;

            try
            {
                var cnt = this.tam.UpdateAll(this.dsMSSQL);
                FCOMMON.Util.MsgI(cnt.ToString() + "건의 자료가 저장 되었습니다");
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE(ex.Message);
            }


        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            if (tbSearch.Text.Trim() == "")
            {
                util.MsgE("검색어를 입력하세요\n\n자료가 많은 관계로 검색어를 입력하세요.\n\n전체 검색을 하려면 %를 입력하세요");
                tbSearch.Focus();
                return;
            }

            refreshData();
        }

        private void dv1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            //var col = this.dv1.Columns[e.ColumnIndex];
            //var value = this.dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;

            //switch (col.DataPropertyName.ToLower())
            //{
            //    case "supply":  //공급처는 검색하게 한다.
            //        if (value == null) return;
            //        var search = value.ToString();
            //        if (search.isEmpty()) return;

            //        FCM0000.fLovSupply f = new fLovSupply(search);
            //        if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            //        {
            //            var name = f.Title;
            //            var idx = f.Index;
            //            dv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = name;
            //            dv1.Rows[e.RowIndex].Cells[e.ColumnIndex + 1].Value = idx;
            //        }
            //        break;
            //}
        }

        private void toolStripButton1_Click_1(object sender, EventArgs e)
        {
            Find();
        }

        void Find()
        {
            var search = tbFind.Text.Trim();
            if (search.isEmpty())
            {
                bs.Filter = "";
                tbFind.BackColor = Color.White;
            }
            else
            {
                string filter = "isnull(storage,'') like '%{0}%' or isnull(cate,'') like '%{0}%' or isnull(name,'') like '%{0}%' or isnull(sid,'') like '%{0}%' or isnull(model,'') like '%{0}%' or isnull(supply,'') like '%{0}%'";
                filter = string.Format(filter, search);
                try
                {
                    bs.Filter = filter;
                    tbFind.BackColor = Color.Lime;
                }
                catch
                {
                    tbFind.BackColor = Color.Pink;
                }
            }
            tbFind.SelectAll();
            tbFind.Focus();

        }

        private void btFind_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) Find();

        }

        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 bs_CurrentChanged(object sender, EventArgs e)
        {
            var drv = this.bs.Current as DataRowView;
            var img = this.pictureBox1.Image;
            if (drv == null)
            {
                this.pictureBox1.Image = null;
            }
            else
            {
                var dr = drv.Row as dsMSSQL.ItemsRow;

                //이미지 확인
                try
                {
                    var img1 = FCOMMON.DBM.GetImageData("Items", "image", dr.idx);
                    if (img1 != null) this.pictureBox1.Image = img1;
                    else this.pictureBox1.Image = null;
                }
                catch
                {
                    this.pictureBox1.Image = null;
                }

                //공급처 담당자 정보
                if (dr.supply != "") label4.Text = "[" + dr.supply + "] 담당자";
                else label4.Text = "공급처 담당자";
                lvSupplyDamdang.Items.Clear();
                if (dr.supplyidx != -1)
                {
                    taStaff.FillByCID(this.dsMSSQL.Staff, FCOMMON.info.Login.gcode, dr.supplyidx);
                    foreach (dsMSSQL.StaffRow item in this.dsMSSQL.Staff)
                    {
                        var name = item.name;
                        if (item.grade != "") name += "(" + item.grade + ")";
                        var lv = lvSupplyDamdang.Items.Add(name);
                        lv.SubItems.Add(item.tel);
                        lv.SubItems.Add(item.email);
                    }
                }

                //최근 입고 데이터 확인 (일자,담당,수량,금액,상태)
                var inData = taPurchase.GetInDate(dr.idx);
                lvInDate.Items.Clear();
                if (inData != null && inData.Rows.Count > 0)
                {
                    foreach (dsMSSQL.PurchaseRow drP in inData.Rows)
                    {
                        string date = drP.indate;
                        if (date.Length > 9) date = date.Substring(2);
                        var lv = this.lvInDate.Items.Add(date);
                        lv.SubItems.Add(drP.request);
                        lv.SubItems.Add(drP.pumqty.ToString("N0"));
                        lv.SubItems.Add(drP.pumprice.ToString("N0"));
                        lv.SubItems.Add(drP.state);
                    }
                }

                var odData = taPurchase.GetOrderDate(dr.idx);
                lvOrder.Items.Clear();
                if (odData != null && odData.Rows.Count > 0)
                {
                    foreach (dsMSSQL.PurchaseRow drP in odData.Rows)
                    {
                        string date = drP.pdate;
                        if (date.Length > 9) date = date.Substring(2);
                        var lv = this.lvOrder.Items.Add(date);
                        lv.SubItems.Add(drP.request);
                        lv.SubItems.Add(drP.pumqty.ToString("N0"));
                        lv.SubItems.Add(drP.pumprice.ToString("N0"));
                        lv.SubItems.Add(drP.state);
                    }
                }
            }
            if (img != null) img.Dispose();
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void 파일섡택ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void 이미지붙여넣기ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void 촬영ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
        {

        }

        private void cmbSort_Click(object sender, EventArgs e)
        {

        }

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

        private void cmbSort_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbSort.Text == "--") this.bs.Sort = "";
            else this.bs.Sort = cmbSort.Text;
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsMSSQL.ItemsRow;
            if (dr.RowState == DataRowState.Deleted || dr.RowState == DataRowState.Detached ||
                dr.RowState == DataRowState.Added)
            {
                FCOMMON.Util.MsgE("이미지는 등록 완료된 아이템만 가능합니다. 먼저 저장한 후 다시 시도하세요.");
                return;
            }
            OpenFileDialog od = new OpenFileDialog();
            if (od.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;
            var image = Image.FromFile(od.FileName);
            if (!FCOMMON.DBM.setImageData(image, "Items", "image", dr.idx))
            {
                FCOMMON.Util.MsgE("등록 실패");
            }
            else this.pictureBox1.Image = Image.FromFile(od.FileName);  //181208
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            if (!Clipboard.ContainsImage())
            {
                FCOMMON.Util.MsgE("이미지를 먼저 클립보드에 복사 하세요.");
                return;
            }

            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsMSSQL.ItemsRow;
            if (dr.RowState == DataRowState.Deleted || dr.RowState == DataRowState.Detached ||
                dr.RowState == DataRowState.Added)
            {
                FCOMMON.Util.MsgE("이미지는 등록 완료된 아이템만 가능합니다. 먼저 저장한 후 다시 시도하세요.");
                return;
            }

            var image = Clipboard.GetImage();
            if (!FCOMMON.DBM.setImageData(image, "Items", "image", dr.idx))
            {
                FCOMMON.Util.MsgE("등록 실패");
            }
            else this.pictureBox1.Image = image;  //181208
        }

        private void toolStripButton9_Click(object sender, EventArgs e)
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as dsMSSQL.ItemsRow;
            if (dr.RowState == DataRowState.Deleted || dr.RowState == DataRowState.Detached ||
                dr.RowState == DataRowState.Added)
            {
                FCOMMON.Util.MsgE("이미지는 등록 완료된 아이템만 가능합니다. 먼저 저장한 후 다시 시도하세요.");
                return;
            }

            //FCOMMON.fWebCamera f = new FCOMMON.fWebCamera(FCOMMON.info.camIndex);
            //if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            //{
            //    System.Drawing.Bitmap bmp = f.bmp.Clone() as System.Drawing.Bitmap;
            //    Application.DoEvents();

            //    if (!FCOMMON.DBM.setImageData(bmp, "Items", "image", dr.idx))
            //    {
            //        FCOMMON.Util.MsgE("등록 실패");
            //    }
            //    else
            //    {
            //        var oimag = this.pictureBox1.Image;
            //        this.pictureBox1.Image = (Image)bmp;
            //        if (oimag != null) oimag.Dispose();
            //    }
            //}
        }

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

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            var msg = "이 기능은 엑셀 파일에서 품목정보를 읽어들여 업데이트 하는 기능 입니다\n" +
                "엑셀파일의 열 구성은 다음과 같이 합니다\n" +
                "SID,품명,모델,단가,공급처,제조\n" +
                "1번줄에는 제목 줄이며,  실제 자료는 2번 줄 부터 시작합니다\n" +
                "SID는 9자리이며, (SID/품명이) 없는 자료는 입력되지 않습니다\n1번시트에 데이가 있어야 합니다\n계속 할까요?";
            if (util.MsgQ(msg) != DialogResult.Yes) return;
            var od = new OpenFileDialog();
            od.Filter = "excel|*.xlsx|allfiles|*.*";
            if (od.ShowDialog() != DialogResult.OK) return;


        

            libxl.Book book;// = new libxl.BinBook();
            book = new libxl.XmlBook();
            book.setKey(FCOMMON.info.libxlCompany, FCOMMON.info.libxlKey);
            var ta = new dsMSSQLTableAdapters.ItemsTableAdapter();
            var dt = new dsMSSQL.ItemsDataTable();
            try
            {
                book.load(od.FileName);
                if (book.sheetCount() < 1)
                {
                    util.MsgE("1번 시트가 없습니다. 파일을 확인하세요");
                    return;
                }
                var sheet = book.getSheet(0);
                var maxrow = sheet.lastRow();
                var icnt = 0;
                var ucnt = 0;

                if (util.MsgQ($"입력을 시작할까요? 전체({maxrow})건\n시간이 오래 걸릴 수 있으므로 기다려 주세요") != DialogResult.Yes) return;


                var f = new Form();
                f.Text = "data input";
                f.Size = new Size(400, 100);
                f.ControlBox = false;
                f.Padding = new Padding(10, 10, 10, 10);
                var p = new ProgressBar();
                p.Dock = DockStyle.Fill;
                p.Maximum = maxrow;
                p.Value = 0;
                f.StartPosition = FormStartPosition.CenterScreen;
                f.Controls.Add(p);
                f.Show();
                Application.DoEvents();

                for (int i = 1; i < maxrow; i++)
                {
                    var sid = sheet.readStr(i, 0); if (sid.isEmpty()) continue;
                    var name = sheet.readStr(i, 1); if (name.isEmpty()) continue;
                    var model = sheet.readStr(i, 2); if (model.isEmpty()) model = name;
                    if (name.Equals(model)) model = ".";

                    f.Text = $"입력중 기다려주세요({i}/{maxrow})";
                    p.Value = i;

                    decimal price = 0;
                    if (sheet.cellType(i, 3) == libxl.CellType.CELLTYPE_STRING)
                    {
                        var vprice = sheet.readStr(i, 3).Replace(",", "");
                        decimal.TryParse(vprice, out price);
                    }
                    else
                    {
                        price = (decimal)(sheet.readNum(i, 3));
                    }

                    var supp = sheet.readStr(i, 4);
                    var manu = sheet.readStr(i, 5);
                    var dr = ta.GetBySID(FCOMMON.info.Login.gcode, sid).FirstOrDefault();
                    if (dr == null)
                    {
                        dr = dt.NewItemsRow();
                        dr.gcode = FCOMMON.info.Login.gcode;
                        dr.disable = false;
                        dr.import = "1";
                        dr.sid = sid;
                        dr.name = name;
                        dr.model = model;
                        dr.supply = supp;
                        dr.manu = manu;
                        dr.price = price;
                        dr.wdate = DateTime.Now;
                        dr.wuid = FCOMMON.info.Login.no;
                        dt.AddItemsRow(dr);
                        icnt += ta.Update(dr);
                        //icnt += 1;
                    }
                    else
                    {
                        if (dr.name.Equals(name) == false) dr.name = name;
                        if (dr.model.isEmpty() || model.Length > dr.model.Length) dr.model = model;
                        if (price > 0) dr.price = price;
                        if (supp.isEmpty() == false) dr.supply = supp;
                        if (manu.isEmpty() == false) dr.manu = manu;
                        dr.EndEdit();
                        ucnt += ta.Update(dr);
                        //ucnt += 1;
                    }

                    if(i % 2 ==0) Application.DoEvents();

                }

                f.Dispose();
                util.MsgI($"입력수:{icnt}\n변경수:{ucnt}");
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE(ex.Message);
                return;
            }
            ta.Dispose();

        }
    }
}
