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.Threading.Tasks;
using System.Windows.Forms;

namespace FEQ0000.Purchase
{
    public partial class fPurchaseNR_Ipgo : fBase
    {
        int idx = -1;
        string po = string.Empty;
        public fPurchaseNR_Ipgo(int purchaseIdx, string po_)
        {
            InitializeComponent();
            this.po = po_;
            this.idx = purchaseIdx;
            this.KeyPreview = true;
            this.KeyDown += (s1, e1) =>
            {
                if (e1.KeyCode == Keys.Escape) this.Close();
            };
        }

        string prestatus = "PO";
        private void fPurchaseCR_Ipgo_Load(object sender, EventArgs e)
        {
            EnsureVisibleAndUsableSize();
            var ta = new dsPurchaseTableAdapters.PurchaseTableAdapter();
            var dt = ta.GetByIdx(this.idx);
            if (dt == null || dt.Any() == false)
            {
                FCOMMON.Util.MsgE("정보를 확인할 수 없습니다");
                this.btOK.Enabled = false;
                return;
            }
            var dr = dt.First();
            prestatus = dr.state;

            tbPumname.Text = dr.pumname;
            textBox16.Text = dr.pumidx.ToString();
            tbModel.Text = dr.pumscale;
            tbUnit.Text = dr.pumunit;
            tbQty.Text = dr.pumqty.ToString();
            tbPriceO.Text = dr.pumprice.ToString();
            tbInPrice.Text = dr.pumprice.ToString();
            tbAmt.Text = (dr.pumqty * dr.pumprice).ToString();
            tbRemarkO.Text = dr.bigo;
            tbPO.Text = dr.po;
            if (string.IsNullOrEmpty(tbPO.Text)) tbPO.Text = this.po;
            tbSC.Text = dr.sc;
            tbSCRCF.Text = dr.orderno;
            tbSID.Text = dr.sid;

            //프로젝트정보 찾는다
            var tap = new DSPrjTableAdapters.ProjectsTableAdapter();
            var dtp = tap.GetData(dr.projectidx);
            DSPrj.ProjectsRow drp;
            if (dtp == null || dtp.Any() == false)
            {
                drp = dtp.NewProjectsRow();
            }
            else
            {
                //프로젝트정보표시
                drp = dtp.First();
            }
            tbPrjName.Text = drp.name;
            tbPrjAsset.Text = drp.asset;
            tbPrjStatus.Text = drp.status;
            tbPrjMemo.Text = drp.memo;
            tbProjOrderNo.Text = drp.orderno;
            tbPrjModel.Text = drp.model;
            tbPrjSerial.Text = drp.serial;
            tbPrjProcess.Text = drp.process;
            tbPrjIdx.Text = drp.idx.ToString();


            var userList = FCOMMON.DBM.getUserList(); //.getGroupList("name", "Users", "[level] > 0 and [level] < 10");
            foreach (var user in userList)
            {
                this.cmbReceive.Items.Add(string.Format("[{0}] {1}", user.Key, user.Value));
                // this.cmbRequest.Items.Add(string.Format("[{0}] {1}", user.Key, user.Value));
            }


            //기존에 설정된 정보가 있다면 그것을 쓴다
            if (dr.receive.isEmpty() == false)
            {
                cmbReceive.Text = $"[{dr.receive}] {dr.receiveName}";
                if (DateTime.TryParse(dr.indate, out DateTime dtin))
                {
                    dtInDate.Value = dtin;
                }
                else dtInDate.Value = DateTime.Now;
                chkInDate.Checked = true;
                if (dr.IsinqtyNull()) tbInQty.Text = string.Empty;
                else tbInQty.Text = dr.inqty.ToString();
                tbInRemark.Text = dr.inremark;
            }
            else
            {
                //설정정보가 없다면 비활성화해준다
                cmbReceive.Text = $"[{dr.request}] {dr.requestName}";//FCOMMON.DBM.GetcurrentUserNoName();
                dtInDate.Value = DateTime.Now;
                chkInDate.Checked = false;
                tbInQty.Text = dr.pumqty.ToString();
                chkInDate_CheckedChanged(null, null);
            }


        }

        private void btOK_Click(object sender, EventArgs e)
        {
            if (chkInDate.Checked && cmbReceive.SelectedIndex < 0)
            {
                FCOMMON.Util.MsgE("수령인을 선택하세요");
                cmbReceive.Focus();
                return;
            }
            var ta = new dsPurchaseTableAdapters.PurchaseTableAdapter();
            var dr = ta.GetByIdx(this.idx).First();
            if (chkInDate.Checked == false)
            {
                if (dr.IsindateNull() == false)
                {
                    if (dr.indate.isEmpty() == false)
                    {
                        if (FCOMMON.Util.MsgQ("입고정보를 삭제할까요? 상태는 [PR]로 전환됩니다.") != DialogResult.Yes) return;
                    }
                }

                dr.indate = string.Empty;
                dr.receive = string.Empty;
                //  dr.receiveName = string.Empty;
                dr.inqty = 0;
                dr.inremark = string.Empty;
                if (prestatus == "Received") dr.state = "PO";
                else dr.state = prestatus;
            }
            else
            {
                dr.indate = dtInDate.Value.ToString("yyyy-MM-dd");
                dr.receive = cmbReceive.Text.Substring(1, cmbReceive.Text.IndexOf("]") - 1);
                // dr.receiveName = cmbReceive.Text.Substring(cmbReceive.Text.IndexOf("]") + 1).Trim();                
                if (int.TryParse(tbInQty.Text, out int qty) == false)
                {
                    FCOMMON.Util.MsgE("수량을 확인하세요");
                    tbInQty.Text = tbQty.Text.Trim();
                    tbInQty.Focus();
                    tbInQty.SelectAll();
                    return;
                }
                else
                {
                    if(qty < 1)
                    {
                        FCOMMON.Util.MsgE("수량이 0 입니다");
                        return;
                    }
                    if (qty > int.Parse(tbQty.Text))
                    {
                        if (FCOMMON.Util.MsgQ("입고수량이 주문수량보다 많습니다 입력 할까요?") != DialogResult.Yes)
                            return;
                    }
                    dr.inqty = qty;
                }
                dr.state = "Received";
                dr.inremark = tbInRemark.Text.Trim();
            }
            dr.windate = DateTime.Now;
            dr.winuid = FCOMMON.info.Login.no;
            dr.po = this.tbPO.Text.Trim();
            dr.EndEdit();
            var cnt = ta.Update(dr);
            DialogResult = DialogResult.OK;
        }

        private void chkInDate_CheckedChanged(object sender, EventArgs e)
        {
            dtInDate.Enabled = chkInDate.Checked;
            cmbReceive.Enabled = chkInDate.Checked;
            tbInQty.Enabled = chkInDate.Checked;
            tbInRemark.Enabled = chkInDate.Checked;
            //if (chkInDate.Checked == false)
            //    cmbReceive.SelectedIndex = -1;
            //else cmbReceive.Text = FCOMMON.DBM.GetcurrentUserNoName();

        }
    }
}
