using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;
using QMAPP.FJC.Entity;
using QMAPP.FJC.Entity.Basic;
using QMAPP.FJC.Entity.Operation;
using QMAPP.FJC.Entity.SendPlan;
using QMAPP.ServicesAgent;
using QMAPP.WinForm.Common;
using QMFrameWork.Common.Serialization;
using QMFrameWork.Data;
using QMAPP.Entity;
using System.Linq;
using System.Reflection;
using System.ServiceModel;
using System.Threading;
using System.Net.Sockets;
using System.IO;
using QMAPP.FJC.Entity.QT;
using QMAPP.FJC.TRACING.DAInterface;
using QMAPP.WinForm.Forms.Andon;
using DCS.Common;
using QMAPP.WinForm.Forms.Mend;
using System.Collections;
using QMAPP.FJC.Entity.ProductionPlan;
using gregn6Lib;
using System.Data;
using QMAPP.FJC.Entity.BZD;

namespace QMAPP.WinForm.Forms.Operation
{
    /// <summary>
    /// 描述:加工操作
    /// 作者:王庆男
    /// 时间:2015年7月1日
    /// </summary>
    [CallbackBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, UseSynchronizationContext = false)]
    public partial class OperationForm : Form, ServiceOpc.IOpcServiceCallback
    {
        #region 全局变量
        public static SynchronizationContext SynchronizationContext;
        //与服务器传递参与以及窗口静态变量
        OperationServiceParam _operationServiceParam = new OperationServiceParam();
        //获取服务代理
        QMAPP.ServicesAgent.ServiceAgent _agent = ClientContext.GetServiceAgent();

        ServiceOpc.OpcServiceClient proy;//连接OPC服务

        BarCodeHook BarCode = new BarCodeHook();

        /// <summary>
        /// 附加信息
        /// </summary>
        Dictionary<string, string> AttachInfo = new Dictionary<string, string>();

        /// <summary>
        /// 采集点列表
        /// </summary>
        private List<DAI> daiList = new List<DAI>();
        /// <summary>
        /// 数据采集点视图
        /// </summary>
        private BindingList<FJC.Entity.View.DAIFormView> daiviewSource = new BindingList<FJC.Entity.View.DAIFormView>();
        /// <summary>
        /// 数据采集点视图
        /// </summary>
        private List<FJC.Entity.View.DAIFormView> daicache = new List<FJC.Entity.View.DAIFormView>();
        /// <summary>
        /// 模架列表
        /// </summary>
        private List<MachineInfoModels> mouldList = new List<MachineInfoModels>();
        /// <summary>
        /// 条码格式规则列表
        /// </summary>
        private List<BarcodeRules> _barcodeRules;

        /// <summary>
        /// 正确的声音文件路径
        /// </summary>
        private string okSoundPath = null;
        /// <summary>
        /// 错误的声音文件路径
        /// </summary>
        private string errorSoundPath = null;
        /// <summary>
        /// 用于隐藏计划tab页
        /// </summary>
        Hashtable htPages = new Hashtable();

        private string _showDetailError = "false"; //后修改内容,若果true. 发生异常时显示异常详细信息. false,显示内容和原来一样,不发生变化
        private string _lowCfgAutoSwitchLoc = string.Empty; //自动填充配置的工位
        private string _ipGJBarCodeRegex = string.Empty;

        private string[] _cfgAutoInputLocs = null;//DP 自动输入配置的工位
        private string _cfgAutoInputSwitch = string.Empty; //DP 自动输入配置的开关
        private string _bentiBarCodeRegex = string.Empty; //DP 自动输入配置的开关

        private string _052printWorkloc = string.Empty; //052打印工位

        #endregion

        #region 窗体构造函数
        /// <summary>
        /// 窗体构造函数
        /// </summary>
        public OperationForm()
        {
            InitializeComponent();
            
            _showDetailError = System.Configuration.ConfigurationManager.AppSettings["是否显示异常详细信息"]?.ToLower();
            _lowCfgAutoSwitchLoc = GetAppConfigValue("AutomationLocAdd"); //查找所有 需要自动填充的工位
            _ipGJBarCodeRegex = GetAppConfigValue("AutomationBarCodeRegex"); //查找所有 需要自动填充的工位

            var str__cfgAutoInputLocs = GetAppConfigValue("AutoInputLocAdd"); //查找所有 需要自动填充的工位
            if (str__cfgAutoInputLocs.Split(';').Length > 0)
                _cfgAutoInputLocs = str__cfgAutoInputLocs.Split(';');
            _cfgAutoInputSwitch = GetAppConfigValue("AutoInputSwitch"); //查找所有 需要自动填充的工位
            _bentiBarCodeRegex = System.Configuration.ConfigurationManager.AppSettings["AutoInput条码正则表达式"]?.Trim();

            _052printWorkloc = System.Configuration.ConfigurationManager.AppSettings["052打印工位"];

            this.WindowState = FormWindowState.Maximized;
            //this.CheckFile();
            okSoundPath = System.Configuration.ConfigurationManager.AppSettings["SaveFilePath"] + "Sound\\" + PlaySoundConst.strSoundOk;
            errorSoundPath = System.Configuration.ConfigurationManager.AppSettings["SaveFilePath"] + "Sound\\" + PlaySoundConst.strSoundNg;
            SynchronizationContext = new SynchronizationContext();
            BarCode.BarCodeEvent += new BarCodeHook.BarCodeDelegate(BarCode_BarCodeEvent);
            BarCode.Start();
        }
        #endregion 

        #region 键盘Hook
        void BarCode_BarCodeEvent(BarCodeHook.BarCodes barCode)
        {
            ShowInfo(barCode);
        }

        private void ShowInfo(BarCodeHook.BarCodes barCode)
        {
            if (!this.txtCode.Focused)
            {
                this.txtCode.Focus();
            }
        }
        #endregion

        #region 窗体载入
        private void Form_Load(object sender, EventArgs e)
        {
            LoadViewSetting();

            //初始化控件属性
            this.DGView.AutoGenerateColumns = false;
            this.DGViewProList.AutoGenerateColumns = false;

            //隐藏工单计划
            //DeletePlanPage("tpPlan");

            //加载所有设备下拉列表
            LoadMachineList();

            _barcodeRules = _agent.InvokeServiceFunction<List<BarcodeRules>>(B9BasicService.BarcodeRulesBLL_GetAllList.ToString());

            this.DGView.DataSource = daiviewSource;
            //页面初始化
            Init();

            //tsbRe.Visible = false;
            DGViewProList.ClearSelection();

            #region 打印模板拷贝
            PrintTempleCopyClass printClass = new PrintTempleCopyClass();
            printClass.CopyPrintTemple("IPASSYLABEL");
            printClass.CopyPrintTemple("DPPLANLABEL");
            #endregion
            btnRefresh.Visible = true;
            txtCode.Focus();
        }
        #endregion

        #region 加载设备列表
        /// <summary>
        /// 加载设备列表
        /// </summary>
        private void LoadMachineList()
        {
            #region
            BasicData basicData = new BasicData();
            var machinelist=basicData.GetMachineInfoAndModelList(new string[] { }, true);
            this.comMachine.DataSource = machinelist;
            this.comMachine.DisplayMember = "MACHINENAME";
            this.comMachine.ValueMember = "MACHINECODDE";

            //如果工位已设定
            if (ClientContext.MachineInfo != null && !string.IsNullOrEmpty(ClientContext.MachineInfo.PID))
            {
                this.comMachine.SelectedValue = ClientContext.MachineInfo.MACHINECODDE;
                //this.lblLock.Visible = false;
                this.LockType(false);
            }
            else
            {
                //this.lblLock.Visible = false;
                this.LockType(false);
            }
            #endregion
        }
        #endregion

        #region 加载列表显示设置
        /// <summary>
        /// 加载列表显示设置
        /// </summary>
        private void LoadViewSetting()
        {
            #region 加载列表显示设置
            string filepath = ConfigurationManager.AppSettings["SaveFilePath"];
            filepath = string.Format("{0}ViewSetting.cfg", filepath);

            var setting = new { ListRowcount = 20, RefreshRate = 5 };
            if (System.IO.File.Exists(filepath))
            {
                string settingstring = System.IO.File.ReadAllText(filepath);
                setting = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(settingstring, setting);
            }
            cbListRowcount.Text = setting.ListRowcount.ToString();
            cbRefreshRate.Text = string.Format("{0}s", setting.RefreshRate);
            cbPlanFilter.SelectedIndex = 1;

            cbListRowcount.SelectedIndexChanged += new EventHandler(cbListRowcount_SelectedIndexChanged);
            cbRefreshRate.SelectedIndexChanged += new EventHandler(cbRefreshRate_SelectedIndexChanged);
            cbPlanFilter.TextChanged += new EventHandler(cbPlanFilter_SelectedIndexChanged);

            #endregion
        }
        #endregion

        #region 初始化界面
        /// <summary>
        /// 初始化界面
        /// 加载当前设备对应的工序信息
        /// 加载当前工序的先决条件
        /// </summary>
        private void Init()
        {
            ClientContext.OpcState = 0;
            var mouldno=0;
            this.tsbConnect.Visible = false;
            this.tsbReSignal.Visible = false;
            this.btnChange.Visible = false;
            this.cBoxVAN.Visible = false;
            this.lblError.Text = "";
            this.lblError.ForeColor = Color.Black;
            this.lblError.BackColor = SystemColors.InactiveBorder;
            _operationServiceParam = new OperationServiceParam();
            _operationServiceParam.produceShift = ClientContext.produceShift;
            _operationServiceParam.machineInfo = this.comMachine.SelectedItem as MachineInfo;
            if (string.IsNullOrEmpty(_operationServiceParam.machineInfo.PID))
            {
                return;
            }
            if (!string.IsNullOrEmpty(_operationServiceParam.machineInfo.OPCGROUPNAME))
            {
                btnChange.Visible = true;
            }
            //****************20210413 DQZhang BC316 VAN **************************************
            if (_operationServiceParam.machineInfo.MACHINECODDE== "ASSEMBLE_BC316")
            {
                this.cBoxVAN.Visible = true;
            }
            //*********************************************************************************
            //else
            //{
            //    //隐藏工单计划
            //    if (_operationServiceParam.machineInfo.PLAN_SET == "1")
            //    {
            //        DeletePlanPage("tpPlan");
            //    }
            //    else
            //    {
            //        AddPage("tpPlan");
            //    }
            //}
            if (LocalSetting.Settings["AbilityValid","1"] == "1")
            {
                var userabbility = _agent.InvokeServiceFunction<List<MD.Entity.UserWithMachine>>("UserWithMachineBLL_GetUserAbility", ClientContext.LoginInfo.UserID);
                if (!userabbility.Exists(p => p.MACHINEID == _operationServiceParam.machineInfo.PID) && !string.Equals("ADMIN", ClientContext.LoginInfo.LoginUserID))
                {
                    plDAI.Enabled =
                    txtCode.Enabled =
                    btnAdd.Enabled =
                    panel4.Enabled =
                    toolStrip1.Enabled = false;
                    MessageBox.Show("当前登录用户不具备此工位的操作能力!\r\n请更换用户或联系管理员设置能力矩阵。", "操作者能力矩阵", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }

            if (string.IsNullOrEmpty(_operationServiceParam.machineInfo.MOLDNUMBER))
            {
                _operationServiceParam.machineInfo.MOLDNUMBER = "1";
            }
            _operationServiceParam.produceShift = ClientContext.produceShift;
            mouldno = ConnectOPCHost(mouldno);
            LoadDAI(mouldno);
            BindAll();

            //var extendpages=tabView.TabPages.
            tabView.TabPages.Clear();
            tabView.TabPages.Add(tpPlan);
            tabView.TabPages.Add(tpRecord);

            if (_operationServiceParam.machineInfo.OPERATETYPE == "EINSP")//终检工位,增加卡扣漏装检测设备接口
            {
                DeviceInterface.LeakInspection frm = new DeviceInterface.LeakInspection();
                
                
                var tabpage = new TabPage(frm.Text);
                tabView.TabPages.Add(tabpage);
                frm.TopLevel = false;
                frm.Parent = tabpage;
                //frm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
                frm.Machine = _operationServiceParam.machineInfo;
                //frm.WindowState = FormWindowState.Maximized;
                //frm.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
                frm.Dock = DockStyle.Fill;
                frm.Show();

                tabpage.BackColor = Color.Black;
                //tabpage.Controls.Add(frm);
                
            }

        }
        #endregion

        #region 加载采集点信息
        /// <summary>
        /// 加载采集点信息
        /// </summary>
        /// <param name="mouldno"></param>
        private void LoadDAI(int mouldno)
        {
            #region 获取采集点

            daiList = _agent.InvokeServiceFunction<List<DAI>>(B9IPCService.DAIBLL_GetList.ToString(), new DAI() { WORKLOC_CODE = _operationServiceParam.machineInfo.WORKLOC_CODE });
            var cachelist = _agent.InvokeServiceFunction<List<DAICache>>(B9IPCService.DAICacheBLL_GetWorklocCache.ToString(), _operationServiceParam.machineInfo.WORKLOC_CODE);
            mouldList = _agent.InvokeServiceFunction<List<MachineInfoModels>>(B9BasicService.MachineInfoModelBLL_GetAllList.ToString(), new MachineInfoModels { MID = _operationServiceParam.machineInfo.PID }).OrderBy(p=>p.MODELCODE).ToList();
            cbMould.DisplayMember = "MODELNAME";
            cbMould.ValueMember = "MODELCODE";
            cbMould.DataSource = mouldList.ToList();
            mouldList.Insert(0, new MachineInfoModels { MODELCODE = "" });


            daicache.Clear();
            foreach (var mould in mouldList)
            {
                foreach (var dai in daiList.Where(p => string.Equals(p.DIVBY_MOULD, mould.MODELCODE != "" ? "1" : "0")))
                {
                    var daiview = new FJC.Entity.View.DAIFormView
                    {
                        DACode = dai.DA_CODE,
                        DAName = dai.DA_NAME,
                        DAResult = "",
                        DAType = dai.DATA_TYPE,
                        MaterialType = dai.MATERIAL_TYPE,
                        MaterialTypeName = "",// dai.MATERIAL_TYPE_NAME,
                        MaterialCode = "",
                        MaterialName = "",
                        StateCode = dai.STATE_CODE,
                        StateName = dai.STATE_NAME,
                        DAValue = "",
                        MouldCode = string.IsNullOrWhiteSpace(mould.MODELCODE) ? dai.WORKCELL_CODE : mould.MODELCODE,
                        MouldName = mould.MODELNAME,
                    };
                    var cache = cachelist.FirstOrDefault(p => p.DA_CODE == daiview.DACode && (string.IsNullOrWhiteSpace(p.MOULD_CODE) || p.MOULD_CODE == daiview.MouldCode) && (!string.Equals(p.PREINPUT, "1")));
                    if (cache != null && !string.IsNullOrWhiteSpace(cache.DA_VALUE))
                    {
                        daiview.DAValue = cache.DA_VALUE;
                        daiview.MaterialCode = cache.MATERIAL_CODE;
                        daiview.MaterialName = cache.MATERIAL_NAME;
                        daiview.DAResult = "通过";
                    }
                   
                    daicache.Add(daiview);
                }

            }

            dgcMouldName.Visible = mouldList.Count > 1;

            if (daiList.Count(p => string.Equals(p.CANPREINPUT, "1")) > 0)
            {
                dgcMouldName.Visible = true;
                int i = 0;
                int m = mouldList.Count;
                if (string.Equals(_operationServiceParam.machineInfo.ISSTATION, 2))
                {
                    i = 1;
                }
                else
                {
                    i = 0;
                    m = 1;
                }
                for (; i < m; i++)
                {
                    foreach (var dai in daiList.Where(p => string.Equals(p.CANPREINPUT, "1")))
                    {
                        var mould = mouldList[i];
                        var daiview = new QMAPP.FJC.Entity.View.DAIFormView
                        {
                            DACode = dai.DA_CODE,
                            DAName = dai.DA_NAME,
                            DAResult = "",
                            DAType = dai.DATA_TYPE,
                            MaterialType = dai.MATERIAL_TYPE,
                            MaterialCode = "",// dai.MATERIAL_TYPE_NAME,
                            MaterialName = "",
                            StateCode = dai.STATE_CODE,
                            StateName = dai.STATE_NAME,
                            DAValue = "",
                            MouldCode = "PRE-" + (string.IsNullOrWhiteSpace(mould.MODELCODE) ? dai.WORKCELL_CODE : mould.MODELCODE),
                            MouldName = "预备",
                            PREINPUT = "1"
                        };
                        var cache = cachelist.FirstOrDefault(p => p.DA_CODE == daiview.DACode && string.Equals(p.PREINPUT, "1")&&string.Equals(p.MOULD_CODE,(string.IsNullOrWhiteSpace(mould.MODELCODE) ? dai.WORKCELL_CODE : mould.MODELCODE)));
                        if (cache != null && !string.IsNullOrWhiteSpace(cache.DA_VALUE))
                        {
                            daiview.DAValue = cache.DA_VALUE;
                            daiview.MaterialCode = cache.MATERIAL_CODE;
                            daiview.MaterialName = cache.MATERIAL_NAME;
                            daiview.DAResult = "通过";
                        }
                        daicache.Add(daiview);
                    }
                }
            }

            //dgcMouldName.Visible = mouldList.Count > 1;
            lblMouldTitle.Visible = cbMould.Visible = mouldList.Count > 1;



            if (mouldList.Count <= 2)
            {
                SwitchMould("");
            }
            else
            {
                if (mouldno > 0)
                {
                    var mould = mouldList.FirstOrDefault(p => string.Equals(p.MODELSTATION, mouldno.ToString()));
                    if (mould != null)
                    {
                        SwitchMould(mould.MODELCODE);
                    }
                }
                else
                {
                    SwitchMould("");
                }
                //cbMould_SelectedIndexChanged(this, EventArgs.Empty);
            }

            //= _agent.InvokeServiceFunction<List<DAI>>(B9IPCService.DAIBLL_GetList.ToString(), new DAI() { WORKLOC_CODE = _operationServiceParam.machineInfo.WORKLOCCODE });



            #endregion
        }

        #endregion 

        #region 连接OPC服务
        //TODO:优化连接失败时的长时间卡死状态
        /// <summary>
        /// 连接OPC服务
        /// </summary>
        /// <param name="mouldno"></param>
        /// <returns></returns>
        private int ConnectOPCHost(int mouldno)
        {
            if (string.IsNullOrEmpty(_operationServiceParam.machineInfo.PID))
            {
                ClientContext.OpcState = 0;
                proy = null;
                return 0;
            }
            if (!_operationServiceParam.machineInfo.ISCONTROL.Equals("0"))
            {
                System.ServiceModel.InstanceContext site = new System.ServiceModel.InstanceContext(this);
                proy = new ServiceOpc.OpcServiceClient(site);

                //设置与设备双工通信
                if (_operationServiceParam.machineInfo.ISCONTROL.Equals("2") || _operationServiceParam.machineInfo.ISCONTROL.Equals("3"))
                {
                    this.tsbConnect.Visible = true;
                    this.tsbReSignal.Visible = true;
                    if (proy.State == System.ServiceModel.CommunicationState.Created || proy.State == System.ServiceModel.CommunicationState.Opened)
                    {
                        try
                        {
                            ClientContext.OpcState = 4;
                            this.lblError.Text = "正在连接中稍后...";

                            mouldno = proy.Register(_operationServiceParam.machineInfo.MACHINECODDE);
                            ClientContext.OpcState = 1;
                            this.lblError.Text = "服务器连接成功!";
                            this.lblError.ForeColor = Color.Green;
                        }
                        catch (Exception)
                        {
                            ClientContext.OpcState = 2;
                            this.lblError.Text = "连接服务失败!";
                            this.lblError.ForeColor = Color.White;
                            this.lblError.BackColor = Color.Red;
                        }
                    }
                    else
                    {
                        ClientContext.OpcState = 2;
                        this.lblError.Text = "服务已经断开,请重连!";
                        this.lblError.ForeColor = Color.White;
                        this.lblError.BackColor = Color.Red;
                    }
                }
            }
            else
            {
                ClientContext.OpcState = 0;
                proy = null;
            }
            return mouldno;
        }
        #endregion

        #region 行序号
        /// <summary>
        /// 行序号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DG_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, this.DGView.RowHeadersWidth - 4, e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), new Font("宋体", 12, FontStyle.Bold), rectangle, this.DGView.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }
        #endregion 

        #region 添加零件
        /// <summary>
        /// 添加零件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            WriteLog.Write(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "      " + txtCode.Text.Trim().ToUpper());
            Operation();
        }
        #endregion 

        #region 采集点扫描校验
        /// <summary>
        /// 采集点扫描校验
        /// </summary>
        private void Operation()
        {

            try
            {
                this.lblError.Text = "";
                this.lblError.ForeColor = Color.Black;
                this.lblError.BackColor = SystemColors.InactiveBorder;
                //使用登录码快速切换用户
                if (System.Text.RegularExpressions.Regex.IsMatch(txtCode.Text, "^<\\w+::\\w+>$"))
                {
                    var ret = ClientContext.CodeLogin(txtCode.Text);
                    if (string.Equals(ret, "登录成功!"))
                    {
                        ClientContext.SetUserAuth(this);
                        if (LocalSetting.Settings["AbilityValid", "1"] == "1")
                        {
                            var userabbility = _agent.InvokeServiceFunction<List<MD.Entity.UserWithMachine>>("UserWithMachineBLL_GetUserAbility", ClientContext.LoginInfo.UserID);
                            if (!userabbility.Exists(p => p.MACHINEID == _operationServiceParam.machineInfo.PID) && !string.Equals("ADMIN", ClientContext.LoginInfo.LoginUserID))
                            {
                                plDAI.Enabled =
                                txtCode.Enabled =
                                btnAdd.Enabled =
                                panel4.Enabled =
                                toolStrip1.Enabled = false;
                                MessageBox.Show("当前登录用户不具备此工位的操作能力!\r\n请更换用户或联系管理员设置能力矩阵。", "操作者能力矩阵", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            }
                        }
                    }
                    lblError.Text = ret;
                    txtCode.Text = "";
                    txtCode.SelectAll();
                    txtCode.Focus();
                    return;
                }

                #region 输入条码校验
                //判断设备列表
                if (comMachine.Items.Count <= 0)
                {
                    txtCode.Text = "";
                    PlaySound.PlaySounds.Play(@errorSoundPath);
                    this.lblError.Text = "请先选择设备!";
                    this.lblError.ForeColor = Color.White;
                    this.lblError.BackColor = Color.Red;
                    txtCode.SelectAll();
                    txtCode.Focus();
                    return;
                }

                string productCode = this.txtCode.Text.Trim().ToUpper();//窗体零件条码
                if (string.IsNullOrEmpty(productCode))
                {
                    txtCode.Text = "";
                    PlaySound.PlaySounds.Play(@errorSoundPath);
                    this.lblError.Text = "请输入条码!";
                    this.lblError.ForeColor = Color.White;
                    this.lblError.BackColor = Color.Red;
                    txtCode.SelectAll();
                    txtCode.Focus();
                    return;
                }
                this.lblError.Text = "";
                this.lblError.ForeColor = Color.Black;
                this.lblError.BackColor = SystemColors.InactiveBorder;

                #endregion

                #region 条码格式解析

                var dai = LocateDAI(productCode);
                if (dai == null)
                {
                    txtCode.Text = "";
                    PlaySound.PlaySounds.Play(@errorSoundPath);
                    this.lblError.Text = "输入条码不是本工序可接受格式!";
                    this.lblError.ForeColor = Color.White;
                    this.lblError.BackColor = Color.Red;
                    txtCode.SelectAll();
                    txtCode.Focus();
                    return;
                }

                this.lblError.Text = "";
                this.lblError.ForeColor = Color.Black;
                this.lblError.BackColor = SystemColors.InactiveBorder;
                #endregion

                object davalue = productCode;
                //采集点输入
                var result = _agent.InvokeServiceFunction<DAResult>(B9IPCService.DAI_Input.ToString()
                                                                   , new DAArgs
                                                                   {
                                                                       WorkCellCode = dai.WORKCELL_CODE,
                                                                       WorkLocCode = dai.WORKLOC_CODE,
                                                                       DACode = dai.DA_CODE,
                                                                       DAValue = davalue,
                                                                       MaterialCode = dai.MATERIAL_CODE,
                                                                       MachineCode = _operationServiceParam.machineInfo.MACHINECODDE,
                                                                       MachineName = _operationServiceParam.machineInfo.MACHINENAME,
                                                                       IsControl = _operationServiceParam.machineInfo.ISCONTROL,
                                                                       MouldCode = string.Equals(dai.DIVBY_MOULD, "0") ? _operationServiceParam.machineInfo.WORKCELL_CODE : (string.IsNullOrWhiteSpace(lblMould.Text) ? _operationServiceParam.machineInfo.WORKCELL_CODE : lblMould.Text),
                                                                       AttachData = AttachInfo
                                                                   });
                var daiview = daicache.FirstOrDefault(p => p.DACode == dai.DA_CODE && (string.IsNullOrWhiteSpace(p.MouldCode) || p.MouldCode == (result.PreInput ? "PRE-" + result.MouldCode : result.MouldCode)));
                if (result.PreInput)
                {
                    string mouldcode = result.MouldCode;
                    if (_operationServiceParam.machineInfo.ISSTATION != 2)
                    {
                        mouldcode = _operationServiceParam.machineInfo.WORKCELL_CODE;
                    }
                    daiview = daicache.FirstOrDefault(p => p.DACode == dai.DA_CODE && (string.IsNullOrWhiteSpace(p.MouldCode) || p.MouldCode == "PRE-" + mouldcode));
                }

                if (!string.IsNullOrEmpty(_052printWorkloc) &&
                    _052printWorkloc.Contains(_operationServiceParam.machineInfo.WORKLOC_CODE))
                {
                    if (string.IsNullOrEmpty(processMainCode))
                    {
                        processMainCode = productCode;
                        if (!string.IsNullOrEmpty(result.MATERIAL_CODE))
                        {
                            List<FJC.Entity.ProductionPlan.WorkOrder> list1 =
                                this.dgvPlan.DataSource as List<FJC.Entity.ProductionPlan.WorkOrder>;
                            var PbomItem = _agent.InvokeServiceFunction<List<PbomItem>>(B9IPCService.PbomItemBLL_Get.ToString(), result.MATERIAL_CODE);
                            var BomCodes = "";
                            if (PbomItem != null && PbomItem.Count > 0)
                            {
                                BomCodes = PbomItem[0].PBOM_CODE;

                                var SSS = _agent.InvokeServiceFunction<Bom>(B9IPCService.PbomItemBLL_GetBom.ToString(), BomCodes);
                                if (SSS != null)
                                    planMATERIAL_CODE = SSS.MATERIAL_CODE;
                            }
                             
                            //List<string> pBomCodes1 = GetPBOMCODEValue(result.MATERIAL_CODE);

                            //List<FJC.Entity.ProductionPlan.WorkOrder> filterList1 =
                            //    list1.Where(p => pBomCodes1.Contains(p.PBOM_CODE)).ToList();


                            //if (filterList1.Count > 0)
                            //{
                            //    planMATERIAL_CODE = filterList1[0].MATERIAL_CODE;
                            //}
                        }
                    }

                }

                if (!result.Success) //如果采集数据输入失败
                {
                    PlaySound.PlaySounds.Play(@errorSoundPath);
                    this.lblError.Text = result.Message;
                    this.lblError.ForeColor = Color.White;
                    this.lblError.BackColor = Color.Red;

                    if (daiview != null)
                    {
                        if (daiview.DAResult != "通过")
                        {
                            daiview.DAResult = "未通过";
                            daiview.DAValue = productCode;
                            daiview.MaterialType = result.MATERIAL_CODE;
                        }
                    }

                    dai.MATERIAL_CODE = string.IsNullOrEmpty(result.MATERIAL_CODE) ? "" : result.MATERIAL_CODE;
                    dai.Result = EnumGeter.ORDERTYPE.NOK.GetHashCode().ToString();
                }
                else
                {
                    if (daiview != null)
                    {
                        daiview.DAResult = "通过";
                        daiview.DAValue = productCode;
                        daiview.MaterialCode = result.MATERIAL_CODE;
                        daiview.MaterialName = result.MATERIAL_NAME;
                    }

                    dai.MATERIAL_CODE = result.MATERIAL_CODE;
                    dai.Result = dai.Result = EnumGeter.ORDERTYPE.OK.GetHashCode().ToString();

                    //执行返回结果中包含的动作
                    DoResultActions(result);

                    this.txtCode.Text = "";

                    if (this.lblLock.Tag.ToString().Equals("0"))
                    {
                        LockType(false);
                    }
                }
                try
                {
                    #region 工位自动输入采集点信息
                    //工位与配置  且经过所有的验证
                    if (result.Success && !string.IsNullOrEmpty(_lowCfgAutoSwitchLoc) && _lowCfgAutoSwitchLoc.Contains(_operationServiceParam.machineInfo.WORKLOC_CODE))
                    {
                        var ispass = false;
                        foreach (var str in _ipGJBarCodeRegex.Split(';'))
                        {
                            if (System.Text.RegularExpressions.Regex.IsMatch(productCode, str))//扫描的是过程主码
                                ispass = true;
                        }
                        if (ispass)//扫描的是过程主码
                        {
                            List<FJC.Entity.ProductionPlan.WorkOrder> list = this.dgvPlan.DataSource as List<FJC.Entity.ProductionPlan.WorkOrder>;

                            var pBomcode = GetWorkOrder_MATERIAL_CODE(result.WorkOrderID);

                            if (!string.IsNullOrEmpty(pBomcode))
                            {
                                //List<FJC.Entity.ProductionPlan.WorkOrder> filterList = list.Where(p => pBomCodes.Contains(p.MATERIAL_CODE)).ToList();

                                var ScanIPConfig_list = GetSendPlcConfig(new ScanIPConfig() { MaterialCode = pBomcode, LocCode = _operationServiceParam.machineInfo.WORKLOC_CODE });
                                if (ScanIPConfig_list != null && ScanIPConfig_list.Count > 0)
                                {
                                    foreach (var Config in ScanIPConfig_list)
                                    {
                                        if (!string.IsNullOrEmpty(Config.PlcAddr))
                                        {
                                            var BarCode = Config.BarCode;
                                            var PlcAddr = Config.PlcAddr;
                                            GetNewCode(ref BarCode, ref PlcAddr);  //查询产品条码是否存在
                                            if (UpdateSendPlcConfig(new ScanIPConfig { PID = Config.PID, PlcAddr = PlcAddr }) )
                                            {
                                                var ProductList = SelectProduct(Config.BarCode);
                                                if (ProductList != null)
                                                {
                                                    var PID = Guid.NewGuid().ToString();
                                                    var ProductNew = new Product()
                                                    {
                                                        PRODUCTCODE = BarCode,
                                                        PID = PID,
                                                        MACHINECODDE = _operationServiceParam.machineInfo.MACHINECODDE,
                                                        MACHINENAME = _operationServiceParam.machineInfo.MACHINENAME,
                                                        PRODUCTSOURCE = "0",
                                                        MATERIAL_CODE = ProductList.MATERIAL_CODE,
                                                        STATUS = "0",
                                                        OUTFLAG = "0",
                                                        USINGSTATE = "0",
                                                        CAPACITY = 1,
                                                        USINGCOUNT = 0,
                                                        WORKCELL_CODE = ProductList.WORKCELL_CODE,
                                                        WORKLOC_CODE = ProductList.WORKLOC_CODE,
                                                        WORKCENTER_CODE = ProductList.WORKCENTER_CODE
                                                    };
                                                    
                                                    var ProcessRecords = new ProcessRecord() {
                                                        PID = Guid.NewGuid().ToString(),
                                                         PRODUCT_PID = ProductNew.PID,
                                                         WORKCELL_CODE = ProductList.WORKCELL_CODE,
                                                         WORKLOC_CODE = ProductList.WORKLOC_CODE,
                                                         IN_WORKCELL_TIME = DateTime.Now,
                                                         WORK_START_TIME = DateTime.Now,
                                                         WORK_END_TIME = DateTime.Now,
                                                         PROCESS_STATE = "1",
                                                         MANUAL_PASS = "",
                                                         MODULE_CODE = string.Equals(dai.DIVBY_MOULD, "0") ? _operationServiceParam.machineInfo.WORKCELL_CODE : (string.IsNullOrWhiteSpace(lblMould.Text) ? _operationServiceParam.machineInfo.WORKCELL_CODE : lblMould.Text)
                                                    };
                                                    if (InsertProduct(ProductNew) && InsertProcessRecord(ProcessRecords))
                                                    {
                                                        txtCode.Text = BarCode;
                                                        Operation();
                                                    }
                                                }
                                            }
                                        }
                                        else
                                        {
                                            txtCode.Text = Config.BarCode;
                                            Operation();
                                        }
                                    }
                                }

                            }
                            else
                            {
                                this.lblError.Text = "通过result.WorkOrderID({result.WorkOrderID.ToString()})未查询到WorkOrder.PBOM_CODE";
                                this.lblError.ForeColor = Color.Black;
                                MessageBox.Show($"通过result.WorkOrderID({result.WorkOrderID.ToString()})未查询到WorkOrder.PBOM_CODE");
                            }


                        }
                    }

                    #endregion

                    #region DP 超声焊1的工位,低配自动输入挡流板条码
                    //DP叫总成焊接工位  不是扫高低配,而是扫多个配置. 扫一个本体码,在配置中,找到多个配置码,自动填写.
                    if (_cfgAutoInputSwitch == "true" && _cfgAutoInputLocs.Contains(_operationServiceParam.machineInfo.WORKLOC_CODE))
                    {
                        if (System.Text.RegularExpressions.Regex.IsMatch(productCode, _bentiBarCodeRegex))//扫描的是本体条码
                        {
                            List<FJC.Entity.ProductionPlan.WorkOrder> list = this.dgvPlan.DataSource as List<FJC.Entity.ProductionPlan.WorkOrder>;
                            
                            var bomCodes = GetPBOMCODEValue(result.MATERIAL_CODE);
                            List<FJC.Entity.ProductionPlan.WorkOrder> filterList = list.Where(p => bomCodes.Contains(p.MATERIAL_CODE)).ToList();
                            if (filterList.Count > 0)
                            {
                                string bomCode = filterList[0].PBOM_CODE;

                                //List<string> autoInputBarCodes = LocSwitchHelper.GetAutoInputBarCode(bomCode, _operationServiceParam.machineInfo.WORKLOC_CODE);

                                List<string> autoInputBarCodes = _agent.InvokeServiceFunction<List<string>>(B9IPCService.MaterialBomConfigBLL_GetAutoInputBarCode.ToString(), bomCode, _operationServiceParam.machineInfo.WORKLOC_CODE);
                                foreach (string autoInputBarCode in autoInputBarCodes)
                                {
                                    //LoadPreState(dai, GetMouldCode(result.MouldCode), isAutoInput, true);
                                    //自动触发txtCode_KeyDown实现
                                    txtCode.Text = autoInputBarCode;
                                    //txtCode_KeyDown(null,null);
                                    Operation();
                                }
                                
                                this.lblError.Text = "";
                                this.lblError.ForeColor = Color.Black;
                            }
                            else
                            {
                                string s = $"没有找到物料号{result.MATERIAL_CODE}对应的计划,请检查T_MD_PBOM_ITEM是否进行了配置.";
                                this.lblError.Text = s;
                                this.lblError.ForeColor = Color.Red;
                                txtCode.SelectAll();
                                txtCode.Focus();
                                WriteLog.WriteError(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "  " + s);

                            }

                        }
                    }


                    #endregion
                }
                catch (Exception ex)
                {
                    if (_showDetailError == "true")
                    {
                        WriteLog.WriteError(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "  " + ex.Message);
                        this.lblError.Text = "";
                        Reset(string.IsNullOrWhiteSpace(lblMould.Text) ? _operationServiceParam.machineInfo.WORKCELL_CODE : lblMould.Text);
                        txtCode.SelectAll();
                        txtCode.Focus();
                        MessageBox.Show(ex.Message);
                        return;
                    }
                    else
                    {
                        throw ex;
                    }
                }

                


                //闫永刚2017-10-2发送操作命令
                dai.MOULD_CODE = string.Equals(dai.DIVBY_MOULD, "1") ? result.MouldCode : "1";

                if (!result.PreInput)
                {
                    SendSignal(dai);
                }

                //刷新采集模式为自适应的采集数据
                if (daiList.Count(p => p.DA_MODE == "3") > 0)
                {
                    var cachelist = _agent.InvokeServiceFunction<List<DAICache>>(B9IPCService.DAICacheBLL_GetWorklocCache.ToString(), _operationServiceParam.machineInfo.WORKLOC_CODE);
                    foreach (var item in daiList.Where(p => p.DA_MODE == "3"))
                    {
                        var viewitem = daicache.FirstOrDefault(p => p.DACode == item.DA_CODE && (string.IsNullOrWhiteSpace(p.MouldCode) || p.MouldCode == result.MouldCode));
                        var cache = cachelist.FirstOrDefault(p => p.DA_CODE == item.DA_CODE);
                        if (viewitem != null)
                        {
                            if (cache != null && !string.IsNullOrWhiteSpace(cache.DA_VALUE))
                            {
                                viewitem.DAValue = cache.DA_VALUE;
                                viewitem.MaterialCode = cache.MATERIAL_CODE;
                                viewitem.MaterialName = cache.MATERIAL_NAME;
                                viewitem.DAResult = "通过";
                            }
                            else
                            {
                                viewitem.DAValue = "";
                                viewitem.MaterialTypeName = "";
                                viewitem.MaterialCode = "";
                                viewitem.MaterialName = "";
                                viewitem.DAResult = "";
                            }
                        }
                    }
                }

                DGView.Refresh();
                DGViewColorBind();

                //设置焦点
                this.ActiveControl = this.txtCode;
                txtCode.SelectAll();
                txtCode.Focus();

                GC.Collect();

            }
            catch (Exception ex)
            {
                WriteLog.WriteError(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "  " + ex.Message);
                this.lblError.Text = "";
                this.lblError.ForeColor = Color.Black;
                this.lblError.BackColor = SystemColors.InactiveBorder;
                Reset(string.IsNullOrWhiteSpace(lblMould.Text) ? _operationServiceParam.machineInfo.WORKCELL_CODE : lblMould.Text);
                txtCode.SelectAll();
                txtCode.Focus();
                MessageBox.Show("系统异常,请重新扫描!");
            }

        }
        #endregion 

        #region 执行返回结果中包含的动作
        /// <summary>
        /// 执行返回结果中包含的动作
        /// </summary>
        /// <param name="result"></param>
        private void DoResultActions(DAResult result)
        {
            lblError.Text = string.Format("当前工位状态:{0}", result.StateName);
            this.lblError.ForeColor = Color.Black;
            this.lblError.BackColor = SystemColors.InactiveBorder;
            lblWorkcellState.Text = result.StateName;
            foreach (var act in result.Actions)
            {
                switch (act)
                {
                    case "SUBMIT": //状态变化动作为 提交数据
                        {
                            //TODO:更细界面数据
                            BindView();
                            BindPlanView();
                            break;
                        }
                    case "SUBMIT_NOPLAN": //状态变化动作为 提交数据
                        {
                            //TODO:更细界面数据
                            BindView();
                            //BindPlanView();
                            break;
                        }
                    case "SIGNAL_START": //状态变化动作为 发送启动信号
                        {
                            //TODO:发送启动信号
                            break;
                        }
                    case "PUSHDATA": //推送提前输入数据
                        {
                            //TODO:发送信号
                            var cachelist = _agent.InvokeServiceFunction<List<DAICache>>(B9IPCService.DAICacheBLL_GetWorklocCache.ToString(), _operationServiceParam.machineInfo.WORKLOC_CODE);
                            string premouldcode = "PRE-" + result.MouldCode;
                            if (_operationServiceParam.machineInfo.ISSTATION != 2)
                            {
                                premouldcode = "PRE-" + _operationServiceParam.machineInfo.WORKCELL_CODE;
                            }

                            foreach (var daiview in daicache.Where(p=>(p.MouldCode==result.MouldCode||string.IsNullOrEmpty(p.MouldCode)||p.MouldCode==premouldcode)))
                            {
                                var cache = cachelist.FirstOrDefault(p => p.DA_CODE == daiview.DACode 
                                                                           && (string.Equals(daiview.PREINPUT, "1") 
                                                                               ? (p.MOULD_CODE == result.MouldCode 
                                                                                  && p.PREINPUT == "1") 
                                                                               : (p.MOULD_CODE == daiview.MouldCode 
                                                                                  && p.PREINPUT != "1")));
                                if (cache != null && !string.IsNullOrWhiteSpace(cache.DA_VALUE))
                                {
                                    daiview.DAValue = cache.DA_VALUE;
                                    daiview.MaterialCode = cache.MATERIAL_CODE;
                                    daiview.MaterialName = cache.MATERIAL_NAME;
                                    daiview.DAResult = "通过";
                                }
                                else
                                {
                                    daiview.DAValue = "";
                                    daiview.MaterialTypeName = "";
                                    daiview.MaterialCode = "";
                                    daiview.MaterialName = "";
                                    daiview.DAResult = "";
                                }
                            }
                            Action signalaction = new Action(() =>
                                {
                                    string sleep = result.Actions.FirstOrDefault(p => p.StartsWith("SLEEP"));
                                    if (sleep != null)
                                    {
                                        int st = 0;
                                        int.TryParse(sleep.Replace("SLEEP_", ""), out st);
                                        System.Threading.Thread.Sleep(st);
                                    }
                                    else
                                    {
                                        System.Threading.Thread.Sleep(10000);
                                    }
                                    //TODO:发送信号
                                    foreach (var daiview in daiviewSource)
                                    {
                                        if (daiview.DAResult == "通过" && !string.Equals(daiview.PREINPUT, "1"))
                                        {
                                            DAI signalDai = new DAI()
                                            {
                                                WORKCELL_CODE = _operationServiceParam.machineInfo.WORKCELL_CODE,
                                                WORKLOC_CODE = _operationServiceParam.machineInfo.WORKLOC_CODE,
                                                DA_CODE = daiview.DACode,
                                                MOULD_CODE = string.Equals(_operationServiceParam.machineInfo.WORKCELL_CODE, result.MouldCode) ? "1" : result.MouldCode,
                                                Result = EnumGeter.ORDERTYPE.OK.GetHashCode().ToString(),
                                                MATERIAL_CODE = daiview.MaterialCode
                                            };
                                            SendSignal(signalDai);
                                        }
                                    }
                                });
                            signalaction.BeginInvoke(null, null);

                            break;
                        }
                    case "PRINT_ASSY": //状态变化动作为 打印总成码
                        {
                            //TODO:清空界面数据 复位启动信号
                            //PrintAssemblyLabe(result.ProcessCode);
                            Print052QRCODE();
                            break;
                        }

                    case "PRINT_PROCESS": //状态变化动作为 打印过程码
                        {
                            //TODO:清空界面数据 复位启动信号
                            PrintProcessLabel(result.ProcessCode);
                            break;
                        }
                    case "PRINT_PLAN": //状态变化动作为 打印计划标签
                        {
                            //TODO:清空界面数据 复位启动信号
                            PrintPlanLabel(result);
                            break;
                        }
                    case "RESET": //状态变化动作为 复位
                        {
                            //TODO:清空界面数据 复位启动信号
                            //SendRecoveryOrder(result.MouldCode);
                            Reset(result.MouldCode);
                            break;
                        }
                    case "SHOWMLIST": //状态变化动作为 显示装配物料清单
                        {
                            ShowMaterialList(result.WorkOrderID);
                            break;
                        }
                    case "HIDEMLIST": //状态变化动作为 隐藏装配物料清单
                        {
                            HideMaterialList();
                            break;
                        }
                    default:
                        {
                            if (act.StartsWith("SIGNAL_"))
                            {
                                string dacode = act.Replace("SIGNAL_", "");
                                var daiview = daiviewSource.FirstOrDefault(p => p.DACode == dacode && p.DAResult == "通过" && !string.Equals(p.PREINPUT, "1"));
                                if (daiview != null)
                                {
                                    DAI signalDai = new DAI()
                                    {
                                        WORKCELL_CODE = _operationServiceParam.machineInfo.WORKCELL_CODE,
                                        WORKLOC_CODE = _operationServiceParam.machineInfo.WORKLOC_CODE,
                                        DA_CODE = daiview.DACode,
                                        MOULD_CODE = string.Equals(_operationServiceParam.machineInfo.WORKCELL_CODE, result.MouldCode) ? "1" : result.MouldCode,
                                        Result = EnumGeter.ORDERTYPE.OK.GetHashCode().ToString(),
                                        MATERIAL_CODE = daiview.MaterialCode
                                    };
                                    SendSignal(signalDai);
                                }
                            }
                            break;
                        }
                }
            }
        }

        private void HideMaterialList()
        {
            dgvMlist.AutoGenerateColumns = false;
            dgvMlist.DataSource = new List<QMAPP.MD.Entity.PbomItem>();
            plInfo.Visible = false;
        }
        private void ShowMaterialList(string OrderNo)
        {
            var mlist = _agent.InvokeServiceFunction<List<QMAPP.MD.Entity.PbomItem>>("PbomBLL_GetWorkingBom", _operationServiceParam.machineInfo.WORKLOC_CODE, OrderNo);
            
            dgvMlist.AutoGenerateColumns = false;
            dgvMlist.DataSource = mlist;
            dgvMlist.ClearSelection();
            if (mlist != null && mlist.Count > 0)
            {
                gbMlist.Visible = plInfo.Visible = true;
                try
                {
                    foreach (DataGridViewRow row in DGView.Rows)
                    {
                        FJC.Entity.View.DAIFormView dv = row.DataBoundItem as FJC.Entity.View.DAIFormView;
                        if (dv != null && dv.StateCode.ToUpper() == "ASSY")
                        {
                            if (!mlist.Exists(p => (p.MATERIAL_TYPE_CODE + "").StartsWith(dv.MaterialType)))
                            {
                                row.Visible = false;
                                continue;
                            }
                            row.Visible = true;
                        }
                    }
                }
                catch
                {
 
                }
            }
            else
            {
                gbMlist.Visible = plInfo.Visible = false;
            }
            plInfo.AutoSize = !gbMlist.Visible;
        }

        #endregion 

        #region 发送信号
        /// <summary>
        /// 发送信号
        /// </summary>
        /// <param name="dai"></param>  
        private void SendSignal(DAI dai)
        {
            if (proy == null)
                return;
            string paraStr = JsonConvertHelper.GetSerializes(dai);
            if (proy.State == System.ServiceModel.CommunicationState.Faulted)
            {
                System.ServiceModel.InstanceContext site = new System.ServiceModel.InstanceContext(this);
                proy = new ServiceOpc.OpcServiceClient(site);
            }
            if (proy.State == System.ServiceModel.CommunicationState.Created || proy.State == System.ServiceModel.CommunicationState.Opened)
            {
                var task = new System.Threading.Tasks.Task(() =>
                {
                    //闫永刚2017-10-2发送操作命令
                    proy.SendOperateOrder(paraStr);
                });
                task.Start();
            }
        }
        #endregion 

        #region 发送操作命令
        /// <summary>
        /// 发送操作命令
        /// </summary>
        private void SendRecoveryOrder(string mouldcode)
        {
            DAI dai = daiList[0];

            DAI recoveryDai = new DAI() { WORKCELL_CODE = dai.WORKCELL_CODE, WORKLOC_CODE = dai.WORKLOC_CODE, DA_CODE = "RECOVERY", MOULD_CODE = string.IsNullOrWhiteSpace(mouldcode) ? "1" : mouldcode, Result = "0" };

            if (proy == null)
            {
                return;
            }
            if (proy.State == System.ServiceModel.CommunicationState.Faulted)
            {
                System.ServiceModel.InstanceContext site = new System.ServiceModel.InstanceContext(this);
                proy = new ServiceOpc.OpcServiceClient(site);
            }
            if (proy.State == System.ServiceModel.CommunicationState.Created || proy.State == System.ServiceModel.CommunicationState.Opened)
            {
                //闫永刚2017-10-2发送操作命令

                string paraStr = JsonConvertHelper.GetSerializes(recoveryDai);
                proy.SendOperateOrder(paraStr);
            }
        }
        #endregion 

        #region 根据输入条码定位采集点
        /// <summary>
        /// 根据输入条码定位采集点
        /// </summary>
        /// <param name="productCode"></param>
        private DAI LocateDAI(string productCode)
        {
            foreach (var rule in _barcodeRules)
            {
                if (System.Text.RegularExpressions.Regex.IsMatch(productCode, rule.REGEX))
                {
                    var dai = daiList.FirstOrDefault(p => (p.MATERIAL_TYPE == rule.MATERIAL_TYPE || p.MATERIAL_TYPE == rule.PARENT_TYPE) && p.DATA_TYPE == rule.DATA_TYPE);
                    if (dai != null)
                    {
                        var ndai = (DAI)dai.Clone();
                        ndai.MATERIAL_CODE = rule.MATERIAL_CODE;
                        ndai.MATERIAL_TYPE = rule.MATERIAL_TYPE;
                        return ndai;
                    }
                    
                }
            }
            //条码未匹配到任何正则
            Product product = _agent.InvokeServiceFunction<Product>(B9BasicService.ProductBLL_GetOrginProduct.ToString(), productCode);
            if (product != null)
            {
                var dai = daiList.FirstOrDefault(p => p.MATERIAL_TYPE == product.MATERIAL_TYPE);
                if (dai != null)
                {
                    var ndai = (DAI)dai.Clone();
                    ndai.MATERIAL_CODE = product.MATERIAL_CODE;
                    return ndai;
                }
                
            }
            
            return null;
        }
        #endregion 

        #region 发送指令或者接受完成指令刷新列表
        /// <summary>
        /// 发送指令或者接受完成指令刷新列表
        /// </summary>
        public void BindView()
        {
            #region 刷新生产零件的列表
            this.DGViewProList.DataSource = new List<MainOperation>();
            //加载当前工序,当前设备的最后几条加工记录
            DataPage dataPage = new DataPage();
            dataPage.PageSize = int.Parse(cbListRowcount.Text);
            dataPage.PageIndex = 1;
            dataPage.SortExpression = " ROWVALUE ASC";
            MainOperation operationSearchModel = new MainOperation();
            //operationSearchModel.CREATEUSER = ClientContext.LoginInfo.UserID;
            operationSearchModel.MACHINECODDE = _operationServiceParam.machineInfo.MACHINECODDE;
            //operationSearchModel.PROCESSTYPE = _operationServiceParam.processSet.PROCESSTYPE;
            operationSearchModel.CURRENTPROCESS = _operationServiceParam.machineInfo.WORKLOC_CODE;

            //if (_operationServiceParam.processSet.PROCESSTYPE != EnumGeter.ProcessType.maojie.GetHashCode().ToString()
            //    && (this.comProductType.SelectedValue.ToString() != EnumGeter.ProductType.fengdao.GetHashCode().ToString()
            //    || this.comProductType.SelectedValue.ToString() != EnumGeter.ProductType.HUDfengdao.GetHashCode().ToString()
            //    )
            //    )
            //{
            //    operationSearchModel.PRODUCTTYPE = this.comProductType.SelectedValue.ToString();
            //}

            try
            {
                #region 服务查询
                dataPage = _agent.InvokeServiceFunction<DataPage>(B9BasicService.MainOperationBLL_GetOperationListNew.ToString(), operationSearchModel, dataPage);
                List<MainOperation> listOperetions = JsonConvertHelper.GetDeserialize<List<MainOperation>>(dataPage.Result.ToString());
                #endregion
                this.DGViewProList.DataSource = listOperetions;
                DGViewProList.ClearSelection();

            }
            catch (Exception ex)
            {
                throw ex;
            }

            #endregion
        }
        #endregion

        #region 发送指令或者接受完成指令刷新列表
        /// <summary>
        /// 发送指令或者接受完成指令刷新列表
        /// </summary>
        public void BindPlanView()
        {
            #region 刷新生产计划
            dgvPlan.AutoGenerateColumns = false;
            this.dgvPlan.DataSource = new List<FJC.Entity.ProductionPlan.WorkOrder>();


            try
            {
                DataPage dataPage = new DataPage();
                dataPage.PageSize = int.Parse(cbListRowcount.Text);
                dataPage.PageIndex = 1;
                dataPage.SortExpression = " ROWVALUE ASC";
                string workcellcode = daiList.Select(p => p.WORKCELL_CODE).FirstOrDefault() + "";
                #region 服务查询
                var orderlist = _agent.InvokeServiceFunction<List<FJC.Entity.ProductionPlan.WorkOrder>>(B9IPCService.WorkOrderBLL_GetOrderInCell.ToString(), workcellcode,cbPlanFilter.SelectedIndex, dataPage);
                #endregion
                this.dgvPlan.DataSource = orderlist;
                //DGViewProList.ClearSelection();

                var plancount = _agent.InvokeServiceFunction<int>(B9IPCService.WorkOrderBLL_GetOrderCountInCell.ToString(), workcellcode, "");
                lblPlanCount.Text = plancount.ToString();

                var dayplancount = _agent.InvokeServiceFunction<int>(B9IPCService.WorkOrderBLL_GetDayPlanCount.ToString(), _operationServiceParam.machineInfo.WORKCENTER_CODE);
                lblDayPlanCount.Text = dayplancount.ToString();

                var shiftplancount = _agent.InvokeServiceFunction<int>(B9IPCService.WorkOrderBLL_GetOrderCountInCell.ToString(), workcellcode, _operationServiceParam.produceShift.PRODUCESHIFTTCODE);
                lblShiftPlanCount.Text = shiftplancount.ToString();

                if (!string.IsNullOrWhiteSpace(_operationServiceParam.produceShift.PID))
                {
                    var shift = _operationServiceParam.produceShift;
                    var condition = new FJC.Entity.QT.ProcessRecord();
                    condition.WORKCELL_CODE = workcellcode;
                    condition.WORK_START_TIME = DateTime.Now.Date.Add(shift.PSSTART - shift.PSSTART.Date);
                    condition.WORK_END_TIME = DateTime.Now.Date.Add(shift.PSEND - shift.PSEND.Date);
                    if (condition.WORK_END_TIME < condition.WORK_START_TIME)
                    {
                        condition.WORK_END_TIME = condition.WORK_END_TIME.AddDays(1);
                    }
                    var shiftcompletecount = _agent.InvokeServiceFunction<int>(B9IPCService.ProcessRecordBLL_GetCount.ToString(), condition);
                    lblShiftCompleteCount.Text = shiftcompletecount.ToString();
                }
                else
                {
                    lblShiftCompleteCount.Text = "";
                }

            }
            catch (Exception ex)
            {
                WriteLog.WriteError(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "  " + ex.Message);
            }
            finally
            {
                timecounter = 0;
            }
            #endregion
        }
        #endregion

        #region 绑定先决条件以及绑定加工记录
        /// <summary>
        /// 绑定先决条件以及绑定加工记录
        /// </summary>
        private void BindAll()
        {
            //设置当前的工序
            //_operationServiceParam.processSet = this.comProductType.SelectedItem as ProcessSet;
            if (_operationServiceParam.machineInfo != null)//_operationServiceParam.processSet != null &&
            {
                this.DGView.Refresh();
                DGViewColorBind();

                BindView();
                BindPlanView();
            }

        }
        #endregion 

        #region 窗口数据重置
        /// <summary>
        /// 窗口数据重置
        /// </summary>
        private void Reset(string mouldcode)
        {
            foreach (var v in daicache.Where(p=>string.Equals(p.MouldCode,mouldcode)))
            {
                if (!string.IsNullOrWhiteSpace(v.StateCode))
                {
                    v.MaterialName = "";
                    v.MaterialCode = "";
                    v.DAValue = "";
                    v.DAResult = "";
                }
            }
            _operationServiceParam = new OperationServiceParam();
            _operationServiceParam.machineInfo = this.comMachine.SelectedItem as MachineInfo;
            _operationServiceParam.produceShift = ClientContext.produceShift;
            BindAll();
        }
        #endregion 

        #region 刷新数据采集列表
        /// <summary>
        /// 刷新数据采集列表
        /// </summary>
        private void DGViewColorBind()
        {
            int panelheight = 0;
            DGView.ClearSelection();
            if (DGView.Rows.Count > 0)
            {
                string mould = "";
                for (int i = 0; i < DGView.Rows.Count; i++)
                {

                    DataGridViewRow dgr = DGView.Rows[i];
                    panelheight += dgr.Height;
                    if (!string.Equals(dgr.Cells[dgcMouldCode.Name].Value, mould))
                    {
                        if (i > 0)
                        {
                            DataGridViewRow dgru = DGView.Rows[i - 1];
                            dgru.DividerHeight = 4;
                            dgru.Height = dgr.Height + 4;
                            panelheight += 4;
                        }

                        mould = dgr.Cells[dgcMouldCode.Name].Value + "";
                    }
                    if (dgr.Cells["daresult"].Value != null && dgr.Cells["daresult"].Value.ToString() == "通过")
                    {
                        dgr.DefaultCellStyle.BackColor = Color.Green;
                    }
                    else if (dgr.Cells["daresult"].Value != null && dgr.Cells["daresult"].Value.ToString() == "未通过")
                    {
                        dgr.DefaultCellStyle.BackColor = Color.Red;
                    }
                    else
                    {
                        dgr.DefaultCellStyle.BackColor = SystemColors.Window;
                    }
                }
                plDAI.Height = 27 + panelheight;
            }

        }
        #endregion

        #region 标签打印

        #region  新版总工标签打印

        GridppReport Report = null;
        public string planMATERIAL_CODE = "";
        public string processMainCode = "";

        /// <summary>
        /// 总成标签打印
        /// </summary>
        /// <param name="processcode"></param>
        private void PrintAssemblyLabe(string processcode)
        {
            tsbPrint.Visible = true;
            /////////////////////
            string selectKey = processcode;
            Main main = _agent.InvokeServiceFunction<Main>(B9IPCService.MainBLL_GetByCondition.ToString(), new Main() { EPIDERMISCODE = selectKey });
            if (main == null)
            {
                MessageBox.Show("获取总成条码异常!");
                return;
            }
            MaterialCodeInit mcinit = _agent.InvokeServiceFunction<MaterialCodeInit>(B9IPCService.MainBLL_GetMaterialSetByCondition.ToString(), new MaterialCodeInit() { MATERIAL_CODE = main.MATERIAL_CODE, WORKCELL_CODE = "ASSEMBLY" });
            if (mcinit == null)
            {
                MessageBox.Show("获取总成条码异常!");
                return;
            }

            #region 总成装配打印
            
            rePrintBzd.barcode = main.MAINCODE;
            rePrintBzd.MATERIAL_CODE = main.MATERIAL_CODE;
            rePrintBzd.color = mcinit.COLOR;

            try
            {
                Report = new GridppReport();

                string reportPath = System.Configuration.ConfigurationManager.AppSettings["AssemblyPrintingTemplatePath"].ToString();

                //数据填充
                Report.FetchRecord += new _IGridppReportEvents_FetchRecordEventHandler(ReadFetchRecordBox2);

                Report.LoadFromFile(reportPath);

                //rep.Printer.PrinterName = "默认打印机";//调取不同的打印机

                Report.Print(false);
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {

                Report = new GridppReport();
            }
            
        }


        //新增
        private BZD rePrintBzd = new BZD();

        private void ReadFetchRecordBox2()
        {
            try
            {
                string e052BarCode = rePrintBzd.barcode;

                Report.DetailGrid.Recordset.Append();

                Report.FieldByName("BarCode").Value = string.Format("*{0}*", e052BarCode);//总装条码

                Report.FieldByName("FullBarCode").Value = e052BarCode;//总装条码
                
                Report.FieldByName("PartCode").Value = rePrintBzd.color;//颜色

                Report.FieldByName("PartDesc").Value = rePrintBzd.MATERIAL_CODE; //物料号

                Report.DetailGrid.Recordset.Post();
            }
            catch (Exception err)
            {
                throw new Exception(err.Message);
            }
        }

        private void ReadFetchRecordBo3()
        {
            try
            {
                string e052BarCode = rePrintBzd.barcode;

                Report.DetailGrid.Recordset.Append();

                Report.FieldByName("BarCode").Value = string.Format("*{0}*", e052BarCode);//总装条码

                Report.FieldByName("FullBarCode").Value = e052BarCode;//总装条码

                Report.FieldByName("PartCode").Value = rePrintBzd.color;//颜色

                Report.FieldByName("PartDesc").Value = rePrintBzd.MATERIAL_CODE; //物料号

                Report.DetailGrid.Recordset.Post();
            }
            catch (Exception err)
            {
                throw new Exception(err.Message);
            }
        }

        /// <summary>
        /// 打印052标签
        /// </summary>
        /// <param name="processcode"></param>
        public void Print052QRCODE()
        {
            try
            {
                Report = new GridppReport();

                //数据填充
                //Report.FetchRecord += new _IGridppReportEvents_FetchRecordEventHandler(ReadFetchRecordBox);


                string reportPath = System.Configuration.ConfigurationManager.AppSettings["AssemblyPrintingTemplatePath"].ToString();

                //数据填充
                Report.FetchRecord += new _IGridppReportEvents_FetchRecordEventHandler(ReadFetchRecordBox);

                Report.LoadFromFile(reportPath);

                //rep.Printer.PrinterName = "默认打印机";//调取不同的打印机

                Report.Print(false);
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {

                Report = new GridppReport();
            }

            #endregion


        }


        public class BZD
        {
            public string barcode;
            public string color;
            public string MATERIAL_CODE;
            public string count;
        };
        /// <summary>
        /// 获取BZD码
        /// </summary>
        /// <returns></returns>
        private BZD getBZDCode()
        {
            BZD bzd = new BZD();
            List<string> list = new List<string>();
            List<string> paramList = new List<string>();

            //张松男 20210207   总成工位打印052  缺少物料号  重新查找填充  start
            if (string.IsNullOrEmpty(planMATERIAL_CODE))
            {
                var MaterialCodes = "";
                var dataSrouce = _agent.InvokeServiceFunction<DataTable>(B9IPCService.BZDConfigBLL_GetMaterialCode.ToString(), processMainCode);
                foreach (DataRow dataRow in dataSrouce.Rows)
                {
                    MaterialCodes = dataRow["MATERIAL_CODE"].ToString();
                }
                if (!string.IsNullOrEmpty(MaterialCodes))
                    planMATERIAL_CODE = MaterialCodes;
                else
                    throw new Exception("创建BZD码失败!缺少planMATERIAL_CODE");
            }
            //张松男 20210207   总成工位打印052  缺少物料号  重新查找填充  end


            paramList.Add(planMATERIAL_CODE);
            paramList.Add(processMainCode);

            try
            {
                //读取BZDCONFIG配置列表
                list = _agent.InvokeServiceFunction<List<string>>(
                    B9IPCService.BZDRecorderBLL_CreateBZDCode.ToString(), paramList);
                if (list != null)
                {
                    //将返回值赋值给bzd对象
                    bzd.barcode = list[0];
                    bzd.color = list[1];
                    bzd.MATERIAL_CODE = list[2];
                    bzd.count = list[3];
                    if (bzd.count == "0")
                    {
                        planMATERIAL_CODE = null;
                        processMainCode = null;
                        throw new Exception("创建BZD码失败!缺少list[3]");
                    }
                    planMATERIAL_CODE = null;
                    processMainCode = null;
                }
                else
                {
                    planMATERIAL_CODE = null;
                    processMainCode = null;
                    throw new Exception("创建BZD码异常!list=null");
                }
            }
            catch (Exception e)
            {
                planMATERIAL_CODE = null;
                processMainCode = null;
                MessageBox.Show(e.Message);
                throw;
            }

            return bzd;
        }

        /// <summary>
        /// 填充数据
        /// </summary>
        private void ReadFetchRecordBox()
        {
            try
            {
                BZD bzd = getBZDCode();
                string e052BarCode = bzd.barcode;

                Report.DetailGrid.Recordset.Append();

                Report.FieldByName("BarCode").Value = string.Format("*{0}*", e052BarCode);//总装条码

                Report.FieldByName("FullBarCode").Value = e052BarCode;//总装条码
                
                Report.FieldByName("PartCode").Value = bzd.color;//颜色

                Report.FieldByName("PartDesc").Value = bzd.MATERIAL_CODE; //物料号

                Report.DetailGrid.Recordset.Post();
            }
            catch (Exception err)
            {
                throw new Exception(err.Message);
            }
        }
        
        #endregion

        #region 总成标签打印
        /// <summary>
        /// 总成标签打印
        /// </summary>
        /// <param name="processcode"></param>
        private void PrintAssemblyLabel(string processcode)
        {
            tsbPrint.Visible = true;
            /////////////////////
            string selectKey = processcode;
            Main main = _agent.InvokeServiceFunction<Main>(B9IPCService.MainBLL_GetByCondition.ToString(), new Main() { EPIDERMISCODE = selectKey });
            if (main == null)
            {
                MessageBox.Show("获取总成条码异常!");
                return;
            }
            MaterialCodeInit mcinit = _agent.InvokeServiceFunction<MaterialCodeInit>(B9IPCService.MainBLL_GetMaterialSetByCondition.ToString(), new MaterialCodeInit() { MATERIAL_CODE = main.MATERIAL_CODE, WORKCELL_CODE = "LS_ASSEMBLE_VW371" });
            if (mcinit == null)
            {
                MessageBox.Show("获取总成条码异常!");
                return;
            }
            #region 总成装配打印
            //string xmlPath = System.Configuration.ConfigurationSettings.AppSettings["XmlName"].ToString(); ;
            //BarcodeLib.BarCodeGenerate g = new BarcodeLib.BarCodeGenerate( xmlPath);
            //bool b = g.PrintBarCode(_operationServiceParam.main.MAINCODE);
            QM.Assist.LabelInfo ll = new QM.Assist.LabelInfo();
            //ll.BarCode = main.MAINCODE + "," + main.MATERIAL_CODE + ",";

            //************20210413 DQZhang BC316 VAN*************************************
            if (cBoxVAN.Checked)
            {
                ll.BarCode = main.MAINCODE + "," + "5CG.857.003.A VAN" + ",";
            }
            else 
            {
                ll.BarCode = main.MAINCODE + "," + main.MATERIAL_CODE + ",";
            }
            //***************************************************************************

            ll.BarCode += mcinit.HB;
            //if (selectKey.ToUpper().Substring(12, 1) == "H")
            //{
            //    ll.BarCode += "高";
            //}
            //else
            //{
            //    ll.BarCode += "低";
            //}
            ll.BarCode += mcinit.COLOR;
            //if (selectKey.Substring(13, 1) == "1")
            //{
            //    ll.BarCode += "黑";
            //}
            //else if (selectKey.Substring(13, 1) == "2")
            //{
            //    ll.BarCode += "灰";
            //}
            //else
            //{
            //    ll.BarCode += "米";
            //}

            ll.BarCode += " ";// +mcinit.PRODUCT_TYPES;
            //ll.BarCode += "\r\n" + ll.BarCode;//总成标签一式两份

            QM.Assist.PrintUtil.LabelList2.Add(ll);
            QM.Assist.PrintUtil pu = new QM.Assist.PrintUtil();
            pu.PrintLabel2(System.Configuration.ConfigurationManager.AppSettings["proPath"].ToString(),
                System.Configuration.ConfigurationManager.AppSettings["ZCtemPath"].ToString(),
                System.Configuration.ConfigurationManager.AppSettings["ZCdataPath"].ToString());
            ///总成标签一式两份
            //pu.PrintLabel2(System.Configuration.ConfigurationManager.AppSettings["proPath"].ToString
            //    (), System.Configuration.ConfigurationManager.AppSettings["ZCtemPath"].ToString
            //    (), System.Configuration.ConfigurationManager.AppSettings["ZCdataPath"].ToString
            //    ());

            #endregion
        }
        #endregion 

        #region 过程标签打印
        /// <summary>
        /// 过程标签打印
        /// </summary>
        /// <param name="processcode"></param>
        private void PrintProcessLabel(string processcode)
        {
            /////////////////////
            string selectKey = processcode;
            Product product = _agent.InvokeServiceFunction<Product>(B9IPCService.ProductBLL_Get.ToString(), new Product() { PRODUCTCODE = selectKey });
            if (product == null)
            {
                MessageBox.Show("获取产品信息异常!");
                return;
            }
            
            #region 过程标签打印
            
            QM.Assist.LabelInfo ll = new QM.Assist.LabelInfo();
            ll.BarCode = product.PRODUCTCODE + "," + product.MATERIAL_CODE + ",";

            ll.BarCode += product.MATERIAL_CODE + "," + product.MATERIAL_CODE + "," + product.MATERIAL_TYPE;

            QM.Assist.PrintUtil.LabelList2.Add(ll);
            QM.Assist.PrintUtil pu = new QM.Assist.PrintUtil();
            pu.PrintLabel2(System.Configuration.ConfigurationManager.AppSettings["proPath"].ToString
                (), System.Configuration.ConfigurationManager.AppSettings["ProcessCodeTMPPath"].ToString
                (), System.Configuration.ConfigurationManager.AppSettings["ProcessCodeDATPath"].ToString
                ());

            #endregion
        }
        #endregion 

        #region 计划标签打印
        /// <summary>
        /// 计划标签打印
        /// </summary>
        /// <param name="processcode"></param>
        private void PrintPlanLabel(DAResult result)
        {
            var labeldata = _agent.InvokeServiceFunction<FJC.Entity.View.PlanLabel>(B9IPCService.WorkOrderBLL_GetPlanLabel.ToString(), result.WorkOrderID);
            labeldata.SN = result.ProcessCode;

            #region 计划标签打印
            //string xmlPath = System.Configuration.ConfigurationSettings.AppSettings["XmlName"].ToString(); ;
            //BarcodeLib.BarCodeGenerate g = new BarcodeLib.BarCodeGenerate( xmlPath);
            //bool b = g.PrintBarCode(_operationServiceParam.main.MAINCODE);
            QM.Assist.LabelInfo ll = new QM.Assist.LabelInfo();


            //planno,plantype,seq,bom,vin,kin,sn,pn,prodname,plandate,project,hbtype,color
            ll.BarCode = string.Format("'{0},'{1},'{2},'{3},'{4},'{5},'{6},'{7},'{8},'{9},'{10},'{11},'{12}",
                                        labeldata.PlanNo,//计划号
                                        labeldata.PlanType,//计划类型(0:FIS,1:STOCK,2:INSERT)
                                        labeldata.SEQ,//顺序号
                                        labeldata.BOM,//bom号
                                        labeldata.VIN,//底盘号
                                        labeldata.KIN,//车身号
                                        labeldata.SN,//序号
                                        labeldata.PN,//总成物料号
                                        labeldata.ProdName,//总成物料名称
                                        labeldata.PlanDate,//计划日期
                                        labeldata.ProjectCode,//项目编号
                                        labeldata.HBType,//车型配置
                                        labeldata.Color//颜色
                                        );



            QM.Assist.PrintUtil.LabelList2.Add(ll);
            QM.Assist.PrintUtil pu = new QM.Assist.PrintUtil();
            pu.PrintLabel2(System.Configuration.ConfigurationManager.AppSettings["proPath"].ToString
                (), System.Configuration.ConfigurationManager.AppSettings["PlanLabelTMPPath"].ToString
                (), System.Configuration.ConfigurationManager.AppSettings["PlanLabelDATPath"].ToString
                ());

            #endregion
        }
        #endregion

        #endregion 

        #region 设备下拉改变事件
        /// <summary>
        /// 设备下拉改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comMachine_SelectionChangeCommitted(object sender, EventArgs e)
        {
            Init();
        }
        #endregion 

        #region 重新发发送操作指令
        /// <summary>
        /// 重新发发送操作指令
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void sendOrderButton_Click(object sender, EventArgs e)
        {
            if (this.DGViewProList.SelectedRows.Count == 0)
            {
                MessageBox.Show("请选择要重新发送操作指令的加工信息!");
                return;
            }


            if (MessageBox.Show("确定重新发送操作指令?", "提示", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
            {
                return;
            }

            //判断是否已加工完成
            if (!this.DGViewProList.SelectedRows[0].Cells["OPERATESTATE"].Value.ToString().Equals(EnumGeter.OPERATESTATE.OPERATING.GetHashCode().ToString()))
            {
                MessageBox.Show("只有加工中的零件可以重新发送操作指令!");
                return;
            }

            string molderNumber = this.DGViewProList.SelectedRows[0].Cells["MOLDNUMBER"].Value.ToString();


            #region 发送指令

            if (proy.State == System.ServiceModel.CommunicationState.Faulted)
            {
                System.ServiceModel.InstanceContext site = new System.ServiceModel.InstanceContext(this);
                proy = new ServiceOpc.OpcServiceClient(site);
            }
            if (proy.State == System.ServiceModel.CommunicationState.Created || proy.State == System.ServiceModel.CommunicationState.Opened)
            {
                string moldnumber = _operationServiceParam.machineInfo.MOLDNUMBER;
                try
                {

                    _operationServiceParam.machineInfo.MOLDNUMBER = molderNumber;
                    DataResult<string> reMsg = _agent.InvokeServiceFunction<DataResult<string>>(B9BasicService.MainOperationBLL_GetSendOrder.ToString(), _operationServiceParam.machineInfo, true);
                    if (!string.IsNullOrEmpty(reMsg.Result) && proy != null && (proy.State == System.ServiceModel.CommunicationState.Created || proy.State == System.ServiceModel.CommunicationState.Opened))
                    {
                        proy.SendOperateOrder(reMsg.Result);
                        this.lblError.Text = "发送指令成功!";
                        this.lblError.ForeColor = Color.Green;
                        this.lblError.BackColor = SystemColors.InactiveBorder;
                        _operationServiceParam.machineInfo.MOLDNUMBER = moldnumber;
                    }
                }
                catch (Exception ex)
                {
                    this.lblError.Text += "发送指令失败!";
                    this.lblError.ForeColor = Color.White;
                    this.lblError.BackColor = Color.Red;
                    _operationServiceParam.machineInfo.MOLDNUMBER = moldnumber;
                }
            }

            #endregion

        }
        #endregion 

        #region 锁定解锁
        /// <summary>
        /// 锁定解锁
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lblLock_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {

            if (this.lblLock.Tag.ToString().Equals("0"))
            {
                LockType(false);
            }
            else
            {
                LockType(true);
            }
        }
        #endregion 

        #region 设备和类别锁定
        /// <summary>
        /// 设备和类别锁定
        /// </summary>
        /// <param name="lockFlag"></param>
        private void LockType(bool lockFlag)
        {
            this.comMachine.Enabled = lockFlag;
            //this.comProductType.Enabled = lockFlag;
            if (lockFlag)
            {

                this.lblLock.Text = "锁定工位";
                this.lblLock.Tag = "0";
            }
            else
            {
                string locationfile = System.Configuration.ConfigurationManager.AppSettings["loactionfile"];
                System.IO.File.WriteAllText(locationfile, this.comMachine.SelectedValue.ToString());
                this.lblLock.Text = "解锁工位";
                this.lblLock.Tag = "1";
            }

        }
        #endregion 

        #region 回车事件
        /// <summary>
        /// 回车事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtCode_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.KeyCode == Keys.Enter)//如果输入的是回车键
            {
                WriteLog.Write(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "      " + txtCode.Text.Trim().ToUpper());
                Operation(); ;//触发button事件
            }

        }

        /// <summary>
        /// 回车事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OperationForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)//如果输入的是回车键  
            {
                this.btnAdd_Click(sender, e);//触发button事件  
            }
        }
        
        #endregion

        #region OPC推送消息
        /// <summary>
        /// OPC推送消息
        /// </summary>
        /// <param name="messageType">消息类型 3:模架号变化,</param>
        /// <param name="message">消息内容</param>
        public void ReturnResult(string messageType, string message)
        {
            this.Invoke((EventHandler)(delegate
            {
                try
                {
                    if (messageType == "3") //模架号
                    {
                        var mould = mouldList.FirstOrDefault(p => string.Equals(p.MODELSTATION, message));
                        if (mould != null)
                        {
                            SwitchMould(mould.MODELCODE);
                        }
                    }
                    else if (messageType == "4") //模具号
                    {
                        var str_messages = message.Split(':');
                        if (!(string.Equals(str_messages[str_messages.Length - 1], "0") || string.Equals(str_messages[str_messages.Length - 1].ToUpper(), "FALSE")))
                        {
                            DAInput(message, "MN");
                        }
                        return;
                    }
                    else if (messageType == "5") //模具号
                    {
                        var str_messages = message.Split(':');
                        if (AttachInfo.ContainsKey(str_messages[0]))
                        {
                            AttachInfo[str_messages[0]] = str_messages[1];
                        }
                        else
                        {
                            AttachInfo.Add(str_messages[0], str_messages[1]);
                        }
                        return;
                    }
                    else if (string.Equals(messageType, "HeartBeat"))
                    {
                        opcheartbeatwaithandel.Set();
                    }
                    else
                    {
                        DAInput(message, "PARM");
                        return;
                    }

                }
                catch (Exception ex)
                {
                    WriteLog.WriteError(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "  " + ex.Message);
                    this.lblError.Text = "";
                    this.lblError.ForeColor = Color.Black;
                    this.lblError.BackColor = SystemColors.InactiveBorder;
                    Reset(string.IsNullOrWhiteSpace(lblMould.Text) ? _operationServiceParam.machineInfo.WORKCELL_CODE : lblMould.Text);
                    txtCode.SelectAll();
                    txtCode.Focus();
                    MessageBox.Show("系统异常,请重新扫描!");
                }
            }));
        }

        private void DAInput(string message,string datype)
        {
            var mould = mouldList.FirstOrDefault(p => string.Equals(p.MODELCODE, message.Split(':')[0]));

            var dai = daiList.FirstOrDefault(p => p.DATA_TYPE == datype);
            var daiview = daicache.FirstOrDefault(p => p.DACode == dai.DA_CODE && (mould == null || p.MouldCode == mould.MODELCODE));
            //daiviews.FirstOrDefault(p => p.DACode == dai.DA_CODE);
            daiview.DAValue = message;
            var result = _agent.InvokeServiceFunction<DAResult>(B9IPCService.DAI_Input.ToString()
                                                               , new DAArgs
                                                               {
                                                                   WorkCellCode = dai.WORKCELL_CODE,
                                                                   WorkLocCode = dai.WORKLOC_CODE,
                                                                   DACode = dai.DA_CODE,
                                                                   DAValue = message,
                                                                   MaterialCode = dai.MATERIAL_CODE,
                                                                   MachineCode = _operationServiceParam.machineInfo.MACHINECODDE,
                                                                   MachineName = _operationServiceParam.machineInfo.MACHINENAME,
                                                                   IsControl = _operationServiceParam.machineInfo.ISCONTROL,
                                                                   MouldCode = mould == null ? _operationServiceParam.machineInfo.WORKCELL_CODE : mould.MODELCODE,
                                                                   AttachData=AttachInfo
                                                               });

            if (!result.Success) //如果采集数据输入失败
            {
                daiview.DAResult = "未通过";
                DGView.Refresh();
                DGViewColorBind();
                this.lblError.Text = result.Message;
                this.lblError.ForeColor = Color.White;
                this.lblError.BackColor = Color.Red;
                txtCode.SelectAll();
                txtCode.Focus();
                return;
            }
            else
            {
                daiview.DAValue = result.AnalyzedValue;
                daiview.DAResult = "通过";
                daiview.MaterialCode = result.MATERIAL_CODE;
                daiview.MaterialName = result.MATERIAL_NAME;
                DGView.Refresh();
                DGViewColorBind();
                //TODO:更新界面数据
            }
            DoResultActions(result);

            if (this.lblLock.Tag.ToString().Equals("0"))
            {
                LockType(false);
            }
            DGView.Refresh();
            DGViewColorBind();

            this.txtCode.Text = "";
            //设置焦点
            this.ActiveControl = this.txtCode;
            this.txtCode.Focus();

            GC.Collect();
        }
        #endregion 

        #region 重新连接服务器
        /// <summary>
        /// 重新连接服务器
        /// </summary>
        private void ReContact()
        {
            //设置与设备双工通信
            if (_operationServiceParam.machineInfo.ISCONTROL.Equals("2") || _operationServiceParam.machineInfo.ISCONTROL.Equals("3"))
            {
                System.ServiceModel.InstanceContext site = new System.ServiceModel.InstanceContext(this);
                proy = new ServiceOpc.OpcServiceClient(site);
                if (proy.State == System.ServiceModel.CommunicationState.Created || proy.State == System.ServiceModel.CommunicationState.Opened)
                {
                    try
                    {
                        this.lblError.BackColor = SystemColors.InactiveBorder;
                        this.lblError.ForeColor = Color.Black;
                        this.lblError.Text = "正在连接中稍后!";
                        var mouldno = proy.Register(_operationServiceParam.machineInfo.MACHINECODDE);
                        this.lblError.Text = "服务器连接成功!";
                        this.lblError.ForeColor = Color.Green;
                        
                        if (mouldList.Count <= 2)
                        {
                            SwitchMould("");
                        }
                        else
                        {
                            if (mouldno > 0)
                            {
                                var mould = mouldList.FirstOrDefault(p => string.Equals(p.MODELSTATION, mouldno.ToString()));
                                if (mould != null)
                                {
                                    SwitchMould(mould.MODELCODE);
                                }

                            }
                            else
                            {
                                SwitchMould("");
                            }
                            //cbMould_SelectedIndexChanged(this, EventArgs.Empty);
                        }
                    }
                    catch (Exception)
                    {
                        this.lblError.Text = "连接服务失败!";
                        this.lblError.ForeColor = Color.White;
                        this.lblError.BackColor = Color.Red;
                    }
                }
            }
        }
        #endregion 

        #region 工具栏Click

        #region 重接服务器
        /// <summary>
        /// 重接服务器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsbConnect_Click(object sender, EventArgs e)
        {
            ReContact();
        }
        /// <summary>
        /// 重接服务器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsbRecovery_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(lblMould.Text) && cbMould.Items.Count > 1)
            {
                tsbRecovery.DropDownItems.Clear();
                foreach (MachineInfoModels mould in cbMould.Items)
                {
                    var dditem = tsbRecovery.DropDownItems.Add(mould.MODELNAME);
                    dditem.Tag = mould.MODELCODE;
                    dditem.Padding = new Padding(0, 10, 0, 0);
                }
                tsbRecovery.ShowDropDown();
                return;
            }
            string mouldcode = string.IsNullOrWhiteSpace(lblMould.Text) ? (cbMould.Items.Count < 2 ? _operationServiceParam.machineInfo.WORKCELL_CODE : cbMould.SelectedValue.ToString()) : lblMould.Text;
            Recovery(mouldcode);
        }
        #endregion

        #region 撤销
        /// <summary>
        /// 撤销
        /// </summary>
        /// <param name="mouldcode"></param>
        private void Recovery(string mouldcode)
        {

            if (MessageBox.Show("确定对该零件进行撤销操作?", "提示", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
            {
                return;
            }

            var result = _agent.InvokeServiceFunction<DAResult>(B9IPCService.DAI_Rollback.ToString()
                                                                   , new DAArgs
                                                                   {
                                                                       WorkCellCode = _operationServiceParam.machineInfo.WORKCELL_CODE,
                                                                       WorkLocCode = _operationServiceParam.machineInfo.WORKLOC_CODE,
                                                                       DACode = "",
                                                                       DAValue = "",
                                                                       MaterialCode = "",
                                                                       MachineCode = _operationServiceParam.machineInfo.MACHINECODDE,
                                                                       MachineName = _operationServiceParam.machineInfo.MACHINENAME,
                                                                       IsControl = _operationServiceParam.machineInfo.ISCONTROL,
                                                                       MouldCode = mouldcode,
                                                                       AttachData = AttachInfo
                                                                   });

            if (!result.Success) //如果采集数据输入失败
            {
                this.lblError.Text = result.Message;
                this.lblError.ForeColor = Color.White;
                this.lblError.BackColor = Color.Red;
                return;
            }
            SendRecoveryOrder(result.MouldCode);
            DoResultActions(result);
            DGView.Refresh();
            DGViewColorBind();

            //设置焦点
            this.ActiveControl = this.txtCode;
            txtCode.SelectAll();
            txtCode.Focus();
        }
        /// <summary>
        /// 撤销
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsbRecovery_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            string mouldcode = e.ClickedItem.Tag.ToString();
            Recovery(mouldcode);

        }
        #endregion 

        #region 重打总成码

        /// <summary>
        /// 
        /// </summary>
        public string PRODUCT_CODE { get; set; }

        /// <summary>
        /// 重打总成码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsbPrint_Click(object sender, EventArgs e)
        {
            if (this.DGViewProList.SelectedRows.Count == 0)
            {
                MessageBox.Show("请选择打印的本体信息!");
                return;
            }


            if (MessageBox.Show("确定打印该本体的总成条码?", "提示", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
            {
                return;
            }

            
            /////////////////////
            string selectKey = this.DGViewProList.SelectedRows[0].Cells["PRODUCTCODE"].Value.ToString();


            PRODUCT_CODE = selectKey;

            Report = new GridppReport();

            //数据填充
            //Report.FetchRecord += new _IGridppReportEvents_FetchRecordEventHandler(ReadFetchRecordBox);


            string reportPath = System.Configuration.ConfigurationManager.AppSettings["AssemblyPrintingTemplatePath"].ToString();

            //数据填充
            Report.FetchRecord += new _IGridppReportEvents_FetchRecordEventHandler(ReadFetchRecordBox3);

            Report.LoadFromFile(reportPath);

            //rep.Printer.PrinterName = "默认打印机";//调取不同的打印机

            Report.Print(false);

            PRODUCT_CODE = null;

            //PrintAssemblyLabe(selectKey);
        }
        private void ReadFetchRecordBox3()
        {
            try
            {
                var record = _agent.InvokeServiceFunction<BZDRecorder2>(B9IPCService.BZDRecorderBLL_GetRecord.ToString(), new BZDRecorder2() { PRODUCTCODE = PRODUCT_CODE });
                if (record != null)
                {
                    var config = _agent.InvokeServiceFunction<DataResult<BZDConfig>>(B9IPCService.BZDConfigBLL_Get.ToString(), new BZDConfig() { PID = record.MPID });
                    string e052BarCode = record.BZDCODE;
                    var MATERIAL_CODE = config.Result.MATERIALCODDE;
                    var color = config.Result.configDetail;

                    //添加补打记录
                    _agent.InvokeServiceFunction<int>(B9IPCService.BarCodeReplacementBLL_Insert.ToString(), new BarCodeReplacement() { ProductCode = PRODUCT_CODE, Type = "BZD条码重打" });

                    Report.DetailGrid.Recordset.Append();

                    Report.FieldByName("BarCode").Value = string.Format("*{0}*", e052BarCode);//总装条码

                    Report.FieldByName("FullBarCode").Value = e052BarCode;//总装条码

                    Report.FieldByName("PartCode").Value = color;//颜色

                    Report.FieldByName("PartDesc").Value = MATERIAL_CODE; //物料号

                    Report.DetailGrid.Recordset.Post();

                }
                
            }
            catch (Exception err)
            {
                throw new Exception(err.Message);
            }
        }


        #endregion

        #region 补打总成


        /// <summary>
        /// 重打总成码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            BZDPasswordForm psd = new BZDPasswordForm(this);
            BZDRePrintForm frm = new BZDRePrintForm(this);

            var result = psd.ShowDialog();
            if (result.ToString() == "OK")
            {
                frm.ShowDialog();
            }
            
        }

        #endregion

        #region 刷新
        /// <summary>
        /// 刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            BindView();
            BindPlanView();
        }
        #endregion

        #region 产品返修操作
        /// <summary>
        /// 产品返修操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEditProduct_Click(object sender, EventArgs e)
        {
            if (this.DGViewProList.SelectedRows.Count == 0)
            {
                MessageBox.Show("请选择要进行返修的表皮信息!");
                return;
            }

            if (MessageBox.Show("确定要进行返修的表皮信息?", "提示", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
            {
                return;
            }


            //判断是否已加工完成
            if (!this.DGViewProList.SelectedRows[0].Cells["OPERATESTATE"].Value.ToString().Equals(EnumGeter.OPERATESTATE.COMPLETED.GetHashCode().ToString()))
            {
                MessageBox.Show("只有加工完成的零件可以产品返修操作!");
                return;
            }

            //获取产品条码
            string selectKey = this.DGViewProList.SelectedRows[0].Cells["PRODUCTCODE"].Value.ToString();

            string pid = this.DGViewProList.SelectedRows[0].Cells["PPID"].Value.ToString();
            MainOperation mo = new MainOperation() { PID = pid };

            DataResult result = _agent.InvokeServiceFunction<DataResult>(B9BasicService.MainOperationBLL_MendProudct.ToString(), mo);
            MessageBox.Show(result.Msg);
            if (result.IsSuccess)
            {
                this.BindView();
                BindPlanView();
            }
        }
        #endregion 

        #region 取消加工
        /// <summary>
        /// 取消加工
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsbCancel_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(lblMould.Text) && cbMould.Items.Count > 1)
            {
                tsbCancel.DropDownItems.Clear();
                foreach (MachineInfoModels mould in cbMould.Items)
                {
                    var dditem = tsbCancel.DropDownItems.Add(mould.MODELNAME);
                    dditem.Tag = mould.MODELCODE;
                    dditem.Padding = new Padding(0, 10, 0, 0);
                }
                tsbCancel.ShowDropDown();
                return;
            }
            string mouldcode = string.IsNullOrWhiteSpace(lblMould.Text) ? (cbMould.Items.Count < 2 ? _operationServiceParam.machineInfo.WORKCELL_CODE : cbMould.SelectedValue.ToString()) : lblMould.Text;
            ResetClick(mouldcode);
        }

        #endregion 

        #region 复位
        /// <summary>
        /// 撤销
        /// </summary>
        /// <param name="mouldcode"></param>
        private void ResetClick(string mouldcode)
        {

            if (MessageBox.Show("确定对本工位进行复位操作?", "提示", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
            {
                return;
            }

            var result = _agent.InvokeServiceFunction<DAResult>(B9IPCService.DAI_Reset.ToString()
                                                                   , new DAArgs
                                                                   {
                                                                       WorkCellCode = _operationServiceParam.machineInfo.WORKCELL_CODE,
                                                                       WorkLocCode = _operationServiceParam.machineInfo.WORKLOC_CODE,
                                                                       DACode = "",
                                                                       DAValue = "",
                                                                       MaterialCode = "",
                                                                       MachineCode = _operationServiceParam.machineInfo.MACHINECODDE,
                                                                       MachineName = _operationServiceParam.machineInfo.MACHINENAME,
                                                                       MouldCode = mouldcode,
                                                                       AttachData = AttachInfo
                                                                   });

            if (!result.Success) //如果采集数据输入失败
            {
                this.lblError.Text = result.Message;
                this.lblError.ForeColor = Color.White;
                this.lblError.BackColor = Color.Red;
                return;
            }
            SendRecoveryOrder(mouldcode);
            DoResultActions(result);
            DGView.Refresh();
            DGViewColorBind();
        }
        #endregion 

        #region 重置
        /// <summary>
        /// 重置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsbCancel_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            string mouldcode = e.ClickedItem.Tag.ToString();
            ResetClick(mouldcode);

        }
        #endregion 

        #region 打开查询界面
        /// <summary>
        /// 打开查询界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsbSearch_Click(object sender, EventArgs e)
        {
            Form f = Application.OpenForms["MainOperationStaticForm"];  //查找是否打开过Form1窗体
            if (f == null)  //没打开过
            {
                MainOperationStaticForm form = new MainOperationStaticForm(_operationServiceParam.machineInfo, _operationServiceParam.processSet);
                form.MdiParent = this.ParentForm;
                form.Show();   //重新new一个Show出来
            }
            else
            {
                f.WindowState = FormWindowState.Normal;
                f.Focus();   //打开过就让其获得焦点
            }
        }
        #endregion 

        #region 放行
        /// <summary>
        /// 放行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsbPass_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(lblMould.Text)&&cbMould.Items.Count>1)
            {
                tsbPass.DropDownItems.Clear();
                foreach (MachineInfoModels mould in cbMould.Items)
                {
                    var dditem = tsbPass.DropDownItems.Add(mould.MODELNAME);
                    dditem.Tag = mould.MODELCODE;
                    dditem.Padding = new Padding(0, 10, 0, 0);
                }
                tsbPass.ShowDropDown();
                return;
            }
            string mouldcode = string.IsNullOrWhiteSpace(lblMould.Text) ? (cbMould.Items.Count < 2 ? _operationServiceParam.machineInfo.WORKCELL_CODE : cbMould.SelectedValue.ToString()) : lblMould.Text;
            LetPass(mouldcode);
        }
        /// <summary>
        /// 放行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsbPass_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            string mould = e.ClickedItem.Tag.ToString();

            LetPass(mould);
        }
        /// <summary>
        /// 放行
        /// </summary>
        /// <param name="mould"></param>
        private void LetPass(string mould)
        {
            if (MessageBox.Show("确定对该零件进行放行操作?", "提示", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
            {
                return;
            }

            var result = _agent.InvokeServiceFunction<DAResult>(B9IPCService.DAI_LetPass.ToString()
                                                                   , new DAArgs
                                                                   {
                                                                       WorkCellCode = _operationServiceParam.machineInfo.WORKCELL_CODE,
                                                                       WorkLocCode = _operationServiceParam.machineInfo.WORKLOC_CODE,
                                                                       DACode = "",
                                                                       DAValue = "",
                                                                       MaterialCode = "",
                                                                       MachineCode = _operationServiceParam.machineInfo.MACHINECODDE,
                                                                       MachineName = _operationServiceParam.machineInfo.MACHINENAME,
                                                                       IsControl = _operationServiceParam.machineInfo.ISCONTROL,
                                                                       MouldCode = mould,//string.IsNullOrWhiteSpace(lblMould.Text) ? (cbMould.Items.Count < 2 ? _operationServiceParam.machineInfo.WORKCELL_CODE : cbMould.SelectedValue.ToString()) : lblMould.Text
                                                                       AttachData = AttachInfo
                                                                   });

            if (!result.Success) //如果采集数据输入失败
            {
                this.lblError.Text = result.Message;
                this.lblError.ForeColor = Color.White;
                this.lblError.BackColor = Color.Red;
                return;
            }
            SendRecoveryOrder(mould);
            DoResultActions(result);
            DGView.Refresh();
            DGViewColorBind();

            //设置焦点
            this.ActiveControl = this.txtCode;
            txtCode.SelectAll();
            txtCode.Focus();
        }
        #endregion

        #region 重发启动信号
        /// <summary>
        /// 重新发送启动信号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsbReSignal_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(lblMould.Text) && cbMould.Items.Count > 1)
            {
                tsbReSignal.DropDownItems.Clear();
                foreach (MachineInfoModels mould in cbMould.Items)
                {
                    var dditem = tsbReSignal.DropDownItems.Add(mould.MODELNAME);
                    dditem.Tag = mould.MODELCODE;
                    dditem.Padding = new Padding(0, 10, 0, 0);
                }
                tsbReSignal.ShowDropDown();
                return;
            }
            string mouldcode = string.IsNullOrWhiteSpace(lblMould.Text) ? (cbMould.Items.Count < 2 ? _operationServiceParam.machineInfo.WORKCELL_CODE : cbMould.SelectedValue.ToString()) : lblMould.Text;
            ReSignal(mouldcode);
        }
        /// <summary>
        /// 重发启动信号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsbReSignal_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            string mould = e.ClickedItem.Tag.ToString();

            ReSignal(mould);
        }
        int reSignalClickCounter = 0;
        /// <summary>
        /// 重发启动信号
        /// </summary>
        /// <param name="mouldcode"></param>
        private void ReSignal(string mouldcode)
        {
            var result = _agent.InvokeServiceFunction<DataResult<string>>(B9IPCService.DAIBLL_GetSignalDAI.ToString(), _operationServiceParam.machineInfo.WORKCELL_CODE, string.Equals(_operationServiceParam.machineInfo.WORKCELL_CODE, mouldcode) ? "" : mouldcode);

            var dcache = daicache.FirstOrDefault(p => p.DACode == result.Result && p.MouldCode == mouldcode);
            if (dcache == null)
            {
                return;
            }
            if (!string.Equals(dcache.DAResult, "通过"))
            {
                if (reSignalClickCounter < 5)
                {
                    lblError.Text = "数据采集未通过,无法发送启动信号!";
                    this.lblError.ForeColor = Color.White;
                    this.lblError.BackColor = Color.Red;
                    reSignalClickCounter += 1;
                    return;
                }
                else //连续点击重发信号5次
                {
                    var dresult = MessageBox.Show("数据采集未通过,是否需要强制发送启动信号?", "发送启动信号", MessageBoxButtons.YesNoCancel);
                    if (dresult != System.Windows.Forms.DialogResult.Yes)
                    {
                        return;
                    }
                }
            }
            DAI signalDai = new DAI()
                {
                    WORKCELL_CODE = _operationServiceParam.machineInfo.WORKCELL_CODE,
                    WORKLOC_CODE = _operationServiceParam.machineInfo.WORKLOC_CODE,
                    DA_CODE = dcache.DACode,
                    MOULD_CODE = string.Equals(_operationServiceParam.machineInfo.WORKCELL_CODE, mouldcode) ? "1" : mouldcode,
                    Result = EnumGeter.ORDERTYPE.OK.GetHashCode().ToString(),
                    MATERIAL_CODE = dcache.MaterialCode

                };
            SendSignal(signalDai);
            reSignalClickCounter = 0;
        }
        #endregion 

        #region 点击缺陷统计卡
        /// <summary>
        /// 点击缺陷统计卡
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (this.DGViewProList.SelectedRows.Count == 0)
            {
                MessageBox.Show("请选择加工记录!");
                return;
            }
            if (this.DGViewProList.SelectedRows.Count > 1)
            {
                MessageBox.Show("只能选择一条加工记录!");
                return;
            }

            var temp = DGViewProList.SelectedRows[0].Cells["PRODUCTCODE"].Value.ToString();
            MendRecorderReasonForm form = new MendRecorderReasonForm(temp);

            form.ShowDialog();
        }
        #endregion 

        #region 安东呼叫
        /// <summary>
        /// 安东呼叫
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsbAndon_Click(object sender, EventArgs e)
        {
            Form f = Application.OpenForms["CallManageForm"];  //查找是否打开过Form1窗体
            if (f == null)  //没打开过
            {
                CallManageForm form = new CallManageForm(_operationServiceParam.machineInfo.WORKCENTER_CODE, _operationServiceParam.machineInfo.WORKLOC_CODE, _operationServiceParam.machineInfo.MACHINECODDE);
                form.MdiParent = this.MdiParent;
                form.WindowState = FormWindowState.Maximized;
                form.Show();   //重新new一个Show出来
            }
            else
            {
                //先关闭
                f.Close();
                //重新打开
                CallManageForm form = new CallManageForm(_operationServiceParam.machineInfo.WORKCENTER_CODE, _operationServiceParam.machineInfo.WORKLOC_CODE, _operationServiceParam.machineInfo.MACHINECODDE);
                form.MdiParent = this.MdiParent;
                form.WindowState = FormWindowState.Maximized;
                form.Show();   //重新new一个Show出来
            }
        }
        #endregion 
        #endregion

        #region 设置加工记录表列的颜色信息
        /// <summary>
        /// 设置列的颜色信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DGViewProList_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            if (e.RowIndex > DGViewProList.Rows.Count - 1)
                return;
            DataGridViewRow dgr = DGViewProList.Rows[e.RowIndex];
            try
            {
                if (dgr.Cells["OPERATESTATE"].Value.ToString() == EnumGeter.OPERATESTATE.OPERATING.GetHashCode().ToString())
                {
                    dgr.DefaultCellStyle.BackColor = Color.YellowGreen;
                    DGViewProList.ClearSelection();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion 

        #region 切换模具
        /// <summary>
        /// 切换模具
        /// </summary>
        /// <param name="mouldcode"></param>
        private void SwitchMould(string mouldcode)
        {
            lblMould.Text = mouldcode;
            daiviewSource.Clear();
            foreach (var row in daicache)
            {
                if (string.IsNullOrWhiteSpace(mouldcode) || string.IsNullOrWhiteSpace(row.MouldCode) || string.Equals(row.MouldCode, daiList.FirstOrDefault().WORKCELL_CODE) || string.Equals(row.MouldCode, mouldcode) || string.Equals(row.PREINPUT, "1"))
                {
                    if (row.DAType == "PARM")
                    { }
                    else
                    {
                        daiviewSource.Add(row);
                    }
                }
            }
            DGViewColorBind();
        }
        #endregion 

        #region 列表定时刷新
        private void cbListRowcount_SelectedIndexChanged(object sender, EventArgs e)
        {
            SaveSetting();
            BindView();
            BindPlanView();
        }

        private void cbRefreshRate_SelectedIndexChanged(object sender, EventArgs e)
        {
            SaveSetting();
        }
        private void cbPlanFilter_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindPlanView();
            SaveSetting();
        }

        private void SaveSetting()
        {
            string filepath = ConfigurationManager.AppSettings["SaveFilePath"];
            filepath = string.Format("{0}ViewSetting.cfg", filepath);
            var setting = new
            {
                ListRowcount = int.Parse(cbListRowcount.Text),
                RefreshRate = int.Parse(cbRefreshRate.Text.Trim('s')),
                //PlanFilter = cbPlanFilter.SelectedIndex
            };
            string settingstring = Newtonsoft.Json.JsonConvert.SerializeObject(setting);
            System.IO.File.WriteAllText(filepath, settingstring);
        }
        int timecounter = 0;
        int opcheartbeatcount = 0;
        System.Threading.AutoResetEvent opcheartbeatwaithandel = new AutoResetEvent(false);
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (!tsbOrderOperation.DropDown.Visible)
            {
                timecounter += 1;
                if (timecounter > int.Parse(cbRefreshRate.Text.Trim('s')))//计时达到刷新时间
                {

                    BindPlanView();

                }
            }
            if (proy != null)
            {
                opcheartbeatcount += 1;
                if (opcheartbeatcount > 10)
                {
                    if (proy.State == System.ServiceModel.CommunicationState.Faulted)
                    {
                        System.ServiceModel.InstanceContext site = new System.ServiceModel.InstanceContext(this);
                        proy = new ServiceOpc.OpcServiceClient(site);
                    }
                    if (proy.State == System.ServiceModel.CommunicationState.Created || proy.State == System.ServiceModel.CommunicationState.Opened)
                    {
                        var task = new System.Threading.Tasks.Task(() =>
                        {
                            try
                            {
                                proy.SendOperateOrder(string.Format("HeartBeat:{0}", _operationServiceParam.machineInfo.MACHINECODDE));
                                //opcheartbeatwaithandel.Reset();
                                if (opcheartbeatwaithandel.WaitOne(5000))
                                {
                                    ClientContext.OpcState = 1;
                                }
                                else
                                {
                                    ClientContext.OpcState = 3;
                                }
                            }
                            catch
                            {
                                ClientContext.OpcState = 2;
                            }
                        });
                        task.Start();
                    }
                    opcheartbeatcount = 0;
                }
            }
        }
        #endregion

        #region 切换选择计划和加工记录
        /// <summary>
        /// 切换选择计划和加工记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabView_Selected(object sender, TabControlEventArgs e)
        {
            tsbOrderOperation.Visible = tabView.SelectedTab == tpPlan;
            //butDEFECT.Enabled = tabView.SelectedTab == tpRecord;
        }
        #endregion

        #region 工单操作

        #region 取消挂起
        /// <summary>
        /// 取消挂起
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmiCancelSuspend_Click(object sender, EventArgs e)
        {
            if (dgvPlan.SelectedRows.Count <= 0)
            {
                MessageBox.Show("请选择一条工单进行取消挂起操作!");
                return;
            }
            List<string> ids = new List<string>();
            foreach (System.Windows.Forms.DataGridViewRow row in dgvPlan.SelectedRows)
            {
                var order = (QMAPP.FJC.Entity.ProductionPlan.WorkOrder)row.DataBoundItem;
                if (!int.Equals(order.STATE, 4))
                {
                    MessageBox.Show("只可取消状态为挂起的工单!");
                    return;
                }
                ids.Add(order.PID);
            }
            _agent.InvokeServiceFunction<int>(B9IPCService.WorkOrderBLL_CancelSuspend.ToString(), ids);
            BindPlanView();
        }
        #endregion

        #region 删除工单
        /// <summary>
        /// 删除工单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmiDeleteOrder_Click(object sender, EventArgs e)
        {
            if (dgvPlan.SelectedRows.Count <= 0)
            {
                MessageBox.Show("请选择一条工单进行删除操作!");
                return;
            }
            List<string> ids = new List<string>();
            foreach (System.Windows.Forms.DataGridViewRow row in dgvPlan.SelectedRows)
            {
                var order = (QMAPP.FJC.Entity.ProductionPlan.WorkOrder)row.DataBoundItem;
                if (!int.Equals(order.STATE, 4))
                {
                    MessageBox.Show("只可删除状态为挂起的工单!");
                    return;
                }
                ids.Add(order.PID);
            }
            _agent.InvokeServiceFunction<int>(B9IPCService.WorkOrderBLL_DeleteOrder.ToString(), ids);
            BindPlanView();
        }
        #endregion 

        #region 重置工单
        /// <summary>
        /// 重置工单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmiResetOrder_Click(object sender, EventArgs e)
        {
            if (dgvPlan.SelectedRows.Count <= 0)
            {
                MessageBox.Show("请选择一条工单进行重置操作!");
                return;
            }
            List<string> ids = new List<string>();
            foreach (System.Windows.Forms.DataGridViewRow row in dgvPlan.SelectedRows)
            {
                var order = (QMAPP.FJC.Entity.ProductionPlan.WorkOrder)row.DataBoundItem;
                if (!int.Equals(order.STATE, 4))
                {
                    MessageBox.Show("只可重置状态为挂起的工单!");
                    return;
                }
                ids.Add(order.PID);
            }
            _agent.InvokeServiceFunction<int>(B9IPCService.WorkOrderBLL_ResetOrder.ToString(), ids);
            BindPlanView();
        }
        #endregion 

        #region 挂起工单
        /// <summary>
        /// 挂起工单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmiSuspendOrder_Click(object sender, EventArgs e)
        {
            if (dgvPlan.SelectedRows.Count <= 0)
            {
                MessageBox.Show("请选择一条工单进行挂起操作!");
                return;
            }
            List<string> ids=new List<string>();
            foreach (System.Windows.Forms.DataGridViewRow row in dgvPlan.SelectedRows)
            {
                var order = (QMAPP.FJC.Entity.ProductionPlan.WorkOrder)row.DataBoundItem;
                if (int.Equals(order.STATE, 2))
                {
                    MessageBox.Show("不能挂起正在执行的工单!");
                    return;
                }
                ids.Add(order.PID);
            }
            _agent.InvokeServiceFunction<int>(B9IPCService.WorkOrderBLL_SuspendOrder.ToString(), ids);
            BindPlanView();
        }
        #endregion 

        #region 回收工单
        /// <summary>
        /// 回收工单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmiTakebackOrder_Click(object sender, EventArgs e)
        {
            if (dgvPlan.SelectedRows.Count <= 0)
            {
                MessageBox.Show("请选择一条工单进行回收操作!");
                return;
            }
            List<string> ids = new List<string>();
            foreach (System.Windows.Forms.DataGridViewRow row in dgvPlan.SelectedRows)
            {
                var order = (QMAPP.FJC.Entity.ProductionPlan.WorkOrder)row.DataBoundItem;
                if (!int.Equals(order.STATE, 4))
                {
                    MessageBox.Show("只可回收状态为挂起的工单!");
                    return;
                }
                ids.Add(order.PID);
            }
            _agent.InvokeServiceFunction<int>(B9IPCService.WorkOrderBLL_TakeBack.ToString(), ids);
            BindPlanView();
        }
        #endregion 

        #endregion 

        #region 工单列表选择发送变化时延时自动刷新
        /// <summary>
        /// 工单列表选择发送变化时延时自动刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvPlan_SelectionChanged(object sender, EventArgs e)
        {
            timecounter = -10;
        }
        #endregion 

        #region 设置计划工单列状态、颜色
        /// <summary>
        /// 设置计划工单列状态、颜色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvPlan_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            var WORKORDER_STATE_TEXT = new string[] {"初始","确认","执行中","完成","挂起" };
            var row = dgvPlan.Rows[e.RowIndex];
            var order = (FJC.Entity.ProductionPlan.WorkOrder)row.DataBoundItem;
            if (order.STATE >= 0 && order.STATE < WORKORDER_STATE_TEXT.Length)
            {
                row.Cells[dgcState.Name].Value = WORKORDER_STATE_TEXT[order.STATE];
            }
            if (order.STATE == FJC.Entity.EnumGeter.WorkOrderState.Suspended.GetHashCode())
            {
                row.DefaultCellStyle.BackColor = Color.LightGray;
                row.DefaultCellStyle.ForeColor = Color.Gray;
            }
            if (order.STATE == FJC.Entity.EnumGeter.WorkOrderState.Executing.GetHashCode())
            {
                row.DefaultCellStyle.BackColor = Color.YellowGreen;
                dgvPlan.ClearSelection();
            }
        }
        #endregion

        #region 切换计划和加工记录触发动作
        /// <summary>
        /// 切换计划和加工记录触发动作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabView_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtCode.SelectAll();
            txtCode.Focus();
        }
        #endregion 

        #region 采集区扫描颜色显示
        /// <summary>
        /// 采集区扫描颜色显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OperationForm_Activated(object sender, EventArgs e)
        {
            DGViewColorBind();
        }
        #endregion 

        #region 切换模具
        /// <summary>
        /// 切换模具
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbMould_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (_operationServiceParam.machineInfo.ISSTATION.Equals(1))
            {
                SwitchMould(cbMould.SelectedValue + "");
            }
        }
        #endregion 

        #region 切换设备
        /// <summary>
        /// 切换设备配置文件
        /// 20181119gzf
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CheckFile()
        {
            string locationfile2 = System.Configuration.ConfigurationManager.AppSettings["loactionfile2"];
            if (File.Exists(@locationfile2))
            {
                this.btnChange.Visible = true;
            }
            else
            {
                this.btnChange.Visible = false;
            }
        }

        /// <summary>
        /// 切换设备
        /// 20181119gzf
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnChange_Click(object sender, EventArgs e)
        {
            //string locationfile = System.Configuration.ConfigurationManager.AppSettings["loactionfile"];
            //string locationfile2 = System.Configuration.ConfigurationManager.AppSettings["loactionfile2"];
            //string str1 = File.ReadAllText(@locationfile);
            //string str2 = File.ReadAllText(locationfile2);
            //System.IO.File.WriteAllText(locationfile, str2);
            //System.IO.File.WriteAllText(locationfile2, str1);
            var machineInfo = this.comMachine.SelectedItem as MachineInfo;
            List<MachineInfo> machinelist = comMachine.DataSource as List<MachineInfo>;
            if (machinelist != null && machineInfo != null && !string.IsNullOrEmpty(machineInfo.OPCGROUPNAME))
            {
                var grouplist = machinelist.Where(p => p.OPCGROUPNAME == machineInfo.OPCGROUPNAME).ToList();
                var currentindex=grouplist.IndexOf(machineInfo);
                if (currentindex < grouplist.Count - 1)
                {
                    currentindex += 1;
                }
                else
                {
                    currentindex = 0;
                }
                this.comMachine.SelectedValue = grouplist[currentindex].MACHINECODDE;
                this.Init();
            }
        }
        #endregion 

        private void btnCollapse_Click(object sender, EventArgs e)
        {
            gbMlist.Visible = !gbMlist.Visible;
            plInfo.AutoSize = !gbMlist.Visible;
        }

        private void tsmiIgnoreFISBreak_Click(object sender, EventArgs e)
        {
            if (dgvPlan.SelectedRows.Count != 1)
            {
                MessageBox.Show("请选择一条(且只能选择一条)工单进行忽略断号操作!");
                return;
            }
            List<string> ids = new List<string>();
            foreach (System.Windows.Forms.DataGridViewRow row in dgvPlan.SelectedRows)
            {
                var order = (QMAPP.FJC.Entity.ProductionPlan.WorkOrder)row.DataBoundItem;
                if (!int.Equals(order.ORDER_TYPE, "0"))
                {
                    MessageBox.Show("只可对FIS工单进行忽略断号操作!");
                    return;
                }
                ids.Add(order.PID);
            }
            _agent.InvokeServiceFunction<int>("WorkOrderBLL_IgnoreFISBreak", ids);
            BindPlanView();
        }

        #region 根据配置 自动填充采集点

        /// <summary>
        /// 查找配置表
        /// </summary>
        /// <returns></returns>
        public string GetAppConfigValue(string pConfigCode)
        {
             var AppConfig = _agent.InvokeServiceFunction<AppConfig>(B9IPCService.AppConfigBLL_Get.ToString(), pConfigCode);

            if (AppConfig != null)
                return AppConfig.Value;
            else
                return null;
        }

        /// <summary>
        /// 查找PbomItem
        /// </summary>
        /// <returns></returns>
        public List<string> GetPBOMCODEValue(string MATERIAL_CODE)
        {
            var list = new List<string>();
            var PbomItem = _agent.InvokeServiceFunction<List<PbomItem>>(B9IPCService.PbomItemBLL_Get.ToString(), MATERIAL_CODE);

            if (PbomItem != null)
            {
                foreach (var va in PbomItem)
                {
                    list.Add(va.PBOM_CODE);
                }
                return list;
            }
            else
                return list;
        }

        /// <summary>
        /// 查找ScanIPConfig
        /// </summary>
        /// <returns></returns>
        public List<ScanIPConfig> GetSendPlcConfig(ScanIPConfig ScanIPConfigs)
        {
            var list = new List<string>();
            var PbomItemList = _agent.InvokeServiceFunction<List<ScanIPConfig>>(B9IPCService.ScanIPConfigBLL_Get.ToString(), ScanIPConfigs);

            return PbomItemList.OrderBy(c=>c.CFG).ToList();
        }
        
        /// <summary>
        /// 查找Product
        /// </summary>
        /// <returns></returns>
        public Product SelectProduct(string Products)
        {
            var list = new List<string>();
            var ProductList = _agent.InvokeServiceFunction<Product>(B9IPCService.ProductBLL_Get.ToString(), new Product() { PRODUCTCODE = Products });
            return ProductList;
        }

        /// <summary>
        /// 查找ScanIPConfig
        /// </summary>
        /// <returns></returns>
        public bool UpdateSendPlcConfig(ScanIPConfig ScanIPConfigs)
        {
            var list = new List<string>();
            var PbomItemList = _agent.InvokeServiceFunction<DataResult<int>>(B9IPCService.ScanIPConfigBLL_Update.ToString(), ScanIPConfigs);
            if (PbomItemList.Result > 0)
                return true;
            else
                return false;
        }

        /// <summary>
        /// 插入产品信息
        /// </summary>
        /// <returns></returns>
        public bool InsertProduct(Product Products)
        {
            var list = new List<string>();
            var PbomItemList = _agent.InvokeServiceFunction<DataResult<int>>(B9IPCService.ProductBLL_Insert.ToString(), Products);
            if (PbomItemList.Result >0)
                return true;
            else
                return false;
        }

        /// <summary>
        /// 插入加工记录信息
        /// </summary>
        /// <returns></returns>
        public bool InsertProcessRecord(ProcessRecord ProcessRecords)
        {
            var list = new List<string>();
            var PbomItemList = _agent.InvokeServiceFunction<DataResult<int>>(B9IPCService.ProcessRecordBLL_Insert.ToString(), ProcessRecords);
            if (PbomItemList.Result >0)
                return true;
            else
                return false;
        }

        /// <summary>
        /// 查找WorkOrder
        /// </summary>
        /// <returns></returns>
        public string GetWorkOrder_MATERIAL_CODE(string WorkOrderPID)
        {
            var WorkOrder = _agent.InvokeServiceFunction<WorkOrder>(B9IPCService.WorkOrderBLL_Get.ToString(), new WorkOrder() { PID = WorkOrderPID });
            if (WorkOrder != null)
                return WorkOrder.PBOM_CODE;
            else
                return null;
        }

        /// <summary>
        /// 查找WorkOrder
        /// </summary>
        /// <returns></returns>
        public void GetNewCode(ref string Code,ref string Number)
        {
            var code1 = Convert.ToInt32(Code.Substring(Code.Length - 9, 9));
            Code = Code.Substring(0, Code.Length - 9) + (code1 + Convert.ToInt32(Number)).ToString().PadLeft(9, '0');
            
            var ProductList = SelectProduct(Code);
            if (ProductList != null )
            {
                var newnumber = (Convert.ToInt32(Number) + 1).ToString();
                GetNewCode(ref Code,ref newnumber);
                Number = newnumber;
            }
            else
                Number = (Convert.ToInt32(Number) + 1).ToString();
        }


        #endregion
        
    }
}