using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using gregn6Lib;
using MESClassLibrary.BLL.Log;
using PunchAndWeld.DataSouce;

namespace PunchAndWeld
{
    public partial class FrmInspection_WheelBrow : Form
    {
        public FrmInspection_WheelBrow()
        {
            InitializeComponent();
        }

        private void textBox2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    if (textBox2.Text.Trim() == "")
                    {
                        MessageBox.Show("请扫描总成码!", "提示", MessageBoxButtons.OK);
                        textBox2.Focus();
                        return;
                    }

                    //string barcode = textBox2.Text.Trim();
                    string barcode = ProScreenFunc.barCode(textBox2.Text.Trim());
                    if (string.IsNullOrWhiteSpace(barcode))
                    {
                        MessageBox.Show("此总成条码不存在!", "提示");
                        textBox2.SelectAll();
                        textBox2.Focus();
                        return;
                    }
                    if (barcode.Contains("."))
                    {
                        barcode = ProScreenFunc.UniteBarCodeToOne(barcode);
                    }

                    if (ProScreenFunc.HaveScan(barcode))
                    {
                        if (ProScreenFunc.IsBad(barcode))
                        {
                            MessageBox.Show("此总成已报废!", "提示");
                            textBox2.SelectAll();
                            textBox2.Focus();
                            return;
                        }

                        if (ProScreenFunc.IsPack(barcode))
                        {
                            MessageBox.Show("此总成已入箱!", "提示");
                            textBox2.SelectAll();
                            textBox2.Focus();
                            return;
                        }

                        #region 判断是否需要打印箱单

                        int maxCount = 0, packCount = 0;
                        string newBox = "", newBatch = "", partName = "", partNo = "",validity="", validityDate="";
                        string boxNo = ProScreenFunc.boxNo(barcode);
                        string batch = DateTime.Now.ToString("yyyy-MM-dd").Substring(2, 2) + DateTime.Now.ToString("yyyy-MM-dd").Substring(5, 2) + DateTime.Now.ToString("yyyy-MM-dd").Substring(8, 2);

                        DataTable dt = ProScreenFunc.ZCInfo(barcode);
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            maxCount = int.Parse(dt.Rows[0]["PackCount"].ToString());
                            partNo = dt.Rows[0]["PartNo"].ToString();
                            partName = dt.Rows[0]["ProductName"].ToString();
                        }

                        if (boxNo != "")
                        {
                            packCount = ProScreenFunc.HavePackCount(boxNo);
                            if (packCount >= maxCount)
                            {
                                #region 生成箱单

                                string[] xx = boxNo.Split('.');

                                if (xx[1] == batch)
                                {
                                    newBox = boxNo.Substring(0, boxNo.Length - 6) + (Convert.ToInt32(boxNo.Substring(boxNo.Length - 6, 6)) + 1).ToString().PadLeft(6, '0');
                                    newBatch = batch;
                                }
                                else
                                {
                                    newBox = partNo + "." + batch + "." + "000001";
                                    //newBatch = boxNo.Substring(12, 6);
                                    newBatch = batch;
                                }

                                #endregion

                                validity = "3个月";
                                validityDate = "从" + DateTime.Now.ToString("yyyy-MM-dd") + "到" +
                                               DateTime.Now.AddMonths(3).ToString("yyyy-MM-dd");

                                ProScreenFunc.AddBoxInfo(newBox, 0, partNo, partName, newBatch, validity, validityDate);

                                #region 打印箱单

                                string filename = AppDomain.CurrentDomain.BaseDirectory + "box.grf";

                                DataTable headTable = new DataTable();
                                headTable.Columns.Add("BoxNo");
                                headTable.Columns.Add("PartNo");
                                headTable.Columns.Add("PartName");
                                headTable.Columns.Add("Batch");

                                DataRow row = headTable.NewRow();
                                row["BoxNo"] = newBox;
                                row["PartNo"] = partNo;
                                row["PartName"] = partName;
                                row["Batch"] = newBatch;

                                string reportName = ConfigurationManager.AppSettings["PrinterName"];
                                headTable.Rows.Add(row);

                                ReportHelper rp = new ReportHelper(filename, headTable, null,
                                    (int)GRPaperOrientation.grpoDefault, 1, reportName);
                                rp.Report.Print(false);

                                #endregion
                            }
                        }
                        else
                        {
                            #region 生成箱单

                            newBox = partNo + "." + batch + "." + "000001";
                            newBatch = batch;

                            #endregion

                            validity = "3个月";
                            validityDate = "从" + DateTime.Now.ToString("yyyy-MM-dd") + "到" +
                                           DateTime.Now.AddMonths(3).ToString("yyyy-MM-dd");

                            ProScreenFunc.AddBoxInfo(newBox, 0, partNo, partName, newBatch, validity, validityDate);

                            #region 打印箱单

                            string filename = AppDomain.CurrentDomain.BaseDirectory + "box.grf";

                            DataTable headTable = new DataTable();
                            headTable.Columns.Add("BoxNo");
                            headTable.Columns.Add("PartNo");
                            headTable.Columns.Add("PartName");
                            headTable.Columns.Add("Batch");

                            DataRow row = headTable.NewRow();
                            row["BoxNo"] = newBox;
                            row["PartNo"] = partNo;
                            row["PartName"] = partName;
                            row["Batch"] = newBatch;

                            string reportName = ConfigurationManager.AppSettings["PrinterName"];
                            headTable.Rows.Add(row);

                            ReportHelper rp = new ReportHelper(filename, headTable, null,
                                (int)GRPaperOrientation.grpoDefault, 1, reportName);
                            rp.Report.Print(false);

                            #endregion
                        }
                        
                        #endregion

                        textBox1.Enabled = true;
                        textBox1.Focus();
                    }
                    else
                    {
                        MessageBox.Show("还未进行装配!", "提示");
                        textBox2.SelectAll();
                        textBox2.Focus();
                        return;
                    }
                }
                catch (Exception ex)
                {
                    LogErrBLL.AddInfo(ex.ToString(),MethodBase.GetCurrentMethod());
                }
            }
        }

        /// <summary>
        /// 报废
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (textBox2.Text.Trim() == "")
                {
                    MessageBox.Show("请扫描总成码!", "提示", MessageBoxButtons.OK);
                    textBox2.Focus();
                    return;
                }

                string barcode = textBox2.Text.Trim();
                if (barcode.Contains("."))
                {
                    barcode = ProScreenFunc.UniteBarCodeToOne(barcode);
                }

                if (ProScreenFunc.HaveScan(barcode))
                {
                    if (ProScreenFunc.IsBad(barcode))
                    {
                        MessageBox.Show("该条码已经做过报废处理!", "提示");
                        textBox2.SelectAll();
                        textBox2.Focus();
                        return;
                    }

                    #region 不良数+1,完成数-1,不能扣当前计划,查询以前扫码记录,扣减相应计划

                    //根据条码查计划,传计划ID
                    string planID = ProScreenFunc.GetPlanIDByBarcode(barcode);
                    ProScreenFunc.AddBadCount(planID.Trim());
                    ProScreenFunc.SubCompleteCount(planID.Trim());
                    ProScreenFunc.SaveRecord2(barcode, "0", planID);

                    #endregion
                }
                else
                {
                    MessageBox.Show("还未进行装配!", "提示");
                    textBox2.SelectAll();
                    textBox2.Focus();
                    return;
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    if (string.IsNullOrEmpty(textBox1.Text.Trim()))
                    {
                        MessageBox.Show("请扫描箱单!", "提示", MessageBoxButtons.OK);
                        textBox1.Focus();
                        return;
                    }

                    DataTable dt1 = ProScreenFunc.IsExsit(textBox1.Text.Trim());
                    if (dt1 != null && dt1.Rows.Count > 0)
                    {

                    }
                    else
                    {
                        MessageBox.Show("此箱单不存在!", "提示", MessageBoxButtons.OK);
                        textBox1.SelectAll();
                        textBox1.Focus();
                        return;
                    }
                    
                    string[] aa = textBox1.Text.Trim().Split('.');
                    int packCount = ProScreenFunc.HavePackCount(textBox1.Text.Trim());

                    string barcode = ProScreenFunc.barCode(textBox2.Text.Trim());
                    DataTable dt = ProScreenFunc.ZCInfo(barcode);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        if (dt.Rows[0]["PartNo"].ToString() != aa[0])
                        {
                            MessageBox.Show("总成和箱单不匹配!", "提示", MessageBoxButtons.OK);
                            textBox1.SelectAll();
                            textBox1.Focus();
                            return;
                        }

                        if (packCount >= int.Parse(dt.Rows[0]["PackCount"].ToString()))
                        {
                            MessageBox.Show("此箱单已装满!", "提示", MessageBoxButtons.OK);
                            textBox1.SelectAll();
                            textBox1.Focus();
                            return;
                        }
                    }

                    #region 装箱操作

                    //ProScreenFunc.AddPackInfo(textBox2.Text.Trim(), textBox1.Text.Trim());
                    ProScreenFunc.AddPackInfo(barcode, textBox1.Text.Trim());

                    textBox2.Text = "";
                    textBox1.Text = "";
                    textBox2.Focus();
                    textBox1.Enabled = false;

                    InitList();

                    #endregion
                }
                catch (Exception ex)
                {
                    LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
                }
            }
        }

        private void InitList()
        {
            try
            {
                listView1.Columns.Clear();
                listView1.Clear();
                listView1.Columns.Add("箱单号", 400, HorizontalAlignment.Center);
                listView1.Columns.Add("总成零件号", 250, HorizontalAlignment.Center);
                listView1.Columns.Add("总成名称", 400, HorizontalAlignment.Center);
                listView1.Columns.Add("已装箱数量", 150, HorizontalAlignment.Center);

                DataTable dt = ProScreenFunc.PackSum(ConfigurationManager.AppSettings["StationNo"]);
                if (dt != null && dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        ListViewItem lvi = new ListViewItem(dt.Rows[i]["BoxNo"].ToString());
                        lvi.SubItems.Add(dt.Rows[i]["PartNo"].ToString());   //后面添加的Item都为SubItems ,即为子项 
                        lvi.SubItems.Add(dt.Rows[i]["ProductName"].ToString());
                        lvi.SubItems.Add(dt.Rows[i]["qty"].ToString());
                        listView1.Items.Add(lvi);
                    }
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(),MethodBase.GetCurrentMethod());
            }
        }

        private void FrmInspection_WheelBrow_Load(object sender, EventArgs e)
        {
            textBox2.Focus();
            textBox1.Enabled = false;
            panel1.Visible = false;
            textBox1.Text = "";
            textBox2.Text = "";
            textBox3.Text = "";
            InitList();
        }

        /// <summary>
        /// 补打箱单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            panel1.Visible = true;
            textBox3.Focus();
        }

        /// <summary>
        /// 补打箱单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(textBox3.Text.Trim()))
                {
                    MessageBox.Show("请扫描箱单!", "提示", MessageBoxButtons.OK);
                    textBox3.Focus();
                    return;
                }

                DataTable dt = ProScreenFunc.IsExsit(textBox3.Text.Trim());
                if (dt!=null && dt.Rows.Count>0)
                {
                    string partNo = "", partName = "", batchNo = "", validity = "", validityDate = "";

                    partNo = dt.Rows[0]["PartNo"].ToString();
                    partName = dt.Rows[0]["PartName"].ToString();
                    batchNo = dt.Rows[0]["BatchNo"].ToString();
                    validity = dt.Rows[0]["Validity"].ToString();
                    validityDate = dt.Rows[0]["ValidityDate"].ToString();

                    ProScreenFunc.AddBoxInfo(textBox3.Text.Trim(), 1, partNo, partName, batchNo, validity, validityDate);

                    #region 打印箱单

                    string filename = AppDomain.CurrentDomain.BaseDirectory + "box.grf";

                    DataTable headTable = new DataTable();
                    headTable.Columns.Add("BoxNo");
                    headTable.Columns.Add("PartNo");
                    headTable.Columns.Add("PartName");
                    headTable.Columns.Add("Batch");

                    DataRow row = headTable.NewRow();
                    row["BoxNo"] = textBox3.Text.Trim();
                    row["PartNo"] = partNo;
                    row["PartName"] = partName;
                    row["Batch"] = batchNo;

                    string reportName = ConfigurationManager.AppSettings["PrinterName"];
                    headTable.Rows.Add(row);

                    ReportHelper rp = new ReportHelper(filename, headTable, null,
                        (int)GRPaperOrientation.grpoDefault, 1, reportName);
                    rp.Report.Print(false);

                    #endregion

                }
                else
                {
                    MessageBox.Show("此箱单不存在!", "提示", MessageBoxButtons.OK);
                    textBox3.SelectAll();
                    textBox3.Focus();
                    return;
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            FrmPackList fr = new FrmPackList();
            fr.Show();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            FrmNotPackList frm = new FrmNotPackList();
            frm.Show();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            panel1.Visible = false;
            textBox3.Text = "";
        }
    }
}