using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using QMAPP.WinForm.Common;
using QMAPP.Entity;
using QMAPP.MD.Entity;
using QMAPP.ServicesAgent;
using QMAPP.FJC.Entity.Operation;
using QMFrameWork.Common.Serialization;
using QMAPP.WinForm.Forms.Operation;
using QMAPP.FJC.Entity.Basic;

namespace QMAPP.WinForm.Forms.Injection
{
    public partial class InjectionCodePrint : Form
    {
        //获取服务代理
        QMAPP.ServicesAgent.ServiceAgent _agent = ClientContext.GetServiceAgent();

        List<ProcessParameter> paramcolumns = new List<ProcessParameter>();
        FileSynchronizers.IFileSynchronizer sync;

        public InjectionCodePrint()
        {
            InitializeComponent();
        }

        private void InjectionCodePrint_Load(object sender, EventArgs e)
        {
            LoadMachineList();
            SetConnectState(0);

            this.radioButSignal.Checked = true;

            PrintTempleCopyClass printClass = new PrintTempleCopyClass();
            printClass.CopyPrintTemple("InjectionCodePrint");

            cbPrintCount.SelectedIndex = 3;
            cbPrintSpan.SelectedIndex = 3;
        }

        #region 加载设备列表
        /// <summary>
        /// 加载设备列表
        /// </summary>
        private void LoadMachineList()
        {
            #region
            BasicData basicData = new BasicData();
            var machinelist = basicData.GetMachineInfoAndModelList(new string[] {"1"}, 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.btnLockMachine.Visible = false;
                this.LockMachine(false);
            }
            else
            {
                //this.btnLockMachine.Visible = false;
                this.LockMachine(false);
            }
            comMachine_SelectedIndexChanged(null, null);
            #endregion
        }
        #endregion

        #region 打印
        /// <summary>
        /// 打印
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsbPrint_Click(object sender, EventArgs e)
        {
            //窗体数据校验
            string errorMessae = ErrorCheck();
            if (errorMessae != "")
            {
                MessageBox.Show(errorMessae, Resource1.ConfirmTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            tsbPrint.Enabled = false;
            CodeCreatePrint();
            tsbPrint.Enabled = true;
        }

        private void CodeCreatePrint()
        {
            List<Material> materialListInfo = GetSelectedMaterials();
            var model = cbMould.SelectedItem as MachineInfoModels;
            if (model == null)
            {
                model = new MachineInfoModels();
            }
            int i = 1;
            //DataResult<List<PrintCode>> resultList = _agent.InvokeServiceFunction<DataResult<List<PrintCode>>>("MainOperationBLL_GetPrintCodeForChengdu", materialListInfo, model, i);
            var machine = comMachine.SelectedItem as MachineInfo;
            DataResult<List<PrintCode>> resultList = _agent.InvokeServiceFunction<DataResult<List<PrintCode>>>("MainOperationBLL_GetPrintCodeWithParam", materialListInfo, machine, model, "", new Dictionary<string,string>());
            
            Print(resultList.Result, true);
        }

        private void CodeCreatePrint(string header, string datarow, char[] dataSeparator)
        {
            
            List<Material> materialListInfo = GetSelectedMaterials();
            var machine = comMachine.SelectedItem as MachineInfo;
            var model = cbMould.SelectedItem as MachineInfoModels;
            if (model == null)
            {
                model = new MachineInfoModels();
            }
            string tableName = paramcolumns.FirstOrDefault().PARATABLENAME;
            Dictionary<string,string> param=new Dictionary<string,string>();
            param.Add("PARAMETER_COLUMNS",header);
            var paramvalue=datarow.Split(dataSeparator);
            for(int j=0;j<paramvalue.Length;j++)
            {
                if(j<paramcolumns.Count)
                {
                    param.Add(paramcolumns[j].PARANAME,paramvalue[j]);
                }
                else
                {
                    break;
                }
            }
            int i = 1;
            DataResult<List<PrintCode>> resultList = _agent.InvokeServiceFunction<DataResult<List<PrintCode>>>("MainOperationBLL_GetPrintCodeWithParam", materialListInfo,machine,model,tableName,param);
            Print(resultList.Result,false);
        }
        private void Print(List<PrintCode> codeList,bool IsManual)
        {
            List<PrintTemplate.InjectLabel> labels = new List<PrintTemplate.InjectLabel>();
            //打印条码
            string typeTem = "";
            string typeData = "";
            foreach (PrintCode item in codeList)
            {
                
                //创建新行
                var row = new DataGridViewRow();
                if (DGView.Rows.Count == 0)
                {
                    var index = this.DGView.Rows.Add();
                    row = DGView.Rows[index];
                }
                else
                {
                    this.DGView.Rows.InsertCopy(0, 0);
                    row = DGView.Rows[0];
                }
                //对datagridview赋值
                row.Cells["MATERIAL_NAME"].Value = item.MATERIAL_NAME;
                row.Cells["PRODUCTCODE"].Value = item.PRODUCTCODE;
                row.Cells["MAINCODE"].Value = item.MAINCODE;
                row.Cells["CREATETIME"].Value = DateTime.Now;

                if (DGView.Rows.Count > 200)
                {
                    DGView.Rows.RemoveAt(200);
                }
                //班次信息
                string shiftCode = ClientContext.produceShift.PRODUCESHIFTTCODE;
                item.ShiftCode = shiftCode;

                DGView.AutoGenerateColumns = false;
                typeTem = item.PRINT_TEMPALTE_TEM;
                typeData = item.PRINT_TEMPALTE_DATA;
                //QM.Assist.LabelInfo ll = new QM.Assist.LabelInfo();
                //ll.BarCode = item.MATERIAL_NAME + "," + item.PRODUCTCODE + "," + item.MAINCODE + "," + shiftCode + "," + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                //QM.Assist.PrintUtil.LabelList2.Add(ll);
                PrintTemplate.InjectLabel label = new PrintTemplate.InjectLabel
                {
                    CreateDate = DateTime.Now,
                    MachineCode = comMachine.SelectedValue + "",
                    MaterialCode = item.PRODUCTCODE,
                    MaterialName = item.MATERIAL_NAME,
                    ModelCode = cbMould.SelectedValue + "",
                    SerialNumber = item.MAINCODE,
                    ShiftCode = shiftCode,
                    IsManualPrint = IsManual
                };
                labels.Add(label);
            }
            string path = System.Configuration.ConfigurationManager.AppSettings["Template_Local_Path"];
            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
            }
            FastReport.Report fr = new FastReport.Report();
            fr.RegisterData(labels, "Labels");
            if (!System.IO.File.Exists(string.Format("{0}\\{1}.frx", path, typeTem)))
            {
                if (System.IO.File.Exists(string.Format("PrintTemplate\\{1}.frx", path, typeTem)))
                {
                    System.IO.File.Copy(string.Format("PrintTemplate\\{1}.frx", path, typeTem)
                        , string.Format("{0}\\{1}.frx", path, typeTem));
                }
                else
                {
                    fr.FileName = string.Format("{0}\\{1}.frx", path, typeTem);
                    fr.Design(true);
                    fr.Save(string.Format("{0}\\{1}.frx", path, typeTem));
                }
            }
            fr.Load(string.Format("{0}\\{1}.frx", path, typeTem));
            if (cbTemplateDesign.Enabled && cbTemplateDesign.Checked)
            {
                fr.Design(true);
            }
            else
            {
                fr.PrintSettings.ShowDialog = false;
                fr.Print();
            }
            fr.Dispose();

            //QM.Assist.PrintUtil pu = new QM.Assist.PrintUtil();
            //pu.PrintLabel2(System.Configuration.ConfigurationManager.AppSettings["proPath"].ToString
            //    (), System.Configuration.ConfigurationManager.AppSettings[typeTem + "temPath"].ToString
            //    (), System.Configuration.ConfigurationManager.AppSettings[typeData + "dataPath"].ToString
            //    ());
        }

        private List<Material> GetSelectedMaterials()
        {
            List<Material> materialListInfo = new List<Material>();
            Material concationMaterial = new Material();
            //int i= Convert.ToInt32( this.txtNum.Text);

            if (this.radioButSignal.Checked == true)
            {
                string materialcode1 = this.txtMaterialCode.Text;
                concationMaterial.MATERIAL_CODE = materialcode1;
                materialListInfo.Add(concationMaterial);
            }
            else if (this.radioButDouble.Checked == true)
            {
                concationMaterial.MATERIAL_CODE = this.txtMaterialCode.Text;
                materialListInfo.Add(concationMaterial);
                if (!string.IsNullOrEmpty(this.comboxMaterial.SelectedValue.ToString()))
                {
                    Material concationMaterial2 = new Material();
                    concationMaterial2.MATERIAL_CODE = this.comboxMaterial.SelectedValue.ToString();
                    materialListInfo.Add(concationMaterial2);
                }
            }
            else if (this.radioButFourth.Checked == true)
            {
                concationMaterial.MATERIAL_CODE = this.txtMaterialCode.Text;
                materialListInfo.Add(concationMaterial);

                if (!string.IsNullOrEmpty(this.txtMaterial2.Text))
                {
                    Material concationMaterial3 = new Material();
                    concationMaterial3.MATERIAL_CODE = this.txtMaterial2.Text.Substring(this.txtMaterial2.Text.LastIndexOf(":") + 1);
                    materialListInfo.Add(concationMaterial3);
                }

                if (!string.IsNullOrEmpty(this.txtMaterial3.Text))
                {
                    Material concationMaterial4 = new Material();
                    concationMaterial4.MATERIAL_CODE = this.txtMaterial3.Text.Substring(this.txtMaterial3.Text.LastIndexOf(":") + 1);
                    materialListInfo.Add(concationMaterial4);
                }
                if (!string.IsNullOrEmpty(this.txtMaterial4.Text))
                {
                    Material concationMaterial5 = new Material();
                    concationMaterial5.MATERIAL_CODE = this.txtMaterial4.Text.Substring(this.txtMaterial4.Text.LastIndexOf(":") + 1);
                    materialListInfo.Add(concationMaterial5);
                }
            }
            return materialListInfo;
        }
        #endregion 

        #region 校验
        /// <summary>
        /// 校验
        /// </summary>
        /// <returns></returns>
        private string ErrorCheck()
        {
            #region
            string strMessage = "";
            
            var selectmachine= comMachine.SelectedItem as MachineInfo;
            if (selectmachine == null || string.IsNullOrEmpty(selectmachine.PID))
            {
                strMessage += "请选择注塑机!" + "\r\n";
            }
            //判断条码是否为空

            if (cbMould.Items.Count > 0 && cbMould.SelectedIndex < 0)
            {
                strMessage += "请选择模具!" + "\r\n";
            }

            //注塑零件
            if (this.txtMaterialCode.Text == null || this.txtMaterialCode.Text == string.Empty)
            {
                strMessage += Resource1.MaterialChoiceValidate + "\r\n";
            }
            
            

            //打印数量
            //if (this.txtNum.Text == null || this.txtNum.Text == string.Empty)
            //{
            //    strMessage += Resource1.NumNullValidate + "\r\n";
            //}
            //else 
            //{
            //    int proNum = 0;
            //    if (!int.TryParse(this.txtNum.Text, out proNum))
            //    {
            //        strMessage += Resource1.NumFormatValidate + "\r\n";
            //    }
            //}
            return strMessage;
            #endregion
        }
        #endregion

        #region 窗体关闭
        /// <summary>
        /// 窗体关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsbClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        #endregion 

        #region 点击选择零件信息
        /// <summary>
        /// 点击选择零件信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnChoiceMaterial_Click(object sender, EventArgs e)
        {
            MaterialTreeForm materialForm = new MaterialTreeForm();
            var ret= materialForm.ShowDialog();
            if (ret == DialogResult.OK)
            {
                this.txtMaterialCode.Text = materialForm.MaterialCode;
                this.textMaterialName.Text = materialForm.MaterialName;
                bool maintype = materialForm.MainType;
                if (maintype)
                {
                    this.groupBox3.Enabled = true;
                }
                else
                {
                    this.groupBox3.Enabled = false;
                }
            }
        }
        #endregion 

        #region 单选按钮
        /// <summary>
        /// 单件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void radioButSignal_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButSignal.Checked == true)
            {
                this.panel34.Visible = false;
                this.paneldouble.Visible = false;
            }
        }
        /// <summary>
        /// 双件,获取物料信息下拉
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void radioButDouble_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButDouble.Checked == true)
            {
                if (this.txtMaterialCode.Text == null || this.txtMaterialCode.Text == string.Empty)
                {
                    string Messae = Resource1.MaterialChoiceValidate + "\r\n";
                    MessageBox.Show(Messae, Resource1.ConfirmTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    radioButSignal.Checked = true;
                    return;
                }
                this.paneldouble.Visible = true;
                this.panel34.Visible = false;

                string materialCode = this.txtMaterialCode.Text;
                BasicData basicData = new BasicData();
                this.comboxMaterial.DataSource = basicData.GetMaterialInfoList(materialCode, true);
                this.comboxMaterial.DisplayMember = "MATERIAL_NAME";
                this.comboxMaterial.ValueMember = "MATERIAL_CODE";
            }

        }
        /// <summary>
        /// 四件,自动填写下拉物料信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void radioButFourth_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButFourth.Checked == true)
            {
                if (this.txtMaterialCode.Text == null || this.txtMaterialCode.Text == string.Empty)
                {
                    string Messae = Resource1.MaterialChoiceValidate + "\r\n";
                    MessageBox.Show(Messae, Resource1.ConfirmTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    radioButSignal.Checked = true;
                    return;
                }
                string materialCode = this.txtMaterialCode.Text;
                BasicData basicData = new BasicData();
                List<Material> materialList = basicData.GetMaterialInfoList(materialCode, false);
                materialList = materialList.OrderBy(p => p.MATERIAL_CODE).ToList();
                if (materialList.Count < 3)
                {
                    string Messae = Resource1.SelectedInfoWrong + "\r\n";
                    MessageBox.Show(Messae, Resource1.ConfirmTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    radioButSignal.Checked = true;
                    return;
                }
                this.panel34.Visible = true;
                this.paneldouble.Visible = false;
                this.txtMaterial2.Text = materialList[0].MATERIAL_NAME;
                this.txtMaterial3.Text = materialList[1].MATERIAL_NAME;
                this.txtMaterial4.Text = materialList[2].MATERIAL_NAME;

            }
        }
        #endregion 


        /// <summary>
        /// 所选零件发生改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtMaterialCode_TextChanged(object sender, EventArgs e)
        {
            radioButSignal.Checked = true;
        }

        

        private void btnStart_Click(object sender, EventArgs e)
        {
            //窗体数据校验
            string errorMessae = ErrorCheck();
            if (errorMessae != "")
            {
                MessageBox.Show(errorMessae, Resource1.ConfirmTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            btnStart.Enabled = false;
            btnStop.Enabled = true;
            cbPrintCount.Enabled = false;
            cbPrintSpan.Enabled = false;
            lblLastCount.Text = cbPrintCount.Text;
            tsbPrint.Enabled = false;
            btnChoiceMaterial.Enabled = false;
            groupBox3.Enabled = false;
            printtimer = int.Parse(cbPrintSpan.Text.Trim('s'));
            LockPrintMode(2);

        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            btnStart.Enabled = true;
            btnStop.Enabled = false;
            cbPrintCount.Enabled = true;
            cbPrintSpan.Enabled = true;
            //lblLastCount.Text = cbPrintCount.Text;
            tsbPrint.Enabled = true;
            btnChoiceMaterial.Enabled = true;
            groupBox3.Enabled = true;
            LockPrintMode(-1);
        }

        int printtimer = 0;

        private void timer2_Tick(object sender, EventArgs e)
        {
            if (!btnStart.Enabled&&btnStop.Enabled)
            {
                int span=int.Parse(cbPrintSpan.Text.Trim('s'));
                if (printtimer >= span)
                {
                    CodeCreatePrint();
                    printtimer = 0;
                    var lastcount = int.Parse(lblLastCount.Text) - 1;
                    lblLastCount.Text = lastcount + "";
                    if (lastcount <= 0)
                    {
                        btnStop_Click(sender, e);
                    }

                }
                else
                {
                    printtimer++;
                }
            }
            else
            {
                printtimer = 0;
            }
        }

        private void comMachine_SelectedIndexChanged(object sender, EventArgs e)
        {
            var selectmachine = comMachine.SelectedItem as MachineInfo;
            if (selectmachine != null && !string.IsNullOrEmpty(selectmachine.PID))
            {
                var mouldList = _agent.InvokeServiceFunction<List<MachineInfoModels>>(B9BasicService.MachineInfoModelBLL_GetAllList.ToString(), new MachineInfoModels { MID = "INJ_MODEL" }).OrderBy(p => p.MODELCODE).ToList();
                mouldList.Insert(0, new MachineInfoModels { });
                cbMould.DisplayMember = "MODELNAME";
                cbMould.ValueMember = "MODELCODE";
                cbMould.DataSource = mouldList.ToList();

                if (selectmachine.ISCONTROL == "1")
                {
                    HideTimerPrint(true);
                }
                else
                {
                    HideTimerPrint(false);
                }
            }
            
        }

        private void btnStartFileScan_Click(object sender, EventArgs e)
        {
            //窗体数据校验
            string errorMessae = ErrorCheck();
            if (errorMessae != "")
            {
                MessageBox.Show(errorMessae, Resource1.ConfirmTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            var selectmachine= comMachine.SelectedItem as MachineInfo;
            if (selectmachine != null&&!string.IsNullOrEmpty(selectmachine.PID))
            {
                txtFilePath.Text = selectmachine.EQUIPMENT_DIRECTORY;
                var columns = _agent.InvokeServiceFunction<DataResult<List<ProcessParameter>>>("ProcessParameterBLL_GetAllList", new ProcessParameter { MACHINECODDE = selectmachine.MACHINECODDE }).Result;
                if (columns != null)
                {
                    paramcolumns = columns;
                }
                else
                {
                    paramcolumns = new List<ProcessParameter>();
                }
                lvParamRecords.Items.Clear();
                lvParamRecords.Columns.Clear();
                var c1=lvParamRecords.Columns.Add("扫描时间");
                c1.Width=180;
                foreach (var col in paramcolumns)
                {
                    var  c= lvParamRecords.Columns.Add(col.PARADESCRIBE);
                }
                if (selectmachine.EQUIPMENT_TYPE_CODE == "HaitianInjection")
                {
                    sync = new FileSynchronizers.HaitianInjectionFileSynchronizer(selectmachine);
                }
                else if (selectmachine.EQUIPMENT_TYPE_CODE == "EngelInjection")
                {
                    sync = new FileSynchronizers.EngelInjectionFileSynchronizer(selectmachine);
                }
                else
                {
                    MessageBox.Show("注塑机型号未设定!", Resource1.ConfirmTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                sync.NewRecordFound += new EventHandler<FileSynchronizers.InjParamEventArgs>(sync_NewRecordFound);
                sync.ExceptionCatched += new EventHandler<FileSynchronizers.InjParamEventArgs>(sync_ExceptionCatched);
                sync.Start(cbSkipHistory.Checked);
                SetConnectState(1);
                btnStartFileScan.Enabled = false;
                btnStopFileScan.Enabled = true;
                LockPrintMode(0);
            }
            else
            {
                MessageBox.Show("请选择注塑机!", Resource1.ConfirmTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        /// <summary>
        /// 设置连接状态
        /// </summary>
        /// <param name="state">0:停止 1:正常 2:断开</param>
        void SetConnectState(int state)
        {
            switch (state)
            {
                case 0:
                    {
                        txtConnectState.Text = "扫描停止";
                        picConnectState.Image = WinForm.Resource1.stop;
                        break;
                    }
                case 1:
                    {
                        txtConnectState.Text = "扫描正常";
                        picConnectState.Image = WinForm.Resource1.reload;
                        break;
                    }
                case 2:
                    {
                        txtConnectState.Text = "连接断开";
                        picConnectState.Image = WinForm.Resource1.no;
                        break;
                    }
            }
        }
        /// <summary>
        /// 锁定打印模式
        /// </summary>
        /// <param name="mode">-1 解锁; 0 联机; 1 手动; 2 定时;</param>
        void LockPrintMode(int mode)
        {
            for(int i=0;i<tpPrintMode.Controls.Count;i++)
            {
                if(i==mode)
                {
                    tpPrintMode.Controls[i].Enabled = true;
                }
                else if (mode < 0)
                {
                    tpPrintMode.Controls[i].Enabled = true;
                }
                else
                {
                    tpPrintMode.Controls[i].Enabled = false;
                }
            }
            plPrintSetting.Enabled = mode < 0;
        }


        /// <summary>
        /// 隐藏定时打印模式
        /// </summary>
        void HideTimerPrint(bool hide)
        {
            if (hide)
            {
                if (tpPrintMode.Controls.Contains(tpTimer))
                    //tpPrintMode.Controls[tpTimer.Name].Visible = !hide;
                    tpPrintMode.Controls.Remove(tpTimer);
            }
            else
            {
                if (!tpPrintMode.Controls.Contains(tpTimer))
                    //tpPrintMode.Controls[tpTimer.Name].Visible = !hide;
                    tpPrintMode.Controls.Add(tpTimer);
            }
        }

        void sync_ExceptionCatched(object sender, FileSynchronizers.InjParamEventArgs e)
        {
            this.Invoke((Action)(() => {
                txtMessage.Text = e.Exception.Message;
                SetConnectState(2);
            }));
        }

        void sync_NewRecordFound(object sender, FileSynchronizers.InjParamEventArgs e)
        {
            this.Invoke((Action)(() =>
            {
                CodeCreatePrint(e.HeaderRow, e.DataRow, e.DataSeparator);
                txtCurrentFile.Text = e.FileName;
                txtLastScanTime.Text = e.RecordTime.ToString("hh:mm:ss");
                txtMessage.Text = e.DataRow;
                var li = lvParamRecords.Items.Insert(0,e.RecordTime.ToString("yyyy-MM-dd hh:mm:ss"));
                li.SubItems.AddRange(e.DataRow.Split(e.DataSeparator));
                if (lvParamRecords.Items.Count > 200)
                {
                    lvParamRecords.Items.RemoveAt(200);
                }
                SetConnectState(1);
            }));
        }

        private void btnStopFileScan_Click(object sender, EventArgs e)
        {
            if (sync != null)
            {
                sync.Stop();
            }
            SetConnectState(0);
            btnStartFileScan.Enabled = true;
            btnStopFileScan.Enabled = false;
            LockPrintMode(-1);
        }

        private void InjectionCodePrint_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (sync != null)
            {
                sync.Stop();
            }
        }

        private void btnLockMachine_Click(object sender, EventArgs e)
        {
            if (this.btnLockMachine.Tag.ToString().Equals("0"))
            {
                LockMachine(false);
            }
            else
            {
                LockMachine(true);
            }
        }
        #region 设备锁定
        /// <summary>
        /// 设备锁定
        /// </summary>
        /// <param name="lockFlag"></param>
        private void LockMachine(bool lockFlag)
        {
            this.comMachine.Enabled = lockFlag;
            //this.comProductType.Enabled = lockFlag;
            if (lockFlag)
            {

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

        }
        #endregion 
    }
}