using FCOMMON;
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;

namespace FCM0000
{
    public partial class fLovItem : fBase
    {
        string fn_fpcolsize = "";

        public string itemName { get; set; }
        public int item { get; set; }
        public string itemmodel { get; set; }
        public decimal itemprice { get; set; }
        public decimal itempriceD { get; set; }
        public string SID { get; set; }
        public string itemUnit { get; set; }

        public string Storage { get; set; }
        public string itemSupply { get; set; }
        public int itemSupplyidx { get; set; }

        public string itemManu { get; set; }

        public fLovItem(string search_)
        {
            InitializeComponent();
            btAdd.Enabled = false;
            Properties.Settings.Default["gwcs"] = FCOMMON.info.CS;

            fn_fpcolsize = System.IO.Path.Combine(FCOMMON.Util.CurrentPath, "formSetting", "fp_" + this.Name + ".ini");

            //initial value
            itemName = string.Empty;
            item = -1;
            itemmodel = string.Empty;
            itemprice = 0;
            itempriceD = 0;
            SID = string.Empty;
            itemUnit = "EA";
            Storage = string.Empty;
            itemSupply = string.Empty;
            itemSupplyidx = -1;
            itemManu = string.Empty;

            this.KeyPreview = true;
            this.KeyDown += (s1, e1) =>
            {
                if (e1.KeyCode == Keys.Escape) this.Close();
            };
            this.tbFind.KeyDown += (s1, e1) => { if (e1.KeyCode == Keys.Enter) Find(); };
            this.fpSpread1.KeyDown += (s1, e1) => { btOK.PerformClick(); };
            this.fpSpread1.CellDoubleClick += (s1, e1) => { btOK.PerformClick(); };
            this.tbFind.Text = search_;
            this.StartPosition = FormStartPosition.CenterScreen;
        }
    
        private void fLovItem_Load(object sender, EventArgs e)
        {
            EnsureVisibleAndUsableSize();
            Application.DoEvents();

            
            refreshData(this.tbFind.Text);

            if (this.bs.Count > 0) fpSpread1.Focus();
            else
            {
                tbFind.Focus();
                tbFind.SelectAll();
            }
        }

        Boolean searchOk = false;
        void refreshData(string search)
        {
            if (search == "")
            {

                //sFCOMMON.Util.MsgI("(품명,모델,SID)을 검색 한 후 없는 경우 '품목추가' 버튼을 이용해서 추가 하시기 바랍니다");
                tbFind.Focus();
            }
            else
            {
                //search data
                this.ta.FillSearchNoDisable(this.dsMSSQL.Items, "%" + search + "%", FCOMMON.info.Login.gcode);
                FPUtil.ColSizeLoad(ref this.fpSpread1, fn_fpcolsize);

                //검색을 수행
                //this.taPMP.Fill(this.dSPMP.SPMaster, "%" + search + "%");
                //this.arDatagridView1.AutoResizeColumns();
                searchOk = true;
                btAdd.Enabled = true;
            }
        }


        private void itemsBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            var drv = bs.Current as DataRowView;
            if (drv == null)
            {
                itemName = string.Empty;
                item = -1;
                itemmodel = string.Empty;
                itemprice = 0;
                itempriceD = 0;
                itemSupply = string.Empty;
                itemSupplyidx = -1;
                itemManu = string.Empty;
                Storage = string.Empty;
                itemUnit = "EA";
                SID = string.Empty;
                return;
            }
            else
            {
                var dr = drv.Row as dsMSSQL.ItemsRow;
                item = dr.idx;
                if (dr.IsnameNull()) itemName = string.Empty;
                else itemName = dr.name;
                if (dr.IsmodelNull()) itemmodel = string.Empty;
                else itemmodel = dr.model;
                if (dr.IsmanuNull()) itemManu = string.Empty;
                else itemManu = dr.manu;
                if (dr.IspriceNull()) itemprice = 0;
                else itemprice = dr.price;
                if (dr.IspriceDNull()) itempriceD = 0;
                else itempriceD = dr.priceD;

                if (dr.IsStorageNull()) Storage = string.Empty;
                else Storage = dr.Storage;

                if (dr.IssupplyNull()) itemSupply = string.Empty;
                else itemSupply = dr.supply;
                if (dr.IssupplyidxNull()) itemSupplyidx = -1;
                else itemSupplyidx = dr.supplyidx;
                if (dr.IsunitNull()) itemUnit = "EA";
                else itemUnit = dr.unit;
                SID = dr.sid;
            }

            if (itemName.isEmpty() || item == -1) DialogResult = System.Windows.Forms.DialogResult.Cancel;
            else DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        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
            {
                try
                {
                    var dr = drv.Row as dsMSSQL.ItemsRow;
                    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 (img != null) img.Dispose();
        }

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

                btOK.PerformClick();
            }

        }

        private void dv_DoubleClick(object sender, EventArgs e)
        {
            btOK.PerformClick();
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs 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);
            }
        }

        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 btFind_Click(object sender, EventArgs e)
        {
            Find();
        }
        void Find()
        {
            var search = tbFind.Text.Trim();
            if (search.isEmpty())
            {
                FCOMMON.Util.MsgE("검색어를 입력하세요");
                return;
            }
            else refreshData(search);
            
            tbFind.SelectAll();
            tbFind.Focus();
            btAdd.Enabled = true;
        }

        private void btAdd_Click(object sender, EventArgs e)
        {
            if (searchOk == false)
            {
                FCOMMON.Util.MsgE("먼저 검색을 통해서 아이템을 찾은 후 없다면 신규추가를 눌러 주세요");
                tbFind.Focus();
                tbFind.SelectAll();
                return;
            }
            var sid = string.Empty;
            if (tbFind.Text.Length == 9 && tbFind.Text.StartsWith("10")) sid = tbFind.Text.Trim();
            
            var f = new Item.fItemAdd(sid);
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                itemName = f.tbName.Text.Trim();
                item = f.newIDX;
                itemmodel = f.tbModel.Text.Trim();
                itemManu = f.tbManu.Text.Trim();
                //decimal price;
                //decimal.TryParse(f.tbPrice.Text.Replace(",", ""), out price);
                //itemprice = price;// decimal.Parse(f.tbPrice.Text.Trim().Replace(",",""));
                if (f.tbPrice.Text.Replace(",", "").isEmpty() == false)
                {
                    if (decimal.TryParse(f.tbPrice.Text.Replace(",", "").Trim(), out decimal price))
                        itemprice = price;
                }
                else itemprice = 0;

                if (f.tbPriceD.Text.Replace(",", "").isEmpty()==false)
                {
                    if (decimal.TryParse(f.tbPriceD.Text.Replace(",", "").Trim(), out decimal priced))
                        itempriceD = priced;
                }
                else itempriceD = 0;

                SID = f.tbSid.Text.Trim();
                if (SID.StartsWith("신규")) SID = "신규";
                itemUnit = f.tbUnit.Text.Trim();
                itemSupply = f.tbSupply.Text.Trim();
                itemSupplyidx = int.Parse(f.tbSupplyIdx.Text);
                Storage = f.tbStorage.Text.Trim();
                DialogResult = System.Windows.Forms.DialogResult.OK;
            }
        }
    }
}
