using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DBUtility;
using grproLib;
using PaintingPC.Model;

namespace PaintingPC
{
    public partial class FrmChainDown : Form
    {
        public FrmChainDown()
        {
            InitializeComponent();
        }

        private void tableLayoutPanel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void label2_Click(object sender, EventArgs e)
        {
            Environment.Exit(0);
        }

        private void FrmChainDown_Load(object sender, EventArgs e)
        {
            var serverUrl = "http://10.60.101.59:8013/";
            var updateXmlFileName = "PaintDown.xml";
            var updater = new AutoUpdater();
            if (updater.CheckUpdateLoad(serverUrl, updateXmlFileName))
            {
                Environment.Exit(0);
            }
            Control.CheckForIllegalCrossThreadCalls = false;
            //this.WindowState = FormWindowState.Maximized;

            txtBarCode.Text = "";
            lbPartName.Text = "";
            lbupCount.BackColor = Color.FromArgb(27,66,39);
            lbdownCount.BackColor = Color.FromArgb(27, 66, 39);
            lbdownCount.ForeColor = Color.FromArgb(255, 234, 45);
            InitCount();
            //initBarCode(Color.Gray);
            initPack("","");
        }

        private void InitCount()
        {
            try
            {
                lbupCount.Text = Function.GetChainCountAll();
                lbdownCount.Text = Function.GetChainCountDown();
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLogBase(ex.ToString(),MethodBase.GetCurrentMethod().Name);
            }
        }

        /// <summary>
        /// 在悬挂链的条码信息
        /// </summary>
        private void initBarCode(Color c)
        {
            try
            {
                panel7.Controls.Clear();

                DataTable dt = Function1.GetOnChainBarCode();
                if (dt != null && dt.Rows.Count > 0)
                {
                    Label[] label = new Label[dt.Rows.Count];
                    string[] type = new string[dt.Rows.Count];
                    string[] color = new string[dt.Rows.Count];
                    string[] barcode=new string[dt.Rows.Count];

                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        //type[i] = dt.Rows[i]["carType"].ToString();
                        type[i] = dt.Rows[i]["productName"].ToString();
                        color[i] = dt.Rows[i]["color"].ToString();
                        barcode[i] = dt.Rows[i]["barcode"].ToString();

                        label[i] = new Label();
                        label[i].Font = new Font("微软雅黑", 9, FontStyle.Bold);
                        label[i].ForeColor = System.Drawing.Color.White;
                        label[i].Size = new Size(200, panel7.Height-2);
                        label[i].Location = new Point(panel7.Size.Width- ((i+1) * label[i].Size.Width)-2, 0);
                        Point p = new Point(label[i].Location.X, label[i].Location.Y);
                        
                        label[i].BorderStyle = BorderStyle.FixedSingle;
                        //label[i].BackColor = Color.Gray;
                        label[i].BackColor = c;
                        label[i].TextAlign = ContentAlignment.MiddleCenter;
                        label[i].Text = type[i] + "\n\r" + color[i] + "\n\r" + barcode[i];
                        panel7.Controls.Add(label[i]);
                    }
                }

            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLogBase(ex.ToString(), MethodBase.GetCurrentMethod().Name);
            }
        }

        private void initPack(string typename,string color1)
        {
            try
            {
                int drow = 0, dcol = 5;

                panel8.Controls.Clear();

                DataTable dt = Function1.GetDownInfo();
                if (dt != null && dt.Rows.Count > 0)
                {
                    UC[] uc=new UC[6];
                    int[] sum = new int[dt.Rows.Count];
                    string[] type = new string[dt.Rows.Count];
                    string[] color = new string[dt.Rows.Count];
                    int[] packCount=new int[dt.Rows.Count];

                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        drow = Convert.ToInt32(Math.Ceiling((double)dt.Rows.Count / dcol));
                        sum[i] = Convert.ToInt32(dt.Rows[i]["sum"].ToString());
                        //type[i] = dt.Rows[i]["carType"].ToString();
                        type[i] = dt.Rows[i]["productName"].ToString();
                        color[i] = dt.Rows[i]["color"].ToString();

                        DataTable packdt = Function1.PackCount(type[i], color[i]);
                        if (packdt != null && packdt.Rows.Count > 0)
                        {
                            packCount[i] = Convert.ToInt32(packdt.Rows[0]["PackCount"].ToString());
                        }
                        else
                        {
                            packCount[i] = 0;
                        }
                    }

                    for (int i = 0; i < dcol; i++)   //列
                    {
                        for (int j = 0; j < drow; j++) //行
                        {
                            uc[i] = new UC();

                            if ((i + dcol * j) < type.Length)
                            {
                                uc[i].typeInfo = type[i + dcol * j];
                                uc[i].colorInfo = color[i + dcol * j];
                                uc[i].countInfo = sum[i + dcol * j].ToString() + "/" + packCount[i + dcol * j].ToString();
                                uc[i].Size = new Size(119, 76);
                                uc[i].Font = new Font("微软雅黑", 12f);
                                uc[i].ForeColor = Color.White;
                                uc[i].Location = new Point(5 + i * (uc[i].Size.Width + 3), 5 + j * (uc[i].Size.Height + 3));
                                uc[i].BackColor = Color.FromArgb(1, 6, 152);
                                panel8.Controls.Add(uc[i]);
                            }
                        }
                    }

                    if (typename != "")
                    {
                        foreach (var aa in panel8.Controls)
                        {
                            UC bb = (UC)aa;
                            if (bb.typeInfo == typename && bb.colorInfo == color1)
                            {
                                bb.BackColor = Color.Green;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLogBase(ex.ToString(), MethodBase.GetCurrentMethod().Name);
            }
        }

        private void txtBarCode_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    //int a = 0;
                    int a = 1;
                    string cartype = "", color = "",filename="",productName="";
                    string barcode = "", partNo = "", packNo = "", partDes = "", batch = "", qLevel = "", type = "", date = "";
                    
                    int packCount = 0;
                    string boxNo = "";

                    if (txtBarCode.Text.Trim() == "")
                    {
                        MessageBox.Show("条码不能为空!", "提示", MessageBoxButtons.OK);
                        txtBarCode.SelectAll();
                        return;
                    }

                    #region 产品条码

                    //TODO 正常扫条码
                    if (txtBarCode.Text.Trim() != "#####" && txtBarCode.Text.Trim() != "DEL" && txtBarCode.Text.Trim() != "88888")
                    {
                        #region 判断是一维码还是二维码,如果是二维码转换成一维码

                        if (txtBarCode.Text.Trim().Contains('.'))
                        {
                            barcode = Function.TransToBarCodeOne(txtBarCode.Text.Trim());
                        }
                        else
                        {
                            barcode = txtBarCode.Text.Trim();
                        }

                        #endregion

                        #region 判断条码是否已下线、是否在悬挂链上

                        if (Function1.IsDown(barcode))
                        {
                            MessageBox.Show("该条码已下悬挂链!", "提示", MessageBoxButtons.OK);
                            txtBarCode.SelectAll();
                            return;
                        }

                        DataTable dt = Function1.GetOnChainBarCode();
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            string[] barCode = new string[dt.Rows.Count];
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                barCode[i] = dt.Rows[i]["barcode"].ToString();
                            }

                            if (barCode.Contains(barcode) == false)
                            {
                                MessageBox.Show("条码不在悬挂链上!", "提示", MessageBoxButtons.OK);
                                txtBarCode.SelectAll();
                                return;
                            }
                            else
                            {
                                #region 判断条码顺序是否一致

                                //if (barcode != barCode[0])
                                //{
                                //    //todo 不一致将所有条码信息标记红色
                                //    a = 0;
                                //    initBarCode(Color.FromArgb(212,39,37));
                                //}
                                //else
                                //{
                                //    //todo 一致将所有条码信息标记灰色
                                //    a = 1;
                                //    initBarCode(Color.Gray);
                                //}
                               
                                #endregion

                                #region 根据条码信息查询对应信息 

                                DataTable barDt = Function1.GetBarCodeInfo(barcode);
                                if (barDt != null && barDt.Rows.Count > 0)
                                {
                                    cartype = barDt.Rows[0]["carType"].ToString();
                                    productName= barDt.Rows[0]["productName"].ToString();
                                    color = barDt.Rows[0]["color"].ToString();
                                    lbPartName.Text = color + ',' + productName;
                                }

                                #endregion

                                #region 执行存储过程操作 1、将上线表Flag改为1;2、插入到下线表中;3、判断是否需要打箱单;4、将pannel8对应标签选中并标记颜色

                                SqlParameter[] param=new SqlParameter[5];

                                param[0] = new SqlParameter("@barCode", SqlDbType.NVarChar, 50);
                                param[0].Value = barcode;

                                param[1] = new SqlParameter("@carType", SqlDbType.NVarChar, 50);
                                param[1].Value = cartype;

                                param[2] = new SqlParameter("@color", SqlDbType.NVarChar, 50);
                                param[2].Value = color;

                                param[3] = new SqlParameter("@flag", SqlDbType.Int);
                                param[3].Value = a;

                                param[4] = new SqlParameter("@productName", SqlDbType.NVarChar,100);
                                param[4].Value = productName;

                                //param[5] = new SqlParameter("@packNo", SqlDbType.NVarChar, 100);
                                //param[5].Direction = ParameterDirection.Output;

                                //param[6] = new SqlParameter("@packCount", SqlDbType.Int);
                                //param[6].Direction = ParameterDirection.Output;

                                //param[7] = new SqlParameter("@partDes", SqlDbType.NVarChar, 200);
                                //param[7].Direction = ParameterDirection.Output;

                                //param[8] = new SqlParameter("@partNo", SqlDbType.NVarChar, 200);
                                //param[8].Direction = ParameterDirection.Output;

                                //param[9] = new SqlParameter("@batch", SqlDbType.NVarChar, 200);
                                //param[9].Direction = ParameterDirection.Output;

                                //param[10] = new SqlParameter("@qLevel", SqlDbType.NVarChar, 200);
                                //param[10].Direction = ParameterDirection.Output;

                                //param[11] = new SqlParameter("@result", SqlDbType.Int);
                                //param[11].Direction = ParameterDirection.Output;

                                #endregion

                                int res = SqlHelper.ExecuteNonQuery(SqlHelper.SqlConnString, CommandType.StoredProcedure, "ChaimDown", param);

                                //if (Convert.ToInt32(param[11].Value) == 1)
                                //{
                                //    #region 打印箱单

                                //    filename = System.AppDomain.CurrentDomain.BaseDirectory + "装箱单.grf";
                                //    DataTable headTable = new DataTable();
                                //    headTable.Columns.Add("BoxNo");
                                //    headTable.Columns.Add("PartName");
                                //    headTable.Columns.Add("PartNo");
                                //    headTable.Columns.Add("BatchNo");
                                //    headTable.Columns.Add("PackCount");
                                //    headTable.Columns.Add("QLevel");
                                //    DataRow row = headTable.NewRow();

                                //    row["BoxNo"] = param[5].Value;
                                //    row["PartNo"] = param[8].Value;

                                //    row["QLevel"] = param[10].Value;
                                //    row["PartName"] = productName+color;

                                //    row["BatchNo"] = param[9].Value;
                                //    row["PackCount"] = param[6].Value + " EA";
                                //    //row["PartNo"] = param[7].Value;

                                //    //row["QLevel"] = param[9].Value;
                                //    //row["PartName"] = param[6].Value;

                                //    //row["BatchNo"] = param[8].Value;
                                //    //row["PackCount"] = param[5].Value + " EA";

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

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

                                //    rp.Report.Print(false);

                                //    #endregion
                                //}

                                #region 判断当前的条码是不是班次的最后一根

                                DataTable isLast = Function1.IsLast();
                                if (isLast != null && isLast.Rows.Count > 0)
                                {
                                    if (barcode == isLast.Rows[0]["barcode"].ToString())
                                    {
                                        Function1.UpdateIsLast(barcode);
                                    }
                                }

                                #endregion

                                #region 刷新页面

                                InitCount();

                                //if (a == 0)
                                //{
                                //    initBarCode(Color.FromArgb(212, 39, 37));
                                //}
                                //else
                                //{
                                //    initBarCode(Color.Gray);
                                //}

                                //initPack(param[1].Value.ToString() ,param[2].Value.ToString());
                                initPack(productName, param[2].Value.ToString());

                                #endregion

                                txtBarCode.SelectAll();
                            }
                        }
                        else
                        {
                            MessageBox.Show("悬挂链上已无产品!", "提示", MessageBoxButtons.OK);
                            txtBarCode.SelectAll();
                            return;
                        }

                        #endregion
                    }
                    //TODO 未满器具打包
                    else if (txtBarCode.Text.Trim() == "#####")   
                    {
                        FrmPack frm = new FrmPack();

                        frm.OkBtnClick += (arg1) =>
                        {
                            #region 查找产品信息

                            DataTable dt2 = Function1.GetBarCodeInfo(arg1);
                            if (dt2 != null && dt2.Rows.Count > 0)
                            {
                                type = dt2.Rows[0]["carType"].ToString();
                                color = dt2.Rows[0]["color"].ToString();
                                partDes = type + color;
                                DataTable dt3 = Function1.GetProductInfo(type, color);
                                if (dt3 != null && dt3.Rows.Count > 0)
                                {
                                    partNo = dt3.Rows[0]["PartNo"].ToString();
                                    qLevel = dt3.Rows[0]["QLevel"].ToString();
                                }
                                else
                                {
                                    MessageBox.Show("此产品零件号不存在!", "提示", MessageBoxButtons.OK);
                                    //textBox1.Focus();
                                    //textBox1.SelectAll();
                                    return;
                                }
                            }

                            #endregion

                            #region 查找未打印产品

                            DataTable dt4 = Function1.GetNotPack(barcode);
                            if (dt4 != null && dt4.Rows.Count > 0)
                            {
                                packCount = Convert.ToInt32(dt4.Rows[0]["aa"].ToString());
                            }
                            else
                            {
                                packCount = 0;
                            }

                            #endregion

                            #region 生成箱单

                            date = DateTime.Now.ToString("yyyy-MM-dd");
                            batch = date.Substring(2, 2) + date.Substring(5, 2) + date.Substring(8, 2);

                            DataTable dt5 = Function1.GetPackNo(partNo + "." + batch);
                            if (dt5 != null && dt5.Rows.Count > 0)
                            {
                                packNo =
                                    dt5.Rows[0]["boxNum"].ToString().Substring(0, dt5.Rows[0]["boxNum"].ToString().Length - 6) +
                                    (Convert.ToInt32(dt5.Rows[0]["boxNum"].ToString()
                                         .Substring(dt5.Rows[0]["boxNum"].ToString().Length - 7, 6)) + 1).ToString()
                                    .PadLeft(6, '0');
                            }
                            else
                            {
                                packNo = partNo + "." + batch + ".000001";
                            }

                            #endregion

                            #region 打印箱单

                            filename = System.AppDomain.CurrentDomain.BaseDirectory + "装箱单.grf";
                            DataTable headTable = new DataTable();
                            headTable.Columns.Add("BoxNo");
                            headTable.Columns.Add("PartName");
                            headTable.Columns.Add("PartNo");
                            headTable.Columns.Add("BatchNo");
                            headTable.Columns.Add("PackCount");
                            headTable.Columns.Add("QLevel");
                            DataRow row = headTable.NewRow();

                            row["BoxNo"] = packNo;
                            row["PartNo"] = partNo;

                            row["QLevel"] = qLevel;
                            row["PartName"] = partDes;

                            row["BatchNo"] = batch;
                            row["PackCount"] = packCount.ToString() + "EA";

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

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

                            rp.Report.Print(false);

                            #endregion

                            #region 存箱单记录

                            PaintBoxModel md = new PaintBoxModel();

                            md.ID = Guid.NewGuid().ToString();
                            md.boxNum = packNo;
                            md.partNo = partNo;
                            md.PackCount = packCount;
                            md.flag = 0;

                            Function1.InsertPaintInfo(md);

                            #endregion

                            #region

                            Function1.UpdateBoxNo(arg1, packNo);

                            #endregion

                            frm.Close();
                        };
                    }

                    //TODO 删除条码
                    else if (txtBarCode.Text.Trim() == "DEL") 
                    {
                        FrmDelChaimUp frm = new FrmDelChaimUp();

                        frm.OkBtnClick += (arg1) =>
                        {
                            frm.Close();

                            #region 删除条码

                            Function1.delChaimUp(arg1);

                            #endregion
                        };
                        frm.ShowDialog();
                        txtBarCode.SelectAll();
                    }

                    //TODO 补打装箱单,屏蔽
                    else if (txtBarCode.Text.Trim() == "88888")
                    {
                        //FrmRePrint frm = new FrmRePrint();

                        //frm.OkBtnClick += (arg1) =>
                        //{
                        //    frm.Close();

                        //    #region 查找所在箱单

                        //    DataTable dt = Function1.BoxNo(arg1);
                        //    if (dt != null && dt.Rows.Count > 0)
                        //    {
                        //        boxNo = dt.Rows[0]["boxNum"].ToString();
                        //    }

                        //    #endregion

                        //    #region 打印箱单

                        //    filename = System.AppDomain.CurrentDomain.BaseDirectory + "装箱单.grf";
                        //    DataTable headTable = new DataTable();
                        //    headTable.Columns.Add("BoxNo");
                        //    headTable.Columns.Add("PartName");
                        //    headTable.Columns.Add("PartNo");
                        //    headTable.Columns.Add("BatchNo");
                        //    headTable.Columns.Add("PackCount");
                        //    headTable.Columns.Add("QLevel");
                        //    DataRow row = headTable.NewRow();

                        //    row["BoxNo"] = boxNo;

                        //    DataTable dt1 = Function1.boxInfo(boxNo);
                        //    if (dt1 != null && dt1.Rows.Count > 0)
                        //    {
                        //        row["PartNo"] = dt1.Rows[0]["partNo"].ToString();

                        //        DataTable dt2 = Function1.SearchProdunctInfo(dt1.Rows[0]["partNo"].ToString());
                        //        if (dt2 != null && dt2.Rows.Count > 0)
                        //        {
                        //            row["QLevel"] = dt2.Rows[0]["QLevel"].ToString();
                        //            row["PartName"] = dt2.Rows[0]["ProductName"].ToString();
                        //        }

                        //        string[] aa = boxNo.Split('.');
                        //        row["BatchNo"] = aa[1].ToString();
                        //        row["PackCount"] = dt1.Rows[0]["PackCount"].ToString() + "EA";
                        //    }

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

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

                        //    rp.Report.Print(false);

                        //    #endregion

                        //    #region 存箱单记录

                        //    PaintBoxModel md = new PaintBoxModel();

                        //    md.ID = Guid.NewGuid().ToString();
                        //    md.boxNum = boxNo;
                        //    md.partNo = dt1.Rows[0]["partNo"].ToString();
                        //    md.PackCount = Convert.ToInt32(dt1.Rows[0]["PackCount"].ToString());
                        //    md.flag = 1;

                        //    Function1.InsertPaintInfo(md);

                        //    #endregion

                        //    frm.Close();

                        //};
                        //frm.ShowDialog();
                        //txtBarCode.SelectAll();
                    }

                    #endregion

                    InitCount();
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLogBase(ex.ToString(), MethodBase.GetCurrentMethod().Name);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            InitCount();
        }
    }
}