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.Threading;
using System.Windows.Forms;
using gregn6Lib;
using MESClassLibrary.BLL.Log;
using PunchAndWeld.DataSouce;
using PunchAndWeld.WebReference;

namespace PunchAndWeld
{
    public partial class FrmProScreen_WheelBrow : Form
    {
        private GridppReport Report = new GridppReport();
        private string oneBarCode = "";
        string stationNo = "", stationId = "";

        public FrmProScreen_WheelBrow()
        {
            InitializeComponent();
        }

        private void FrmProScreen_WheelBrow_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();
                stationId = ProScreenFunc.GetStationId(stationNo);
                label1.Text = ProScreenFunc.GetStation(stationNo);

                Control.CheckForIllegalCrossThreadCalls = false;
                Thread t = new Thread(new ThreadStart(TimeGo));
                t.Start();

                LoadScreen();
                textBox1.TabIndex = 0;
                textBox1.Select();
            }
            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)
        {
            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();
            string barcode = textBox1.Text.Trim();

            if (barcode.Length != 20)
            {
                MessageBox.Show("条码位数有误,请重新扫描!");
                textBox1.SelectAll();
                return;
            }

            #region 查询完成数==计划数,如果相等,就不允许扫描

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

            #endregion

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

            #region 查询是否已扫描过,如果扫过,需输入用户名密码,确认过才可以再扫

            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);
            }

            #endregion
        }

        private void ScanBarcode(string barcode)
        {
            string 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))
                {
                    string productID2 = ProScreenFunc.GetProductID(barcode);
                    if (!ProScreenFunc.CheckPartAndProduct(productID, productID2))
                    {
                        this.InsLog(productID, productID2);
                        MessageBox.Show("当前扫描的零件与总成不匹配,请检查后再扫描");
                        this.textBox1.Text = "";
                    }
                    else
                    {
                        SavePunch(barcode, productID2, productID, base.Tag.ToString().Trim(),stationId);
                        if (ConfigurationManager.AppSettings["IsHaveVisual"].ToString() != "1")
                        {
                            this.AfterScanBarcode1(barcode, productID2, productID, base.Tag.ToString().Trim());
                        }

                    }
                }
                else
                {
                    string productID2 = ProScreenFunc.GetProductID(code, "");
                    SavePunch(barcode, productID2, productID, base.Tag.ToString().Trim(), stationId);
                    if (ConfigurationManager.AppSettings["IsHaveVisual"].ToString() != "1")
                    {
                        this.AfterScanBarcode1(barcode, productID2, productID, base.Tag.ToString().Trim());
                    }
                }
            }
            else
            {
                string productID2 = "";

                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)
                    {
                        if (ConfigurationManager.AppSettings["IsHaveVisual"].ToString() != "1")
                        {
                            this.AfterScanBarcode1(barcode, productID2, productID, base.Tag.ToString().Trim());
                        }
                        else
                        {
                            SavePunch(barcode, productID2, productID, base.Tag.ToString().Trim(), stationId);
                        }
                    }
                }
            }
        }

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

        private void SavePunch(string barcode, string productID2, string productID1, string planID,string stationId)
        {
            #region 存储

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

            #endregion
        }

        private void AfterScanBarcode1(string barcode, string productID2, string productID1, string planID)
        {
            #region 调WMS接口

            try
            {
                LogHelper.WriteSysLogBase("条码号:" + barcode + "工位:" + label1.Text.Trim() + ",一码到底调用WMS接口", MethodBase.GetCurrentMethod().Name);

                string stockNo = "";
                string batchNo = "";
                string partNo = "";
                string filename = "", printName = "", tmp="",sn="", reportName="";
                ProScreenFunc.GetCode(barcode, out stockNo, out batchNo, out partNo);

                partNo = label3.Text.Trim();
                //2020-11-11 由原来的datetime.Now.ToString("yyyyMMdd")修改成计划的录入时间
                batchNo = ProScreenFunc.GetPlanTime(planID).ToString("yyyyMMdd");

                WMSWebService webService = new WMSWebService();
                webService.Url = ConfigurationManager.AppSettings["WMSWebServiceURL"].ToString();

                #region 存储

                DateTime time = DateTime.Now;
                tmp = ProScreenFunc.SerialNo(label3.Text.Trim(), time.ToString("yyMMdd"));
                 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');
                }

                if ( ProScreenFunc.SavePartAndProduct1(barcode, productID2, productID1, label2.Text, label8.Text,
                    planID, sn,stationId, ConfigurationManager.AppSettings["StationDescription"])<=0)
                {
                    MessageBox.Show("连接数据库失败!");
                    return;
                }

                //ProScreenFunc.SaveZcCode(barcode, label3.Text.Trim());

                #endregion

                #region 完成数量+1

                if ( ProScreenFunc.AddCompleteCount(this.Tag.ToString().Trim()) <= 0)
                {
                    MessageBox.Show("连接数据库失败!");
                    return;
                }

                #endregion

                #region 打印标签

                try
                {
                    if (ConfigurationManager.AppSettings["PrintEnable"].ToString().ToLower() == "true")
                    {
                        filename = AppDomain.CurrentDomain.BaseDirectory + "aaa.grf";

                        DataTable headTable = new DataTable();
                        headTable.Columns.Add("zcPartNo");
                        headTable.Columns.Add("zcName");
                        headTable.Columns.Add("oneBarCode");
                        headTable.Columns.Add("SerialNo");
                        headTable.Columns.Add("BatchNo");

                        DataRow row = headTable.NewRow();
                        row["zcPartNo"] = label3.Text.Trim();
                        row["zcName"] = label4.Text.Trim();
                        row["BatchNo"]  = time.ToString("yyMMdd");
                        row["oneBarCode"] = barcode;
                        row["SerialNo"] = sn;

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

                        ReportHelper rp = new ReportHelper(filename, headTable, null,
                            (int)GRPaperOrientation.grpoDefault, 1, reportName);
                        rp.Report.Print(false);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                #endregion

                #region 是否计划已完成

                if (ProScreenFunc.CheckPlanCompleted(this.Tag.ToString().Trim()))
                {
                    LoadScreen();
                }
                else
                {
                    label7.Text = ProScreenFunc.GetCompleteCount(this.Tag.ToString().Trim());
                }

                #endregion
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLogBase("工位:" + label1.Text.Trim() + ",一码到底调用WMS接口:" + ex.ToString(), MethodBase.GetCurrentMethod().Name);
            }

            #endregion

            ProScreenFunc.SavePartAndProductBF(barcode, productID2, productID1, label2.Text, label8.Text, planID);
        }

        /// <summary>
        /// 上一计划
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_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("无上一计划");
            }
        }

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

        /// <summary>
        /// 补打标签
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            textBox4.Text = "";
            textBox4.Visible = true;
            textBox4.Focus();
        }

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

                    DataTable dtHg = ProScreenFunc.GetGh(barcode);
                    if (dtHg == null || dtHg.Rows.Count < 1)
                    {
                        MessageBox.Show("未装配,不能补打标签!");
                        textBox4_DoubleClick(sender, e);
                        return;
                    }

                    DataTable dtBl = ProScreenFunc.GetBl(barcode);
                    if (dtBl != null && dtBl.Rows.Count > 0)
                    {
                        DateTime hgTime = (DateTime)Tools.NumericParse.StringToDateTime("1900-01-01 00:00:00");
                        DataTable dtHG1 = ProScreenFunc.GetHG_New(barcode);
                        if (dtHG1 != null && dtHG1.Rows.Count > 0)
                        {
                            hgTime = (DateTime)Tools.NumericParse.StringToDateTime(dtHG1.Rows[0]["CreateTime"].ToString());
                        }

                        DateTime blTime = (DateTime)Tools.NumericParse.StringToDateTime(dtBl.Rows[0]["createTime"].ToString());
                        if (DateTime.Compare(blTime, hgTime) > 0)
                        {
                            MessageBox.Show("产品不良,不能补打标签!");
                            textBox4_DoubleClick(sender, e);
                            return;
                        }
                    }

                    LogSysBLL.AddInfo("条码:" + barcode + "补打标签", MethodBase.GetCurrentMethod());

                    string zcID = dtHg.Rows[0]["ZcID"].ToString();
                    ZcPrintLabel zl = ProScreenFunc.GetZcPrintLabel(zcID);
                    if (zl != null && zl.zcPartNo != null && zl.zcName != null)
                    {
                        if (ConfigurationManager.AppSettings["PrintEnable"].ToString().ToLower() == "true")
                        {
                            string filename = AppDomain.CurrentDomain.BaseDirectory + "aaa.grf";

                            DataTable headTable = new DataTable();
                            headTable.Columns.Add("zcPartNo");
                            headTable.Columns.Add("zcName");
                            headTable.Columns.Add("oneBarCode");
                            headTable.Columns.Add("SerialNo");
                            headTable.Columns.Add("BatchNo");

                            DataRow row = headTable.NewRow();
                            row["zcPartNo"] = zl.zcPartNo;
                            row["zcName"] = zl.zcName;
                            string sn = dtHg.Rows[0]["SerialNo"].ToString();
                            string[] tmp = sn.Split('.');
                            row["BatchNo"] = tmp[1];
                            row["oneBarCode"] = barcode;
                            row["SerialNo"] = dtHg.Rows[0]["SerialNo"].ToString(); ;

                            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);
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogErrBLL.AddInfo(ex.ToString(),MethodBase.GetCurrentMethod());
                    textBox4_DoubleClick(sender, e);
                }
            }
        }

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

        private void timer1_Tick(object sender, EventArgs e)
        {
            string orderNo = label2.Text.Trim();
            if (string.IsNullOrWhiteSpace(orderNo))
            {
                LoadScreen();
            }
        }

        /// <summary>
        /// 计划完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button7_Click(object sender, EventArgs e)
        {
            ProScreenFunc.SetPlanComplete(this.Tag.ToString().Trim());
            LoadScreen();
        }

        /// <summary>
        /// 计划查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button6_Click(object sender, EventArgs e)
        {
            FrmProScreen2 frm = new FrmProScreen2();
            frm.Show();
        }

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