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 FPJ0000
{
    public partial class fProjectPartToPurchase : Form
    {
        BindingSource bsModel;
        int ProjectIndex = -1;
        public fProjectPartToPurchase(int pidx)
        {
            InitializeComponent();
            this.ProjectIndex = pidx;
            this.KeyPreview = true;
            this.StartPosition = FormStartPosition.CenterScreen;
            this.KeyDown += (s1, e1) =>
            {
                if (e1.KeyCode == Keys.Escape) this.Close();
            };
        }
        void MakeList(dsPRJ.ProjectsPartDataTable dt)
        {
            this.listView1.SuspendLayout();
            this.listView1.Items.Clear();
            var orderdata = dt
                .OrderBy(t => string.Concat(t.ItemGroup, t.option1, t.ItemSid, t.ItemName));

            foreach (dsPRJ.ProjectsPartRow dr in orderdata)
            {
                var lvitem = this.listView1.Items.Add(dr.ItemGroup);
                lvitem.Tag = dr;
                lvitem.Checked = true;
                lvitem.SubItems.Add(dr.option1);
                lvitem.SubItems.Add(dr.ItemSid);
                lvitem.SubItems.Add(dr.ItemName);
                lvitem.SubItems.Add(dr.ItemModel);
                lvitem.SubItems.Add(dr.qty.ToString("N0"));
                lvitem.SubItems.Add(dr.price.ToString("N0"));
                lvitem.SubItems.Add(dr.amt.ToString("N0"));

                if(dr.qtybuy == dr.qty)
                {
                    //동일하면 보기 편하게 표시하지 않는다.
                    lvitem.SubItems.Add("--");
                    lvitem.SubItems.Add("--");
                }
                else
                {
                    lvitem.SubItems.Add(dr.qtybuy.ToString("N0"));
                    var amt = dr.qtybuy * dr.price;
                    lvitem.SubItems.Add(amt.ToString("N0"));
                }
                
            }

            this.listView1.ResumeLayout();
            showSummary();
        }
        private void __Load(object sender, EventArgs e)
        {
            //프로젝트정보를 찾는다.
            var dtPrj = taProject.GetbyIDX(this.ProjectIndex);
            var drPrj = dtPrj.Rows[0] as dsPRJ.ProjectsRow;
            this.tbProjectIndex.Text = drPrj.idx.ToString();
            this.textBox1.Text = drPrj.remark_ans;
            this.tbProject.Text = drPrj.name;
            this.tbCr.Text = drPrj.orderno;
            this.tbOrderNo.Text = drPrj.orderno;

            //파트리스트 합계금액
            var dtPart = taPart.GetData(this.ProjectIndex);
            MakeList(dtPart);


            //상태
            var stateList = FCOMMON.DBM.getCodeTable("04");
            this.cmbState.DisplayMember = "Value";
            this.cmbState.ValueMember = "Value";
            this.cmbState.DataSource = stateList;

            //장비제조            
            var dt_dept = FCOMMON.DBM.getCodeTable("06");
            BindingSource bsManu = new BindingSource(dt_dept, "");
            this.cbEQManu.DisplayMember = "Value";
            this.cbEQManu.ValueMember = "Value";
            this.cbEQManu.DataSource = bsManu;

            //장비모델            
            var dt_asset = FCOMMON.DBM.getCodeTable("07");
            bsModel = new BindingSource(dt_asset, "");
            bsModel.Filter = "svalue='그런거없다'";
            this.cbEQModel.DisplayMember = "Value";
            this.cbEQModel.ValueMember = "Value";
            this.cbEQModel.DataSource = bsModel;

            //제조공정
            var dt_manuproc = FCOMMON.DBM.getCodeTable("08");
            this.cbManuProc.DisplayMember = "Value";
            this.cbManuProc.ValueMember = "Value";
            this.cbManuProc.DataSource = dt_manuproc;

            //장비기술공정
            var dt_eetproc = FCOMMON.DBM.getCodeTable("09");
            this.cbProcess.DisplayMember = "Value";
            this.cbProcess.ValueMember = "Value";
            this.cbProcess.DataSource = dt_eetproc;

            ////processlist
            //var procList = FCOMMON.DBM.getGroupTable("process", "Purchase", "process <> ''");
            //this.cbProcess.DisplayMember = "Value";
            //this.cbProcess.ValueMember = "Key";
            //this.cbProcess.DataSource = new BindingSource(procList, "");

            //담당자목록
            //담당자목록 - 사용자목록으로 처리한다.    
            string namestr = string.Format("{0}({1})", FCOMMON.info.Login.nameK, FCOMMON.info.Login.no);
            if (FCOMMON.info.Login.no == "dev") namestr = "김치균(395552)";
            this.cmbRequest.Items.Clear();
            this.cmbRequest.Items.Add(namestr);
            try
            {
                var cn = FCOMMON.DBM.getCn();
                cn.Open();
                string sql = "select [id],[name] " +
                            " from users" +
                            " where gcode='{1}' and id <> '{0}'" +
                            " order by [name]";
                sql = string.Format(sql, FCOMMON.info.Login.no, FCOMMON.info.Login.gcode);
                var cmd = new System.Data.SqlClient.SqlCommand(sql, cn);
                var rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    string cmbdata = string.Format("{1}({0})", rdr[0].ToString(), rdr[1].ToString());
                    this.cmbRequest.Items.Add(cmbdata);
                }
                cmd.Dispose();
                cn.Close();
                cn.Dispose();
            }
            catch (Exception ex)
            {
                FCOMMON.Util.MsgE("User List Error\n\n" + ex.Message);
            }
            cmbRequest.Text = namestr;// FCOMMON.info.Login.nameK;


            dtPdate.Value = DateTime.Now;

            cmbState.Text = "PR";   //po에서 변경 200423 - JBS요청


            this.Show();
            Application.DoEvents();
        }

        void showSummary()
        {
            //모든 선택된 자료의 합계를 표시한다
            var items = listView1.CheckedItems;
            int sumAmt = 0;
            foreach (ListViewItem item in items)
            {
                var str_amt = item.SubItems[7].Text.Replace(",", "").Trim();
                sumAmt += int.Parse(str_amt);
            }
            this.tbSum.Text = sumAmt.ToString("N0");

        }
        private bool saveData()
        {
            this.Validate();

            //체크된 항목확인
            if (this.listView1.CheckedItems == null ||
                this.listView1.CheckedItems.Count < 1)
            {
                FCOMMON.Util.MsgE("선택된 항목이 없습니다");
                return false;
            }


            if (cbProcess.Text.Trim() == "")
            {
                FCOMMON.Util.MsgE("프로세스를 선택하세요.");
                cbProcess.Focus();
                return false;
            }

            if (tbProject.Text == "")
            {
                FCOMMON.Util.MsgE("프로젝트 정보를 입력하세요.");
                tbProject.Focus();
                return false;
            }

            var overtime = DateTime.Now - DateTime.Parse("2019-01-09 00:00:00");
            if (overtime.TotalSeconds > 0)
            {
                if (this.cbProcess.SelectedIndex == -1)
                {
                    if (FCOMMON.info.Login.level >= 5)
                    {
                        var dlg = FCOMMON.Util.MsgQ("[공정]을 입력하지 않고 진행 하시겠습니까?\n\n" +
                       "선택 대상이 없는 경우 문의 바랍니다.\n\n" +
                       "BongSeok Jung(T.7191)\n" +
                       "BongSeok.Jung@amkor.co.kr");
                        if (dlg != System.Windows.Forms.DialogResult.Yes)
                        {
                            cbProcess.Focus();
                            return false;
                        }
                    }
                    else
                    {
                        FCOMMON.Util.MsgE("[공정]을 선택하세요\n\n" +
                        "선택 대상이 없는 경우 문의 바랍니다.\n\n" +
                        "BongSeok Jung(T.7191)\n" +
                        "BongSeok.Jung@amkor.co.kr");

                        cbProcess.Focus();
                        return false;
                    }
                }
                if (cbManuProc.SelectedIndex == -1)
                {
                    if (FCOMMON.info.Login.level >= 5)
                    {
                        var dlg = FCOMMON.Util.MsgQ("제조공정을 입력하지 않고 진행 하시겠습니까?\n\n" +
                       "선택 대상이 없는 경우 문의 바랍니다.\n\n" +
                       "BongSeok Jung(T.7191)\n" +
                       "BongSeok.Jung@amkor.co.kr");
                        if (dlg != System.Windows.Forms.DialogResult.Yes)
                        {
                            cbManuProc.Focus();
                            return false;
                        }
                    }
                    else
                    {
                        FCOMMON.Util.MsgE("제조공정을 선택하세요\n\n" +
                        "선택 대상이 없는 경우 문의 바랍니다.\n\n" +
                        "BongSeok Jung(T.7191)\n" +
                        "BongSeok.Jung@amkor.co.kr");

                        cbManuProc.Focus();
                        return false;
                    }
                }
                if (this.cbEQManu.SelectedIndex == -1)
                {
                    if (FCOMMON.info.Login.level >= 5)
                    {
                        var dlg = FCOMMON.Util.MsgQ("장비제조사를 입력하지 않고 진행 하시겠습니까?\n\n" +
                        "선택 대상이 없는 경우 문의 바랍니다.\n\n" +
                        "BongSeok Jung(T.7191)\n" +
                        "BongSeok.Jung@amkor.co.kr");
                        if (dlg != System.Windows.Forms.DialogResult.Yes)
                        {
                            cbEQManu.Focus();
                            return false;
                        }
                    }
                    else
                    {
                        FCOMMON.Util.MsgE("장비 제조사를 선택하세요.\n\n" +
                        "선택 대상이 없는 경우 문의 바랍니다.\n\n" +
                        "BongSeok Jung(T.7191)\n" +
                        "BongSeok.Jung@amkor.co.kr");
                        cbEQManu.Focus();
                        return false;
                    }
                }
            }

            int itemCount = 0;
            int itemAmt = 0;

            foreach (ListViewItem item in this.listView1.CheckedItems)
            {
                itemCount += 1;
                itemAmt += int.Parse(item.SubItems[7].Text.Replace(",", "").Trim());
            }

            //part 목록을 조회해서 NR에 등록해줘야 함
            var dlg2 = FCOMMON.Util.MsgQ("해당 파트리스트를 NR구매 목록에 등록 하시겠습니까?\n" +
                itemCount.ToString() + "건 " + itemAmt.ToString("N0") + "원");
            if (dlg2 != System.Windows.Forms.DialogResult.Yes) return false;


            string userNo = this.cmbRequest.Text.Substring(cmbRequest.Text.LastIndexOf('(') + 1);
            userNo = userNo.Substring(0, userNo.Length - 1);

            //기존에 등록된 자료가 있는지 체크한다.
            var SQLExist =
                " select count(*) from Purchase" +
                " where import = 1" +
                " and gcode = '" + FCOMMON.info.Login.gcode + "' and pdate = '{0}'" +
                " and projectidx = {1}";
            SQLExist = string.Format(SQLExist, dtPdate.Value.ToShortDateString(), this.ProjectIndex.ToString());
            var ExistCnt = FCOMMON.DBM.ExecuteScalarI(SQLExist);
            if (ExistCnt > 0)
            {
                var dlgq = FCOMMON.Util.MsgQ(string.Format("생성된 자료가 {0}건 존재 합니다.\n\n" + "기존 자료를 삭제 하시겠습니까?", ExistCnt));
                if (dlgq == System.Windows.Forms.DialogResult.Yes)
                {
                    SQLExist =
                  " delete from Purchase" +
                  " where import = 1" +
                  " and gcode = '" + FCOMMON.info.Login.gcode + "' and pdate = '{0}'" +
                  " and projectidx = {1}";
                    SQLExist = string.Format(SQLExist, dtPdate.Value.ToShortDateString(), this.ProjectIndex.ToString());
                    var delCnt = FCOMMON.DBM.ExecuteNonQuery(SQLExist);
                    Console.WriteLine(delCnt.ToString() + "건의 기존 입력된 자료가 삭제됨");
                }
            }

            var fProg = new FCOMMON.fProgress();
            fProg.Title = "NR구매파트 자료 등록 중";
            fProg.SetProgress(0, itemCount);
            fProg.Show();
            fProg.Refresh();

            int iCnt = 0;

            //데이터를 넣는다
            foreach (ListViewItem item in this.listView1.CheckedItems)
            {
                var dr = item.Tag as dsPRJ.ProjectsPartRow;

                //insert query
                var SQL =
                    " insert into purchase(asset,dept,manuproc,gcode,pdate,state,process,request,sid,pumname,pumidx,pumscale,pumunit," +
                    " pumqty,pumprice,pumamt,supply,supplyidx,project,projectidx,bigo,import,wuid,wdate,orderno)" +
                    " values( '{asset}','{dept}','{manuproc}','{gcode}', '{pdate}','{State}','{process}' ,'{userNo}','{ItemSid}'," +
                    " '{ItemName}','{Item}','{ItemModel}','{ItemUnit}','{qty}','{price}','{amt}','{ItemSupply}','{ItemSupplyidx}','{projectname}','{Project}'," +
                    " '{memo}',1 ,'{wuid}', getdate(),'{orderno}')" ;

                SQL = SQL.Replace("{asset}", this.cbEQModel.Text);
                SQL = SQL.Replace("{dept}", this.cbEQManu.Text);
                SQL = SQL.Replace("{manuproc}", this.cbManuProc.Text);
                SQL = SQL.Replace("{gcode}", FCOMMON.info.Login.gcode);

                SQL = SQL.Replace("{orderno}", tbOrderNo.Text.Trim());
                SQL = SQL.Replace("{wuid}", FCOMMON.info.Login.no);
                SQL = SQL.Replace("{projectname}", tbProject.Text.Trim());
                SQL = SQL.Replace("{userNo}", userNo.Trim());
                SQL = SQL.Replace("{process}", cbProcess.Text.Trim());
                SQL = SQL.Replace("{State}", cmbState.Text.Trim());
                SQL = SQL.Replace("{pdate}", dtPdate.Value.ToShortDateString());
                SQL = SQL.Replace("{ItemSid}", dr.ItemSid.Replace(" ","").Trim());
                SQL = SQL.Replace("{ItemName}", dr.ItemName.Trim());
                SQL = SQL.Replace("{Item}", dr.Item.ToString());
                SQL = SQL.Replace("{ItemModel}", dr.ItemModel);
                SQL = SQL.Replace("{ItemUnit}", dr.ItemUnit);                
                SQL = SQL.Replace("{price}", dr.price.ToString());


                if(radioButton1.Checked)
                {
                    SQL = SQL.Replace("{qty}", dr.qty.ToString());   //일반수량이 아닌 필요수량으로
                    SQL = SQL.Replace("{amt}", dr.amt.ToString());
                }
                else
                {
                    //실제 구매에 필요한 수량으로 처리
                    SQL = SQL.Replace("{qty}", dr.qtybuy.ToString());   //일반수량이 아닌 필요수량으로
                    SQL = SQL.Replace("{amt}", (dr.qtybuy * dr.price).ToString());
                }
                
                SQL = SQL.Replace("{ItemSupply}", dr.ItemSupply);
                SQL = SQL.Replace("{ItemSupplyidx}", dr.ItemSupplyidx.ToString());
                SQL = SQL.Replace("{Project}", dr.Project.ToString());
                SQL = SQL.Replace("{memo}", dr.memo);

                // Console.WriteLine(SQL);
                fProg.IncProgress();

                var cnt = FCOMMON.DBM.ExecuteNonQuery(SQL);
            }

            FCOMMON.Util.MsgI(string.Format("{0}건의 자료가 생성 되었습니다.\n\n구매등록 화면에서 내용을 확인하세요.", itemCount));
            fProg.Close();
            fProg.Dispose();

            return true;
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void cbEQManu_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (bsModel == null) return;
            string 원본모델 = cbEQModel.Text;

            //장비모델 필터를 변경해준다.
            if (cbEQManu.SelectedIndex < 0)
            {
                cbEQModel.SelectedIndex = -1;
                return;
            }

            string filter = "svalue='" + cbEQManu.Text.Replace("'", "''") + "'";
            bsModel.Filter = filter;
            if (원본모델 != "") cbEQModel.Text = 원본모델;
            else cbEQModel.SelectedIndex = -1;
        }

        private void toolStripDropDownButton1_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem lv in this.listView1.Items)
                lv.Checked = true;
            showSummary();
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem lv in this.listView1.Items)
                lv.Checked = false;
            showSummary();
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem lv in this.listView1.Items)
                lv.Checked = !lv.Checked;
            showSummary();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem lv in this.listView1.CheckedItems)
            {
                var SID = lv.SubItems[2].Text;
                if (SID.Trim() == "") lv.Checked = false;
            }

            showSummary();
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            if (!saveData()) return;
            DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            //동일 중분류
            if (listView1.FocusedItem == null) return;
            var grp = listView1.FocusedItem.SubItems[0].Text.Trim();
            if (grp == "")
            {
                FCOMMON.Util.MsgE("입력된 중분류값이 없습니다");
                return;
            }
            //체크안된데이터중에서 동일한 그룹을 모두 체크한다
            foreach (ListViewItem item in this.listView1.Items)
            {
                if (item.Checked == false)
                {
                    var itemgrp = item.SubItems[0].Text.Trim();
                    if (itemgrp == grp) item.Checked = true;
                }
            }
            showSummary();
        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            //동일 소분류
            if (listView1.FocusedItem == null) return;
            var grp = listView1.FocusedItem.SubItems[1].Text.Trim();
            if (grp == "")
            {
                FCOMMON.Util.MsgE("입력된 소분류값이 없습니다");
                return;
            }
            //체크안된데이터중에서 동일한 그룹을 모두 체크한다
            foreach (ListViewItem item in this.listView1.Items)
            {
                if (item.Checked == false)
                {
                    var itemgrp = item.SubItems[1].Text.Trim();
                    if (itemgrp == grp) item.Checked = true;
                }
            }
            showSummary();
        }

        private void toolStripButton7_Click(object sender, EventArgs e)
        {
            //기존에 등록된 자료가 있는지 체크한다.
            var SQLExist =
                " select count(*) from Purchase" +
                " where import = 1" +
                " and gcode = '" + FCOMMON.info.Login.gcode + "' and pdate = '{0}'" +
                " and projectidx = {1}";
            SQLExist = string.Format(SQLExist, dtPdate.Value.ToShortDateString(), this.ProjectIndex.ToString());
            var ExistCnt = FCOMMON.DBM.ExecuteScalarI(SQLExist);
            if (ExistCnt > 0)
            {
                var dlgq = FCOMMON.Util.MsgQ(string.Format("생성된 자료가 {0}건 존재 합니다.\n\n" + "기존 자료를 삭제 하시겠습니까?", ExistCnt));
                if (dlgq == System.Windows.Forms.DialogResult.Yes)
                {
                    SQLExist =
                  " delete from Purchase" +
                  " where import = 1" +
                  " and gcode = '" + FCOMMON.info.Login.gcode + "' and pdate = '{0}'" +
                  " and projectidx = {1}";
                    SQLExist = string.Format(SQLExist, dtPdate.Value.ToShortDateString(), this.ProjectIndex.ToString());
                    var delCnt = FCOMMON.DBM.ExecuteNonQuery(SQLExist);
                    FCOMMON.Util.MsgI(delCnt.ToString() + "건의 기존 입력된 자료가 삭제됨");
                }
            }
            else
            {
                FCOMMON.Util.MsgE("등록된 자료가 없습니다\n" +
              "일자 : " + dtPdate.Value.ToShortDateString() + "\n" +
              "프로젝트 : " + this.ProjectIndex.ToString());
            }
        }
    }
}
