using gregn6Lib;
using PunchAndWeld.DataSouce;
using PunchAndWeld.WebReference;
using System;
using System.Collections.Generic;
using System.ComponentModel;
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;
using System.Windows.Forms;
using DBUtility;
using MESClassLibrary.BLL.Log;
//using MESClassLibrary.BLL.Log;
namespace PunchAndWeld
{
    public partial class FrmHybird : Form
    {
        private string oneBarCode = "";
        private string productID2 = "";
        private string barcode = "";
        private string productID = "";
        string stationNo = "", stationId = "";

        public FrmHybird()
        {
            InitializeComponent();
        }

        private void FrmHybird_Load(object sender, EventArgs e)
        {
            try
            {
                //var serverUrl = "http://10.60.101.10:8013/";
                //var updateXmlFileName = "ProScreenUpdate.xml";
                //var updater = new AutoUpdater();
                //if (updater.CheckUpdateLoad(serverUrl, updateXmlFileName))
                //{
                //    Environment.Exit(0);
                //}

                label5.Text = "当前版本:" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
                stationNo = ConfigurationManager.AppSettings["StationNo"].ToString();
                label1.Text = ProScreenFunc.GetStation(stationNo);
                stationId = ProScreenFunc.GetStationId(stationNo);
                Control.CheckForIllegalCrossThreadCalls = false;
                Thread t = new Thread(new ThreadStart(TimeGo));
                t.Start();

                LoadScreen();
                textBox1.TabIndex = 0;
                textBox1.Select();

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

        private void TimeGo()
        {
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Interval = 10;
            timer.Enabled = true;
            timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Tick);
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            label9.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            Thread.Sleep(500);
        }

        public void LoadScreen()
        {
            string stationNo = ConfigurationManager.AppSettings["StationNo"].ToString();

            DataTable dt = ProScreenFunc.GetProScreen(stationNo);
            if (dt != null && dt.Rows.Count > 0)
            {
                SetPage(dt);
            }
        }

        public void SetPage(DataTable dt)
        {
            textBox2.Text = "";
            textBox2.Visible = false;
            textBox3.Text = "";
            textBox3.Visible = false;
            textBox4.Text = "";
            textBox4.Visible = false;

            if (dt != null && dt.Rows.Count > 0)
            {
                #region 页面赋值
                label1.Text = dt.Rows[0]["Des"].ToString();
                label2.Text = dt.Rows[0]["OrderNo"].ToString();
                label3.Text = dt.Rows[0]["PartNo"].ToString();
                label4.Text = dt.Rows[0]["ProductName"].ToString();
                //label5.Text = dt.Rows[0]["Des"].ToString();
                label6.Text = dt.Rows[0]["OrderCount"].ToString();
                label7.Text = dt.Rows[0]["CompleteCount"].ToString();
                label8.Text = dt.Rows[0]["OrderNo"].ToString().Substring(0, 1) + "班";
                label10.Text = dt.Rows[0]["BadCount"].ToString();

                this.Tag = dt.Rows[0]["ID"].ToString(); //计划ID
                textBox1.Tag = dt.Rows[0]["ProductID1"].ToString();
                textBox1.Text = "";
                #endregion
            }
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                CheckPartAndProduct();
            }
        }

        public void CheckPartAndProduct()
        {
            textBox1.SelectAll();
            barcode = textBox1.Text.Trim();


            if (!ProScreenFunc.CanScan(this.Tag.ToString().Trim()))
            {
                MessageBox.Show("完成数量等于计划数量,不允许扫描!");
                textBox1.SelectAll();
                return;
            }

            if (barcode.Contains("."))
            {
                barcode = ProScreenFunc.UniteBarCodeToOne(barcode);
            }


            if (ProScreenFunc.HaveScan(barcode))
            {
                if (ProScreenFunc.IsBad(barcode))
                {
                    MessageBox.Show("条码为" + barcode + "的蒙皮为不良品,请操作不良转合格!");
                    textBox1.SelectAll();
                    return;
                }

                DialogResult result = MessageBox.Show("条码为" + barcode + "的蒙皮已经装配,是否重新装配?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                if (result == DialogResult.OK)
                {
                    FrmPassWord pass = new FrmPassWord();
                    pass.OkBtnClick += (arg1) =>
                    {
                        if (!string.IsNullOrEmpty(arg1) &&
                            arg1.ToLower() == ConfigurationManager.AppSettings["password"].ToLower())
                        {
                            pass.Close();

                            ScanBarcode(barcode);
                        }
                        else
                        {
                            MessageBox.Show("密码错误,请重新输入!", "提示", MessageBoxButtons.OK);
                        }
                    };
                    pass.ShowDialog();
                }
                else
                {
                    return;
                }
            }
            else
            {
                ScanBarcode(barcode);
            }

        }

        private void ScanBarcode(string barcode)
        {
            productID = this.textBox1.Tag.ToString().Trim();
            string[] codeSpecial = ProScreenFunc.GetSpecialStockNo();
            string code = barcode.Substring(0, 10);
            if (codeSpecial.Contains(code) && !ProScreenFunc.HaveInspect(barcode) && ProScreenFunc.IsFBC(code, this.label3.Text.Trim()))
            {
                if (ProScreenFunc.HaveScan(barcode))
                {
                    productID2 = ProScreenFunc.GetProductID(barcode);
                    if (!ProScreenFunc.CheckPartAndProduct(productID, productID2))
                    {
                        this.InsLog(productID, productID2);
                        MessageBox.Show("当前扫描的零件与总成不匹配,请检查后再扫描");
                        this.textBox1.Text = "";
                    }
                    else
                    {
                        textBox4.Visible = true;
                        textBox4.Focus();
                    }
                }
                else
                {
                    textBox4.Visible = true;
                    textBox4.Focus();
                    productID2 = ProScreenFunc.GetProductID(code, "");
                }
            }
            else
            {
                 productID2 = ProScreenFunc.GetProductID(barcode);
                if (string.IsNullOrWhiteSpace(productID2))
                {
                    string stockNo = barcode.Substring(0, 10);
                    productID2 = ProScreenFunc.GetProductID(stockNo, "");
                }
                if (!ProScreenFunc.CheckPartAndProduct(productID, productID2))
                {
                    this.InsLog(productID, productID2);
                    MessageBox.Show("当前扫描的零件与总成不匹配,请检查后再扫描");
                    this.textBox1.Text = "";
                }
                else
                {
                    ScanAll.ScanResult = false;
                    OtherPart parts = ProScreenFunc.HaveOtherPart(this.label1.Text.Trim(), productID);
                    if (parts != null && (!string.IsNullOrWhiteSpace(parts.productID3) || !string.IsNullOrWhiteSpace(parts.productID4) || !string.IsNullOrWhiteSpace(parts.productID5)))
                    {
                        FrmProScreen3 frm3 = new FrmProScreen3(parts);
                        frm3.ShowDialog();
                    }
                    else
                    {
                        ScanAll.ScanResult = true;
                    }
                    if (ScanAll.ScanResult)
                    {
                        textBox4.Visible = true;
                        textBox4.Focus();
                    }
                }
            }
        }

        public void InsLog(string productID1, string productID2)
        {
            LogHelper.WriteSysLogBase("一码到底【当前扫描的零件与总成不匹配】:productID1:" + productID1 + ",productID2:" + productID2 + ",工位:" + label1.Text + ",计划ID:" + this.Tag.ToString(), MethodBase.GetCurrentMethod().Name);
        }

        private void AfterScanBarcode(string barcode, string productID2, string productID1, string planID,string stationId)
        {
            try
            {
                string stockNo = "";
                string batchNo = "";
                string partNo = "";
                ProScreenFunc.GetCode(barcode, out stockNo, out batchNo, out partNo);

                partNo = label3.Text.Trim();
                batchNo = ProScreenFunc.GetPlanTime(planID).ToString("yyyyMMdd");

                DateTime time = DateTime.Now;
                string tmp = ProScreenFunc.SerialNo(label3.Text.Trim(), time.ToString("yyMMdd"));
                string sn = "";
                if (tmp == "")
                {
                    sn =
                        label3.Text.Trim() + "." + time.ToString("yyMMdd") + ".000001";
                }
                else
                {
                    sn = tmp.Substring(0, tmp.Length - 6) +
                         (int.Parse(tmp.Substring(tmp.Length - 6, 6)) + 1).ToString()
                         .PadLeft(6, '0');
                }

                ProScreenFunc.SavePartAndProduct1(barcode, productID2, productID1, label2.Text, label8.Text, planID, sn,stationId, ConfigurationManager.AppSettings["StationDescription"]);
                ProScreenFunc.SaveZcCode(barcode, label3.Text.Trim());

                ProScreenFunc.AddCompleteCount(this.Tag.ToString().Trim());


                if (ProScreenFunc.CheckPlanCompleted(this.Tag.ToString().Trim()))
                {
                    LoadScreen();
                }
                else
                {
                    label7.Text = ProScreenFunc.GetCompleteCount(this.Tag.ToString().Trim());
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(),MethodBase.GetCurrentMethod());
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (this.Tag.ToString() == "")
            {
                MessageBox.Show("无上一计划!", "提示");
            }
            else
            {
                LoadPlanScreen(this.Tag.ToString(), "上一计划");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (this.Tag.ToString() == "")
            {
                MessageBox.Show("无下一计划!", "提示");
            }
            else
            {
                LoadPlanScreen(this.Tag.ToString(), "下一计划");
            }
        }

        public void LoadPlanScreen(string id, string plan)
        {
            string stationNo = ConfigurationManager.AppSettings["StationNo"].ToString();

            DataTable dt = ProScreenFunc.GetProScreenPlan(id, stationNo, plan);
            if (dt != null && dt.Rows.Count > 0)
            {
                SetPage(dt);
            }
            else
            {
                if (plan == "下一计划")
                    MessageBox.Show("无下一计划");
                else
                    MessageBox.Show("无上一计划");
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            textBox2.Visible = true;
            textBox2.Focus(); 
        }

        private void textBox2_DoubleClick(object sender, EventArgs e)
        {
            textBox2.Text = "";
            textBox2.Visible = false;
        }

        private void textBox2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    string barcode = textBox2.Text.Trim();
                    if (barcode.Contains("."))
                    {
                        barcode = ProScreenFunc.UniteBarCodeToOne(barcode);
                    }

                    if (ProScreenFunc.HaveScan(barcode))
                    {
                        if (ProScreenFunc.IsBad(barcode))
                        {
                            MessageBox.Show("该条码已经做过报废处理!", "提示");
                            textBox2.Text = "";
                            textBox2.Visible = false;
                            return;
                        }
                        string planID = ProScreenFunc.GetPlanIDByBarcode(barcode);
                        ProScreenFunc.AddBadCount(planID.Trim());
                        ProScreenFunc.SubCompleteCount(planID.Trim());

                        ProScreenFunc.SaveRecord2(barcode, "0", planID);
                        DataTable dt = ProScreenFunc.GetProScreenByPlanID(this.Tag.ToString().Trim());
                        SetPage(dt);

                        textBox2.Text = "";
                        textBox2.Visible = false;
                    }
                    else
                    {
                        MessageBox.Show("还未进行装配!", "提示");

                        textBox2.Text = "";
                        textBox2.Visible = false;
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteErrLogBase(ex.ToString(), MethodBase.GetCurrentMethod().Name);
                }
            }
            else if (e.KeyCode == Keys.Escape)
            {
                textBox2.Text = "";
                textBox2.Visible = false;
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            textBox3.Visible = true;
            textBox3.Focus(); 
        }

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

        private void textBox3_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    try
                    {
                        string barcode = textBox3.Text.Trim();
                        if (barcode.Contains("."))
                        {
                            barcode = ProScreenFunc.UniteBarCodeToOne(barcode);
                        }

                        if (ProScreenFunc.IsBad(barcode))
                        {
                            string planID = ProScreenFunc.GetPlanIDByBarcode(barcode);
                            if (!ProScreenFunc.CheckPlanCompleted(planID))
                            {
                                ProScreenFunc.SubBadCount(planID.Trim());
                                ProScreenFunc.AddCompleteCount(planID.Trim());

                                ProScreenFunc.SaveRecord2(barcode, "1", planID);
                            }
                            else
                            {
                                string partNo = ProScreenFunc.GetPaintCode(barcode);
                                if (partNo == label3.Text.Trim())
                                {
                                    ProScreenFunc.AddCompleteCount(Tag.ToString().Trim());
                                    ProScreenFunc.SaveRecord2(barcode, "1", Tag.ToString().Trim());
                                }
                                else
                                {
                                    MessageBox.Show("当前扫描的零件与总成不匹配,请检查后再扫描!");
                                }
                            }
                            if (ProScreenFunc.CheckPlanCompleted(this.Tag.ToString().Trim()))
                            {
                                LoadScreen();
                            }
                            else
                            {
                                DataTable dt = ProScreenFunc.GetProScreenByPlanID(this.Tag.ToString().Trim());
                                SetPage(dt);
                            }

                            textBox3.Text = "";
                            textBox3.Visible = false;
                        }
                        else
                        {
                            MessageBox.Show("该条码未做过报废处理,无法转合格!", "提示");
                            textBox3.Text = "";
                            textBox3.Visible = false;
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.WriteErrLogBase(ex.ToString(), MethodBase.GetCurrentMethod().Name);
                    }
                }
                else if (e.KeyCode == Keys.Escape)
                {
                    textBox3.Text = "";
                    textBox3.Visible = false;
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(),MethodBase.GetCurrentMethod());
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            ProScreenFunc.SetPlanComplete(this.Tag.ToString().Trim());
            LoadScreen();
        }

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

        private void textBox4_DoubleClick(object sender, EventArgs e)
        {
            textBox4.Visible = false;
            textBox4.Text = "";
        }

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

                    if (string.IsNullOrEmpty(textBox4.Text))
                    {
                        MessageBox.Show("盖板条码不能为空!");
                        textBox4.Focus();
                        return;
                    }

                    if (textBox4.Text.Trim().Split('-').Length!=3)
                    {
                        MessageBox.Show("盖板条码有误!");
                        textBox4.SelectAll();
                        textBox4.Focus();
                        return;
                    }

                    if (textBox4.Text.Trim().Substring(0, 11) != "A2068853104")
                    {
                        MessageBox.Show("盖板条码有误!");
                        textBox4.SelectAll();
                        textBox4.Focus();
                        return;
                    }

                    string[] aa = textBox4.Text.Trim().Split('-');
                    string[] bb = label3.Text.Trim().Split('-');

                    if (aa[1] != bb[1])
                    {
                        MessageBox.Show("盖板条码颜色不符!");
                        textBox4.SelectAll();
                        textBox4.Focus();
                        return;
                    }

                    AfterScanBarcode(barcode, productID2, productID, base.Tag.ToString().Trim(), stationId);
                }
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(),MethodBase.GetCurrentMethod());
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {

        }

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