using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Threading;
using ChuPiao.AutoPrint.Machine;
using ChuPiao.AutoPrint.Machine.Models;
using ChuPiao.AutoPrint.Services.OpenCode;
using ChuPiao.AutoPrint.Services.TicketFile;
using ChuPiao.Common.Core.Utils;
using ChuPiao.Common.Enums;
using ChuPiao.Common.Models;
using ChuPiao.Common.Utils;
//using ChuPiao.AutoPrint.Services.ZcMatch;
using System.Data;
using ChuPiao.Common.Communication.GtdJson.Packs;
using ChuPiao.Common.Communication.GtdJson;
using ChuPiao.Common.Communication.GtdJson.Items;

namespace ChuPiao.AutoPrint.Services.AutoPrint
{
    public class AutoPrintService
    {

        public static bool isCOMOK = true;
        /// <summary>
        /// 出票中
        /// </summary>
        public event EventHandler<TicketEventArgs> Printing;
        /// <summary>
        /// 出票完成
        /// </summary>
        public event EventHandler<TicketEventArgs> Printed;
        /// <summary>
        /// 状态变化
        /// </summary>
        public event EventHandler<MachineStatusArgs> StatusChanged;
        /// <summary>
        /// 合计清零
        /// </summary>
        public event EventHandler AmountCleared;
        /// <summary>
        /// 错误清除
        /// </summary>
        public event EventHandler ErrorCleared;
        public ILotMachine LotMachine;
        private Thread _workThread;
        private bool _isStop = true;
        //private JcMatchSnapService _jcMatchSnapService = null;
        //private ZcMatchSnapService _zcMatchSnapService = null;
        private IOpenCodeSnapService _openCodeSnapService = null;
        //ManualResetEvent _manualResetEvent = new ManualResetEvent(false);
        public void Start()
        {
            try
            {
                if (LotMachine.MachineInfo.M_Status == (int)MachineStatusEnum.Stopped)
                {
                    lock (WaitPrintTickets)
                    {
                        WaitPrintTickets.Clear();
                    }
                    LotMachine.Log.Info("启动出票前获取彩票机缓冲区数据……");
                    CaptureDataInfo dataInfo = LotMachine.GetCacheTicket();
                    if (dataInfo != null && dataInfo.CaptureDataBytes.Length > 0)
                    {
                        LotMachineService.PrintETicket(LotMachine.MachineInfo.M_Number, dataInfo.CaptureDataBytes);
                    }

                    //开启出票就置空彩票机的投注模式，处理完错误就重新切换投注模式
                    LotMachine.MacCurrentMode = null;

                    ////加载上一次出票成功但更新数据库失败的票
                    //try
                    //{
                    //    L_LotTicketEntity ticket = new L_LotTicketEntity();
                    //    L_PrintTicketEntity printTicket = new L_PrintTicketEntity();
                    //    bool loadsuc = FileService.LoadPrintInfoFromLocalFile(LotMachine.MachineInfo.M_Number, ticket, printTicket);
                    //    if (loadsuc)
                    //    {
                    //        //L_LotTicketService ticketService = new L_LotTicketService();
                    //        try
                    //        {
                    //            //ticketService.AddPrintTicket(ticket, printTicket);
                    //            //LotMachine.Log.Info(string.Concat("处理上一次出票成功但更新数据库失败的票完成。生产流水号：", ticket.L_TicketSn, " 票号：", printTicket.P_TicketCode, " 密码：", printTicket.P_Password, " 金额：", printTicket.P_Money));
                    //        }
                    //        catch (Exception exception)
                    //        {
                    //            MessageService.ShowMessage(string.Concat("处理上一次出票成功但更新数据库失败的票异常。错误信息：", exception));
                    //            FileService.SavePrintInfoToLocalFile(ticket, printTicket);
                    //            return;
                    //        }
                    //    }
                    //}
                    //catch (Exception exception)
                    //{
                    //    MessageService.ShowMessage(string.Concat("处理上一次出票成功但更新数据库失败的票异常。错误信息：", exception));
                    //    return;
                    //}

                    //if (LotMachine.MachineInfo.M_Type == (int)MachineType.JxJingCaiV1 || LotMachine.MachineInfo.M_Type == (int)MachineType.TjJingCaiV1)
                    //{
                    //    //竟彩对阵抓取服务
                    //    _jcMatchSnapService = new JcMatchSnapService(LotMachine);
                    //}
                    //else if (LotMachine.MachineInfo.M_Type == (int)MachineType.JxTiCaiMachineV2)
                    //{
                    //    _zcMatchSnapService = new ZcMatchSnapService(LotMachine);
                    //}
                    //else if (LotMachine.MachineInfo.M_Type == (int)MachineType.JxTiCaiMachineV3 || LotMachine.MachineInfo.M_Type == (int)MachineType.HbGaoPinCai)
                    //{
                        _openCodeSnapService = new DlOpenCodeSnapService(LotMachine,(int)Lottype.Hd);
                    //}
                    //else if (LotMachine.MachineInfo.M_Type == (int)MachineType.JsTiCai)
                    //{
                    //    string address = System.Configuration.ConfigurationManager.AppSettings.Get("Address");
                    //    if (address == null) address = "";
                    //    if (address.IndexOf("竞彩") > -1)
                    //    {
                    //        _jcMatchSnapService = new JcMatchSnapService(LotMachine);
                    //    }
                    //    else if (address.IndexOf("多乐彩") > -1)
                    //    {
                    //        _openCodeSnapService = new JdOpenCodeSnapService(LotMachine);
                    //    }
                    //    else if (address.IndexOf("体彩") > -1)
                    //    {
                    //        _zcMatchSnapService = new ZcMatchSnapService(LotMachine);
                    //    }
                    //}


                    //LotMachine.EnterSaleGui();
                    if (_workThread != null && _workThread.IsAlive)
                    {
                        LoggingService.Error(string.Concat("线程", _workThread.ManagedThreadId, "当前为执行状态"));
                        return;
                    }
                    if (_workThread != null)
                    {
                        _workThread.Abort();
                    }

                    _isStop = false;
                    _workThread = new Thread(new ThreadStart(DoTask));
                    _workThread.Start();
                    UpdateMachineStatus(MachineStatusEnum.Printing);
                    LotMachine.Log.Info("启动出票");
                    LoggingService.Info(string.Concat(LotMachine.MachineInfo.M_Number, "启动出票"));
                }
            }
            catch (Exception e1)
            {
                LoggingService.Error(string.Concat("启动出票服务异常。错误信息：", e1));
            }

        }

        public void Stop()
        {
            //if (LotMachine.MachineInfo.M_Status == (int)MachineStatusEnum.Printing)
            if (!_isStop)
            {
                try
                {
                    UpdateMachineStatus(MachineStatusEnum.Stopping);
                    LotMachine.Log.Info("停止出票中" + LotMachine.MachineInfo.M_Status);
                    LoggingService.Info(string.Concat(LotMachine.MachineInfo.M_Number, "停止出票中"));
                    _isStop = true;
                    Wait4Job.Set();

                    //_manualResetEvent.Set();
                    //WaitPrintTickets.Clear();
                }
                catch (Exception e)
                {
                    LotMachine.Log.Info("停止出票失败！");
                }
            }
        }



        private EventWaitHandle _wait4Job = new EventWaitHandle(true, EventResetMode.ManualReset);

        public EventWaitHandle Wait4Job
        {
            get
            {
                return _wait4Job;
            }
        }
        /// <summary>
        /// 出票错误
        /// </summary>
        public event EventHandler<ErrorTicketEventArgs> PrintTicketError;
        /// <summary>
        /// 等待出票队列
        /// </summary>
        public Queue<L_LotTicketEntity> WaitPrintTickets = new Queue<L_LotTicketEntity>();
        /// <summary>
        /// 等待出票票数
        /// </summary>
        public int WaitPrintTicketCount
        {
            get
            {
                lock (WaitPrintTickets)
                {
                    return WaitPrintTickets.Count;
                }
            }
        }

        public List<M_LotTypeEntity> LotTypeList
        {
            get
            {
                if (_lotTypeList == null)
                {
                    //M_LotTypeService lotTypeService = new M_LotTypeService();
                    //_lotTypeList = lotTypeService.GetEnabledLotTypeList();

                    _lotTypeList = new List<M_LotTypeEntity>();

                    M_LotTypeEntity entity = new M_LotTypeEntity();
                    entity.L_LotId = 911;
                    entity.L_LotName = "竞彩足球";
                    entity.L_LotShortName = "jz";
                    entity.L_Enabled = true;
                    _lotTypeList.Add(entity);

                    entity = new M_LotTypeEntity();
                    entity.L_LotId = 951;
                    entity.L_LotName = "竞彩篮球";
                    entity.L_LotShortName = "jl";
                    entity.L_Enabled = true;
                    _lotTypeList.Add(entity);

                    entity = new M_LotTypeEntity();
                    entity.L_LotId = 701;
                    entity.L_LotName = "大乐透";
                    entity.L_LotShortName = "lt";
                    entity.L_Enabled = true;
                    _lotTypeList.Add(entity);

                    entity = new M_LotTypeEntity();
                    entity.L_LotId = 601;
                    entity.L_LotName = "胜负彩";
                    entity.L_LotShortName = "sf";
                    entity.L_Enabled = true;
                    _lotTypeList.Add(entity);

                    entity = new M_LotTypeEntity();
                    entity.L_LotId = 503;
                    entity.L_LotName = "湖北11选5";
                    entity.L_LotShortName = "hd";
                    entity.L_Enabled = true;
                    _lotTypeList.Add(entity);

                    entity = new M_LotTypeEntity();
                    entity.L_LotId = 702;
                    entity.L_LotName = "排列3";
                    entity.L_LotShortName = "ps";
                    entity.L_Enabled = true;
                    _lotTypeList.Add(entity);

                    entity = new M_LotTypeEntity();
                    entity.L_LotId = 703;
                    entity.L_LotName = "排列5";
                    entity.L_LotShortName = "pw";
                    entity.L_Enabled = true;
                    _lotTypeList.Add(entity);

                    entity = new M_LotTypeEntity();
                    entity.L_LotId = 704;
                    entity.L_LotName = "7星彩";
                    entity.L_LotShortName = "qx";
                    entity.L_Enabled = true;
                    _lotTypeList.Add(entity);

                }
                return _lotTypeList;
            }
        }

        private List<M_LotTypeEntity> _lotTypeList = null;

        /// <summary>
        /// 出票空闲时等待轮询时间 秒
        /// </summary>
        public int WaitTime = 3;
        /// <summary>
        /// 一次最多加载票数
        /// </summary>
        public const int MaxOneLoad = 100;
        //更新当前有效彩种的间隔时间 秒
        private const int UpdateEnabledLotTypeInterval = 60;
        //更新当前有效彩种的等待时间
        private int UpdateEnabledLotTypeWaitTime = 0;
        private void UpdateEnabledLotType()
        {
            try
            {
                //_lotTypeList = new M_LotTypeService().GetEnabledLotTypeList();
            }
            catch (Exception ex)
            {
                LotMachine.Log.Error(ex.ToString());
            }
        }

        private bool _isTopGUI = false;
        private void DoTask()
        {
            Random random = new Random();

            //int i = 0;
            //while (LotMachine.MachineInfo.M_Status==(int)MachineStatusEnum.Printing)
            while (!_isStop || WaitPrintTicketCount > 0)
            {
                LotMachine.Log.Debug(string.Concat("出票服务心跳正常 ThreadId:", _workThread.ManagedThreadId, " IsAlive:", _workThread.IsAlive));
                //if (LotMachine.MachineInfo.M_Status == (int)MachineStatusEnum.Stopping)
                //{
                //    LotMachine.Log.Info("停止出票中……");
                //}
                if (WaitPrintTicketCount == 0)
                {
                    //加载票
                    bool isLoadSuc = false;
                    try
                    {

                        //M_MachinePlayCacheService machinePlayCacheService = new M_MachinePlayCacheService();
                        //List<int> lotIdList = machinePlayCacheService.GetMachineLotIdList(LotMachine.MachineInfo.M_Number);
                        //LotMachine.Log.Info(string.Concat("可出票彩种个数：", lotIdList.Count));

                        //L_ExpectCacheService expectCacheService = new L_ExpectCacheService();
                        //L_ExpectService expectService=new L_ExpectService();
                        //PrintTicketComparer ticketComparer = new PrintTicketComparer();
                        //foreach (M_LotTypeEntity lotTypeEntity in LotTypeList)
                        //{
                        //    //不在可出票彩种，直接跳过
                        //    if (!LotMachine.MachineInfo.M_LotStr.Contains(lotTypeEntity.L_LotId.ToString() + ","))
                        //        continue;


                        ////if (lotTypeEntity.L_LotId == (int)Lottype.Lt)
                        ////{
                        ////    if ((DateTime.Now.DayOfWeek == DayOfWeek.Monday || DateTime.Now.DayOfWeek == DayOfWeek.Wednesday || DateTime.Now.DayOfWeek == DayOfWeek.Saturday)
                        ////    && DateTime.Now.Hour >= 20 && DateTime.Now.Hour < 22)            //大乐透截期后两小时内彩票机没有开售新期不请求票
                        ////    {
                        ////        continue;
                        ////    }

                        ////    if (!((DateTime.Now.DayOfWeek == DayOfWeek.Monday || DateTime.Now.DayOfWeek == DayOfWeek.Wednesday || DateTime.Now.DayOfWeek == DayOfWeek.Saturday)
                        ////    && DateTime.Now.Hour >= 19 && DateTime.Now.Hour < 20))           //截止前1小时 以外的时间，平均1分钟请求1次，因为大乐透的票量不大，很多都是无效请求
                        ////    {

                        ////        int num = random.Next(100);
                        ////        //LotMachine.Log.Info(num.ToString());
                        ////        num = num % 10;
                        ////        if (num != 0 && num != 1)
                        ////        {
                        ////            continue;
                        ////        }
                        ////    }
                        ////}

                        //if (lotTypeEntity.L_LotId == (int)Lottype.Jz || lotTypeEntity.L_LotId == (int)Lottype.Jl || lotTypeEntity.L_LotId == (int)Lottype.Jm)
                        //{
                        //竟彩不按期加载可出票列表
                        //JcL_LotTicketService jcLotTicketService=new JcL_LotTicketService();
                        List<L_LotTicketEntity> jcTicketList = new List<L_LotTicketEntity>();
                        try
                        {
                            //jcTicketList = jcLotTicketService.LoadPrintTicketList(lotTypeEntity.L_LotId, LotMachine.MachineInfo.M_Number, MaxOneLoad);
                            //jcTicketList.Sort(ticketComparer);

                            A10001GetTicket pack = new A10001GetTicket();
                            pack.AgentId = LotMachine.MachineInfo.M_Number;
                            pack.Salt = LotMachine.MachineInfo.M_Salt;
                            pack.LotId = 0;
                            A10001GetTicketRet packRet = PackManager.Instance.Send(pack) as A10001GetTicketRet;
                            if (packRet.Ticket != null)
                            {
                                //packRet.Ticket.LotId = lotTypeEntity.L_LotId;
                                jcTicketList.Add(packRet.Ticket);
                            }


                        }
                        catch (Exception exception1)
                        {
                            LotMachine.Log.Warn(string.Concat("加载票异常。错误信息：", exception1));
                        }

                        LotMachine.Log.Info(string.Concat("加载票：", jcTicketList.Count, "张"));

                        if (jcTicketList.Count > 0)
                        {
                            isLoadSuc = true;
                            lock (WaitPrintTickets)
                            {
                                foreach (L_LotTicketEntity entity in jcTicketList)
                                {
                                    WaitPrintTickets.Enqueue(entity);
                                }
                            }
                        }

                        //}
                        //else if (lotTypeEntity.L_LotId == (int)Lottype.Bd)
                        //{
                        //    //L_BdExpectCacheService bdExpectCacheService = new L_BdExpectCacheService();
                        //    BdL_ExpectService bdExpectService = new BdL_ExpectService();
                        //    //List<L_ExpectEntity> expectList =bdExpectCacheService.GetChuPiaoExpectList(lotTypeEntity.L_LotId);
                        //    List<L_ExpectEntity> expectList = bdExpectService.GetExpectListByStatus(lotTypeEntity.L_LotId, (int)ExpectStatus.ChuPiao);
                        //    BdL_LotTicketService bdLotTicketService=new BdL_LotTicketService();
                        //    foreach (L_ExpectEntity expectEntity in expectList)
                        //    {
                        //        List<L_LotTicketEntity> ticketList = new List<L_LotTicketEntity>();
                        //        try
                        //        {
                        //            ticketList = bdLotTicketService.LoadPrintTicketList(lotTypeEntity.L_LotId, expectEntity.E_Expect, LotMachine.MachineInfo.M_Number, MaxOneLoad);
                        //            ticketList.Sort(ticketComparer);
                        //        }
                        //        catch (Exception exception1)
                        //        {
                        //            LotMachine.Log.Warn(string.Concat("加载票异常。错误信息：", exception1, " LoadPrintTicketList()参数：lotId:", lotTypeEntity.L_LotId, " expect:", expectEntity.E_Expect, " macNumber:", LotMachine.MachineInfo.M_Number, " num:", MaxOneLoad));
                        //        }
                        //        if (ticketList != null)
                        //        {
                        //            LotMachine.Log.Info(string.Concat("彩种：", lotTypeEntity.L_LotName, "，可出票期号：", expectEntity.E_Expect, "，加载票：", ticketList.Count, "张"));

                        //            //#region 北单自动设置禁止出票（针对某些特定的订单bd_cancelorder表有效的订单号）
                        //            //if(ticketList.Count>0)
                        //            //{
                        //            //    try
                        //            //    {
                        //            //        List<string> cancelOrderSnList =
                        //            //            new L_CancelOrderService().GetEnabledCancelOrderSnList(
                        //            //                (int)Lottype.Bd, expectEntity.E_Expect);
                        //            //        if (cancelOrderSnList.Count > 0)
                        //            //        {
                        //            //            LotMachine.Log.Info(string.Concat("加载北单自动设置禁止出票订单号", cancelOrderSnList.Count, "个"));
                        //            //            List<L_LotTicketEntity> bdCancelTicketList = new List<L_LotTicketEntity>();
                        //            //            for (int i = ticketList.Count - 1; i >= 0; i--)
                        //            //            {
                        //            //                L_LotTicketEntity ticketEntity = ticketList[i];
                        //            //                if (cancelOrderSnList.Contains(ticketEntity.L_OrderSn))
                        //            //                {
                        //            //                    bdCancelTicketList.Add(ticketEntity);
                        //            //                    ticketList.RemoveAt(i);
                        //            //                }
                        //            //            }
                        //            //            if (bdCancelTicketList.Count > 0)
                        //            //            {
                        //            //                bdLotTicketService.SetStopPrint((int)Lottype.Bd, bdCancelTicketList, (int)TicketStatus.Cancel);
                        //            //            }
                        //            //        }
                        //            //    }
                        //            //    catch (Exception exception)
                        //            //    {
                        //            //        LotMachine.Log.Warn(string.Concat("北单自动设置禁止出票异常。错误信息：", exception));
                        //            //    }
                        //            //}

                        //            //#endregion

                        //            if (ticketList.Count > 0)
                        //            {
                        //                isLoadSuc = true;
                        //                lock (WaitPrintTickets)
                        //                {
                        //                    foreach (L_LotTicketEntity entity in ticketList)
                        //                    {
                        //                        if(!WaitPrintTickets.Contains(entity))
                        //                        {
                        //                            WaitPrintTickets.Enqueue(entity);
                        //                        }
                        //                    }
                        //                }
                        //            }
                        //        }
                        //    }
                        //}
                        //else
                        //{
                        //    //除竟彩以外彩种，按期加载可出票列表
                        //    int TmpHour = DateTime.Now.Hour;
                        //    int TmpMinute = DateTime.Now.Minute;
                        //    int TmpSecond = DateTime.Now.Second;
                        //    if (lotTypeEntity.L_LotId == (int)Lottype.Dl)
                        //    {
                        //        //彩票机返回顶级界面
                        //        //if (TmpHour >= 8 && (TmpMinute == 9 || TmpMinute == 19 || TmpMinute == 29 || TmpMinute == 39 || TmpMinute == 49 || TmpMinute == 59))
                        //        if (TmpHour >= 8 && TmpHour <= 22 && TmpMinute % 10 == 9)
                        //        {
                        //            if(!_isTopGUI)
                        //            {
                        //                if (LotMachine.MachineInfo.M_Status == (int)MachineStatusEnum.Printing)
                        //                {
                        //                    LotMachine.MachineInfo.M_Status = (int)MachineStatusEnum.Stopped;
                        //                    //UpdateMachineMoney();//更新机器额度
                        //                    LotMachine.MachineInfo.M_Status = (int)MachineStatusEnum.Printing;
                        //                }
                        //                //LotMachine.ReturnTopGui();
                        //                LotMachine.ReturnTopGui();//执行2次返回顶级界面
                        //                _isTopGUI = true;
                        //            }
                        //        }
                        //        else
                        //        {
                        //            _isTopGUI = false;
                        //        }
                        //    }
                        //    if (lotTypeEntity.L_LotId == (int)Lottype.Jd)
                        //    {
                        //        //彩票机返回顶级界面
                        //        if (TmpHour >= 8 && TmpHour <= 22 && (TmpMinute % 10 == 5 && TmpSecond > 20 && TmpSecond < 30))
                        //        {
                        //            if (!_isTopGUI)
                        //            {
                        //                if (LotMachine.MachineInfo.M_Status == (int)MachineStatusEnum.Printing)
                        //                {
                        //                    LotMachine.MachineInfo.M_Status = (int)MachineStatusEnum.Stopped;
                        //                    //UpdateMachineMoney();//更新机器额度
                        //                    LotMachine.MachineInfo.M_Status = (int)MachineStatusEnum.Printing;
                        //                }
                        //                LotMachine.ReturnTopGui();//执行2次返回顶级界面
                        //                _isTopGUI = true;
                        //            }
                        //        }
                        //        else
                        //        {
                        //            _isTopGUI = false;
                        //        }
                        //    }
                        //    if (lotTypeEntity.L_LotId == (int)Lottype.Xs)
                        //    {
                        //        //彩票机返回顶级界面
                        //        //if (TmpHour >= 9 && (TmpMinute == 6 || TmpMinute == 16 || TmpMinute == 26 || TmpMinute == 36 || TmpMinute == 46 || TmpMinute == 56) && (TmpSecond>50))
                        //        //if (TmpHour >= 9 && TmpHour <= 22 && ((TmpMinute % 10 == 6 && TmpSecond > 50) || (TmpMinute % 10 == 7) || (TmpMinute % 10 == 8 && TmpSecond < 20)))
                        //        if (TmpHour >= 9 && TmpHour <= 22 && TmpMinute % 10 == 7)
                        //        {
                        //            if (!_isTopGUI)
                        //            {
                        //                if (LotMachine.MachineInfo.M_Status == (int)MachineStatusEnum.Printing)
                        //                {
                        //                    LotMachine.MachineInfo.M_Status = (int)MachineStatusEnum.Stopped;
                        //                    //UpdateMachineMoney();//更新机器额度
                        //                    LotMachine.MachineInfo.M_Status = (int)MachineStatusEnum.Printing;
                        //                }
                        //                LotMachine.ReturnTopGui();//执行返回顶级界面
                        //                _isTopGUI = true;
                        //            }
                        //        }
                        //        else
                        //        {
                        //            _isTopGUI = false;
                        //        }
                        //    }

                        //List<L_ExpectEntity> expectList =
                        //    expectService.GetExpectListByStatus(lotTypeEntity.L_LotId,
                        //                                        (int) ExpectStatus.ChuPiao);
                        //if(expectList.Count>1)
                        //{
                        //    expectList.Sort(new ExpectComparer());
                        //}
                        //Dictionary<string,string> expectSnDictionary=new Dictionary<string, string>();
                        //int expectindex = 1;
                        //foreach (L_ExpectEntity entity in expectList)
                        //{
                        //    expectSnDictionary.Add(entity.E_Expect,expectindex.ToString());
                        //    entity.ExpectSn = expectindex.ToString();
                        //    expectindex++;
                        //}
                        ////L_LotTicketService lotTicketService = new L_LotTicketService();
                        //foreach (L_ExpectEntity expectEntity in expectList)
                        //{
                        //    List<L_LotTicketEntity> ticketList = new List<L_LotTicketEntity>();
                        //    //try
                        //    //{
                        //    //    ticketList = lotTicketService.LoadPrintTicketList(lotTypeEntity.L_LotId, expectEntity.E_Expect, LotMachine.MachineInfo.M_Number, MaxOneLoad);
                        //    //    ticketList.Sort(ticketComparer);
                        //    //}
                        //    //catch (Exception exception1)
                        //    //{
                        //    //    LotMachine.Log.Warn(string.Concat("加载票异常。错误信息：", exception1, " LoadPrintTicketList()参数：lotId:", lotTypeEntity.L_LotId, " expect:", expectEntity.E_Expect, " macNumber:", LotMachine.MachineInfo.M_Number, " num:", MaxOneLoad));
                        //    //}
                        //    //LotMachine.Log.Info(string.Concat("彩种：", lotTypeEntity.L_LotName, "，可出票期号：", expectEntity.E_Expect, "，加载票：", ticketList.Count, "张"));
                        //    if (ticketList != null && ticketList.Count > 0)
                        //    {
                        //        //#region 多乐彩/幸运赛车自动限号
                        //        //if (lotTypeEntity.L_LotId == (int)Lottype.Dl || lotTypeEntity.L_LotId == (int)Lottype.Jd || lotTypeEntity.L_LotId == (int)Lottype.Xs || lotTypeEntity.L_LotId == (int)Lottype.Hd)
                        //        //{
                        //        //    List<M_LimitCodeEntity> limitCodeList = new List<M_LimitCodeEntity>();
                        //        //    M_LimitCodeService limitCodeService = new M_LimitCodeService();
                        //        //    try
                        //        //    {
                        //        //        limitCodeList = limitCodeService.GetLimitCodeList(expectEntity.LotId, expectEntity.E_Expect);
                        //        //        if (limitCodeList.Count > 0)
                        //        //        {
                        //        //            LotMachine.Log.Info(string.Concat("获取自动限号列表：",
                        //        //                                              limitCodeList.Count, "个"));
                        //        //        }
                        //        //    }
                        //        //    catch (Exception exception)
                        //        //    {
                        //        //        LotMachine.Log.Info(string.Concat("获取自动限号列表异常。错误信息：", exception.Message));
                        //        //    }
                        //        //    if (limitCodeList.Count > 0)
                        //        //    {
                        //        //        for (int i = ticketList.Count - 1; i >= 0; i--)
                        //        //        {
                        //        //            bool isautolimit = false;
                        //        //            L_LotTicketEntity ticketEntity = ticketList[i];
                        //        //            foreach (M_LimitCodeEntity limitCodeEntity in limitCodeList)
                        //        //            {
                        //        //                if (limitCodeEntity.C_Lotid == ticketEntity.LotId && limitCodeEntity.C_Playid == ticketEntity.L_PlayId && limitCodeEntity.C_Expect == ticketEntity.L_Expect)
                        //        //                {
                        //        //                    if (limitCodeEntity.C_ModeType == 0)
                        //        //                    {
                        //        //                        //单式号码中存在限号则自动限号当前票
                        //        //                        if (ticketEntity.L_Code.IndexOf(limitCodeEntity.C_Code) > -1)
                        //        //                        {
                        //        //                            isautolimit = true;
                        //        //                            break;
                        //        //                        }
                        //        //                    }
                        //        //                    else
                        //        //                    {
                        //        //                        //复式、胆拖、定位复式号码完全匹配则自动限号当前票
                        //        //                        if (limitCodeEntity.C_Code == ticketEntity.L_Code)
                        //        //                        {
                        //        //                            isautolimit = true;
                        //        //                            break;
                        //        //                        }
                        //        //                    }
                        //        //                }
                        //        //            }
                        //        //            if (isautolimit)
                        //        //            {
                        //        //                //Dl_LotTicketDao psDao = new Dl_LotTicketDao();
                        //        //                //psDao.SetLimitNumber(ticketEntity);
                        //        //                ticketEntity.L_AllowPrint = (int)AllowPrintStatus.NotAllowPrint;
                        //        //                ticketEntity.L_NotifyStatus = (int) NotifyStatus.NotifyAble;
                        //        //                ticketEntity.L_Status = (int) TicketStatus.Limit;
                        //        //                lotTicketService.SetStopPrint(ticketEntity);
                        //        //                ticketList.RemoveAt(i);
                        //        //                LotMachine.Log.Info(string.Concat("彩种：", ticketEntity.L_LotName, " 玩法：", ticketEntity.L_PlayName, " 生产流水号：", ticketEntity.L_TicketSn, " 投注号码：", ticketEntity.L_Code, " 被自动设置为限号"));
                        //        //            }
                        //        //        }
                        //        //    }
                        //        //}
                        //        ////TODO 培训模式机器，无法出过三关玩法
                        //        ///*if (lotTypeEntity.L_LotId == (int)Lottype.Xs)
                        //        //{
                        //        //    for (int i = ticketList.Count - 1; i >= 0; i--)
                        //        //    {
                        //        //        L_LotTicketEntity ticketEntity = ticketList[i];
                        //        //        if (ticketEntity.L_PlayId >= 50637 && ticketEntity.L_PlayId<=50639)
                        //        //        {
                        //        //            //ticketEntity.L_AllowPrint = (int)AllowPrintStatus.NotAllowPrint;
                        //        //            //ticketEntity.L_NotifyStatus = (int)NotifyStatus.NotifyAble;
                        //        //            //ticketEntity.L_Status = (int)TicketStatus.Limit;
                        //        //            //lotTicketService.SetStopPrint(ticketEntity);

                        //        //            //票号、随机码、密码
                        //        //            TicketSimulator.Build(ticketEntity, null);
                        //        //            L_PrintTicketEntity printTicketEntity = new L_PrintTicketEntity();
                        //        //            printTicketEntity.P_Money = ticketEntity.L_Money;
                        //        //            printTicketEntity.P_TicketCode = ticketEntity.L_TicketCode;
                        //        //            printTicketEntity.P_Password = ticketEntity.L_Password;
                        //        //            printTicketEntity.P_RandomCode = ticketEntity.L_RandomCode;
                        //        //            printTicketEntity.P_SaleAddress = "";
                        //        //            printTicketEntity.P_PrnText = "";
                        //        //            printTicketEntity.P_SucTime = ticketEntity.L_SucTime;
                        //        //            lotTicketService.AddPrintTicket(ticketEntity, printTicketEntity);

                        //        //            ticketList.RemoveAt(i);
                        //        //        }
                        //        //    }
                        //        //}*/
                        //        //#endregion

                        //        if (ticketList.Count > 0)
                        //        {
                        //            LotMachine.Log.Info(string.Concat("彩种：", lotTypeEntity.L_LotName, "，可出票期号：", expectEntity.E_Expect, "，加载票：", ticketList.Count, "张"));
                        //            isLoadSuc = true;
                        //            /*从配置文件加载配置*/
                        //            //foreach (L_LotTicketEntity entity in ticketList)
                        //            //{
                        //            //    M_LotPlayModeMapEntity lotPlayMap = LotPlayMapService.GetLotPlayMapByPlayId(entity.L_PlayId);
                        //            //    entity.MacLotId = lotPlayMap.M_MacLotId;
                        //            //    entity.MacPlayId = lotPlayMap.M_MacPlayId;
                        //            //    entity.MacModeId = lotPlayMap.M_MacModeId;
                        //            //}
                        //            /*从配置文件加载配置*/
                        //            lock (WaitPrintTickets)
                        //            {
                        //                foreach (L_LotTicketEntity entity in ticketList)
                        //                {
                        //                    entity.ExpectSn = expectSnDictionary[entity.L_Expect];//设置期号序列号
                        //                    WaitPrintTickets.Enqueue(entity);
                        //                }
                        //            }
                        //        }
                        //    }
                        //    if (ticketList != null && ticketList.Count == 0)
                        //    {
                        //        LotMachine.Log.Debug(string.Concat("彩种：", lotTypeEntity.L_LotName, "，可出票期号：", expectEntity.E_Expect, "，加载票：0张"));
                        //    }
                        //}
                        //}


                        // }
                    }
                    catch (Exception exception2)
                    {
                        LotMachine.Log.Warn(string.Concat("加载票异常。错误信息：", exception2));
                    }
                    if (!isLoadSuc)
                    {
                        //没有加载到数据
                        LotMachine.Log.Info(string.Concat("当前没有可出票数据，等待", WaitTime, "秒后继续进行"));
                        Thread.Sleep(WaitTime * 1000);

                        try
                        {
                            //    if (LotMachine.MachineInfo.AllowSnapJcMatch)
                            //    {
                            //        //抓取竟彩对阵
                            //        if (_jcMatchSnapService != null && _jcMatchSnapService.AllowSnap())
                            //        {
                            //            if (LastSucTicket != null && DateTime.Now.Subtract(LastSucTicket.L_SucTime).TotalSeconds < 5)
                            //            {
                            //                Wait4Job.Reset();
                            //                Wait4Job.WaitOne(TimeSpan.FromSeconds(5));
                            //            }
                            //            bool snapJzMatch = _jcMatchSnapService.SnapJzMatch();
                            //            if (!snapJzMatch)
                            //            {
                            //                Wait4Job.Reset();
                            //                Wait4Job.WaitOne(TimeSpan.FromSeconds(10));
                            //            }
                            //            else
                            //            {
                            //                if (!_isStop)
                            //                {
                            //                    Wait4Job.Reset();
                            //                    Wait4Job.WaitOne(TimeSpan.FromSeconds(3));
                            //                    bool snapJlMatch = _jcMatchSnapService.SnapJlMatch();
                            //                    if (!snapJlMatch)
                            //                    {
                            //                        Wait4Job.Reset();
                            //                        Wait4Job.WaitOne(TimeSpan.FromSeconds(10));
                            //                    }
                            //                }
                            //            }
                            //        }
                            //        else
                            //        {
                            //            Wait4Job.Reset();
                            //            Wait4Job.WaitOne(TimeSpan.FromSeconds(10));
                            //        }
                            //    }
                            //    else if (LotMachine.MachineInfo.AllowSnapZcPs)//抓取足彩和排三限号列表
                            //    {
                            //        if (_zcMatchSnapService != null && _zcMatchSnapService.AllowSnap())
                            //        {
                            //            if (LastSucTicket != null && DateTime.Now.Subtract(LastSucTicket.L_SucTime).TotalSeconds < 5)
                            //            {
                            //                Wait4Job.Reset();
                            //                Wait4Job.WaitOne(TimeSpan.FromSeconds(5));
                            //            }

                            //            if (!_isStop)
                            //            {
                            //                //排列20:00-20:10不抓取
                            //                if (DateTime.Now.Hour != 20 || DateTime.Now.Minute > 9)
                            //                {
                            //                    string address = System.Configuration.ConfigurationManager.AppSettings.Get("Address");
                            //                    if (address == null) address = "";
                            //                    if (address.IndexOf("江西") > -1)
                            //                    {
                            //                        //只抓江西的限号数据
                            //                        _zcMatchSnapService.SnapLimitOfPs();
                            //                    }
                            //                }

                            //            }

                            //            //_zcMatchSnapService.Snap();
                            //            for (int i = 1; i <= 4; i++)
                            //            {
                            //                if (_isStop)
                            //                    break;
                            //                _zcMatchSnapService.SnapMatchOfSf(i);
                            //                Thread.Sleep(2000);
                            //            }
                            //            for (int i = 1; i <= 4; i++)
                            //            {
                            //                if (_isStop)
                            //                    break;
                            //                _zcMatchSnapService.SnapMatchOfBq(i);
                            //                Thread.Sleep(2000);
                            //            }
                            //            for (int i = 1; i <= 4; i++)
                            //            {
                            //                if (_isStop)
                            //                    break;
                            //                _zcMatchSnapService.SnapMatchOfJq(i);
                            //                Thread.Sleep(2000);
                            //            }
                            //        }
                            //        else
                            //        {
                            //            Wait4Job.Reset();
                            //            Wait4Job.WaitOne(TimeSpan.FromSeconds(10));
                            //        }
                            //    }
                            //    else 
                            if (LotMachine.MachineInfo.AllowSnapOpenCode)//抓取多乐彩开奖结果报表
                            {
                                if (_openCodeSnapService != null && _openCodeSnapService.AllowSnap())
                                {
                                    _openCodeSnapService.SnapOpenCode();
                                }
                                Wait4Job.Reset();
                                Wait4Job.WaitOne(TimeSpan.FromSeconds(5));
                            }
                            //else
                            //{
                            //    Wait4Job.Reset();
                            //    Wait4Job.WaitOne(TimeSpan.FromSeconds(10));
                            //}
                        }
                        catch (Exception exSnap)
                        {
                            LotMachine.Log.Warn(string.Concat("抓取异常，休眠10秒。错误信息：", exSnap));
                            Thread.Sleep(10000);
                        }

                        UpdateEnabledLotTypeWaitTime += WaitTime;
                        if (UpdateEnabledLotTypeWaitTime >= UpdateEnabledLotTypeInterval)
                        {
                            UpdateEnabledLotType();
                            UpdateEnabledLotTypeWaitTime = 0;
                        }
                        continue;
                        //Application.DoEvents();
                    }
                }
                else
                {
                    //bool isCP = true;
                    //int r1 = new Random().Next(1, 600001);

                    //if (DateTime.Now.Hour >= 10 && DateTime.Now.Hour < 11) 
                    //{   
                    //    if (r1 > 200000)      //60分钟内有20分钟有效时间，2-4票，60分钟出60票，平均1票/分
                    //    {
                    //        isCP = false;
                    //    }
                    //}
                    //else if (DateTime.Now.Hour >= 11 && DateTime.Now.Hour < 14)
                    //{
                    //    if (r1 > 250000)      //60分钟内有25分钟有效时间，2-4票，60分钟出75票，平均1.5票/分，3小时共225票
                    //    {
                    //        isCP = false;
                    //    }
                    //}
                    //else if (DateTime.Now.Hour >= 14 && DateTime.Now.Hour < 17)
                    //{
                    //    if (r1 > 100000)      //60分钟内有10分钟有效时间，2-4票，60分钟出30票，平均0.5票/分，3小时共90票
                    //    {
                    //        isCP = false;
                    //    }
                    //}
                    //else if (DateTime.Now.Hour >= 17 && DateTime.Now.Hour < 21)
                    //{
                    //    if (r1 > 300000)      //60分钟内有30分钟有效时间，2-4票，60分钟出90票，平均2票/分，4小时共360票
                    //    {
                    //        isCP = false;
                    //    }
                    //}
                    //else
                    //{
                    //    if (r1 > 150000)      //60分钟内有15分钟有效时间，2-4票，60分钟出45票，平均0.8票/分
                    //    {
                    //        isCP = false;
                    //    }
                    //}

                    //if (isCP)
                    //{
                    L_LotTicketEntity ticket;
                    DecodePrintData decodePrintData = new DecodePrintData();
                    lock (WaitPrintTickets)
                    {
                        ticket = WaitPrintTickets.Dequeue();
                    }
                    if (ticket == null)
                    {
                        continue;
                    }

                    //出票前清掉指令，防止执行历史指令
                    try
                    {
                        //获取指令
                        A10009GetCommand pack = new A10009GetCommand();
                        pack.AgentId = LotMachine.MachineInfo.M_Number;
                        pack.Salt = LotMachine.MachineInfo.M_Salt;
                        A10009GetCommandRet packRet = PackManager.Instance.Send(pack) as A10009GetCommandRet;
                        if (packRet.Code > 0)
                        {
                            LotMachine.Log.Info("出票前清除指令:" + packRet.Command);
                        }
                    }
                    catch (Exception ex)
                    {
                        LotMachine.Log.Info("出票前清除指令失败！" + ex.ToString());
                    }

                    //根据ticket.L_Code来判断任务类型
                    if (ticket.L_Code == "recharge")   //充值任务--------------------------------------------------------------------
                    {
                        try
                        {
                            OnPrinting(ticket);

                            LotMachine.Log.Info("开始充值:" + ticket.L_TicketSn);

                            LotMachine.Recharge(Convert.ToInt32(ticket.L_Money));
                        }
                        catch (Exception ex)
                        {
                            LotMachine.Log.Warn(string.Concat("充值异常：", ex.Message));
                        }
                        finally
                        {
                            LotMachine.Log.Info("结束充值");
                            OnPrinted(ticket);
                        }
                    }
                    else if (ticket.L_Code == "getbouns")   //兑奖任务--------------------------------------------------------------------
                    {
                        try
                        {
                            OnPrinting(ticket);

                            LotMachine.Log.Info("开始兑奖:" + ticket.L_TicketSn);

                            LotMachine.Encash(ticket);
                        }
                        catch (Exception ex)
                        {
                            LotMachine.Log.Warn(string.Concat("兑奖异常：", ex.Message));
                        }
                        finally
                        {
                            //回写
                            try
                            {
                                A10010NotifyBonus pack = new A10010NotifyBonus();
                                pack.AgentId = LotMachine.MachineInfo.M_Number;
                                pack.Salt = LotMachine.MachineInfo.M_Salt;
                                pack.Ticket = ticket;
                                A10010NotifyBonusRet packRet = PackManager.Instance.Send(pack) as A10010NotifyBonusRet;
                                if (packRet.Code > 0)
                                {
                                    LotMachine.Log.Info("兑奖回写成功");
                                }
                            }
                            catch (Exception ex)
                            {
                                LotMachine.Log.Info("兑奖回写失败！" + ex.ToString());
                            }

                            OnPrinted(ticket);
                        }
                    }
                    else   //出票任务------------------------------------------------------------------------------------------------------
                    {
                        try
                        {
                            OnPrinting(ticket);

                            PrintOneTicket(ticket, decodePrintData);
                            //LotMachine.MachineInfo.M_LastPrintCounter = LotMachine.VirtualPrinter.LastPrintCounter;

                            //不能只空闲的时候抓，因为可能刚好到抓的时候，有票过来
                            try
                            {
                                if (LotMachine.MachineInfo.AllowSnapOpenCode)//抓取多乐彩开奖结果报表
                                {
                                    if (_openCodeSnapService != null && _openCodeSnapService.AllowSnap())
                                    {
                                        _openCodeSnapService.SnapOpenCode();
                                    }
                                }
                            }
                            catch (Exception exSnap)
                            {
                                LotMachine.Log.Warn(string.Concat("抓取异常，休眠10秒。错误信息：", exSnap));

                            }
                        }
                        catch (Exception ex)
                        {
                            LoggingService.Info(string.Concat("出票异常。生产流水号：", ticket.L_TicketSn, " 错误信息：", ex));
                            LotMachine.Log.Warn(string.Concat("出票异常。生产流水号：", ticket.L_TicketSn, " 错误信息：", ex.Message));
                            ReportError(ticket, decodePrintData, ex.Message, ex.ToString());
                        }
                        //}
                        //else
                        //{
                        //    int sleeptime = new Random().Next(5000, 35000); //休眠平均20秒
                        //    LotMachine.Log.Info("不让出票，我很生气，我需要冷静"+sleeptime.ToString()+"毫秒");
                        //    Thread.Sleep(sleeptime);
                        //}


                    }


                    //StatusBarService.SetMessage("完成打印" + ticket.L_TicketSn);
                    //StatusBarService.ShowErrorMessage("完成打印" + ticket.L_TicketSn);
                    //StatusBarService.SetInsertMode(true);
                    //StatusBarService.SetCaretPosition(1,2,3);
                    //i++;
                }
            }

            LotMachine.Log.Debug("更新机器状态为停止状态……");
            try
            {
                UpdateMachineStatus(MachineStatusEnum.Stopped);
            }
            catch
            {
                LotMachine.Log.Warn("更新机器状态失败！");
            }
            LoggingService.Info(string.Concat(LotMachine.MachineInfo.M_Number, "停止出票"));
        }

        /// <summary>
        /// 从休眠状态唤醒
        /// </summary>
        public void Wakeup()
        {
            try
            {
                LotMachine.Log.Info("从休眠状态唤醒");
                if (!_isStop && LotMachine.MachineInfo.M_Status == (int)MachineStatusEnum.Printing)
                {
                    Wait4Job.Set();
                }
                //_manualResetEvent.Set();
            }
            catch (Exception ex)
            {
                LotMachine.Log.Warn(ex);
            }
        }
        //最后一张成功的票
        private L_LotTicketEntity LastSucTicket = null;
        //最后一次清除奖期已更新时间
        private DateTime LastClearExpectTime = new DateTime(1900, 1, 1);
        //当前正在打印的票
        public L_LotTicketEntity CurrentTicket = null;
        private int _clearMoneyWaitTicketNum = 0;
        //当期是否有错票
        public bool HasErrorTicket = false;
        private int lastRandomWaitTime = 0;
        private int _jcScanTicketInterval = -1;
        private int _jcTicketInterval = -1;
        private int _jcBTicketInterval = -1;
        private int _jcClearExpectInterval = -1;
        private int _fuShiTicketInterval = -1;
        private int _playChangeInterval = -1;
        private int _TicketInterval = -1;
        private int _BTicketInterval = -1;
        /// <summary>
        /// 竟彩扫描票间隔
        /// </summary>
        public int JcScanTicketInterval
        {
            get
            {
                if (_jcScanTicketInterval < 0)
                {
                    try
                    {
                        _jcScanTicketInterval = int.Parse(ConfigurationManager.AppSettings["JcScanTicketInterval"]);
                    }
                    catch (Exception ex)
                    {
                        LotMachine.Log.Info(string.Concat("读取JcScanTicketInterval配置异常", ex.Message));
                        _jcScanTicketInterval = 500;
                    }
                }
                return _jcScanTicketInterval;
            }
        }
        /// <summary>
        /// 竟彩票间隔
        /// </summary>
        public int JcTicketInterval
        {
            get
            {
                if (_jcTicketInterval < 0)
                {
                    try
                    {
                        _jcTicketInterval = int.Parse(ConfigurationManager.AppSettings["JcTicketInterval"]);
                    }
                    catch (Exception ex)
                    {
                        LotMachine.Log.Info(string.Concat("读取JcTicketInterval配置异常", ex.Message));
                        _jcTicketInterval = 2500;
                    }
                }
                return _jcTicketInterval;
            }
        }
        /// <summary>
        /// 竟彩大额票间隔
        /// </summary>
        public int JcBTicketInterval
        {
            get
            {
                if (_jcBTicketInterval < 0)
                {
                    try
                    {
                        _jcBTicketInterval = int.Parse(ConfigurationManager.AppSettings["JcBTicketInterval"]);
                    }
                    catch (Exception ex)
                    {
                        LotMachine.Log.Info(string.Concat("读取JcBTicketInterval配置异常", ex.Message));
                        _jcBTicketInterval = 3000;
                    }
                }
                return _jcBTicketInterval;
            }
        }
        /// <summary>
        /// 竟彩自动清除奖期已更新间隔
        /// </summary>
        public int JcClearExpectInterval
        {
            get
            {
                if (_jcClearExpectInterval < 0)
                {
                    try
                    {
                        _jcClearExpectInterval = int.Parse(ConfigurationManager.AppSettings["JcClearExpectInterval"]);
                    }
                    catch (Exception ex)
                    {
                        LotMachine.Log.Info(string.Concat("读取JcClearExpectInterval配置异常", ex.Message));
                        _jcClearExpectInterval = 30;
                    }
                }
                return _jcClearExpectInterval;
            }
        }
        /// <summary>
        /// 复式票间隔
        /// </summary>
        public int FuShiTicketInterval
        {
            get
            {
                if (_fuShiTicketInterval < 0)
                {
                    try
                    {
                        _fuShiTicketInterval = int.Parse(ConfigurationManager.AppSettings["FuShiTicketInterval"]);
                    }
                    catch (Exception ex)
                    {
                        LotMachine.Log.Info(string.Concat("读取FuShiTicketInterval配置异常", ex.Message));
                        _fuShiTicketInterval = 800;
                    }
                }
                return _fuShiTicketInterval;
            }
        }
        /// <summary>
        /// 玩法切换间隔
        /// </summary>
        public int PlayChangeInterval
        {
            get
            {
                if (_playChangeInterval < 0)
                {
                    try
                    {
                        _playChangeInterval = int.Parse(ConfigurationManager.AppSettings["PlayChangeInterval"]);
                    }
                    catch (Exception ex)
                    {
                        LotMachine.Log.Info(string.Concat("读取PlayChangeInterval配置异常", ex.Message));
                        _playChangeInterval = 2000;
                    }
                }
                return _playChangeInterval;
            }
        }

        /// <summary>
        /// 票间隔
        /// </summary>
        public int TicketInterval
        {
            get
            {
                if (_TicketInterval < 0)
                {
                    try
                    {
                        _TicketInterval = int.Parse(ConfigurationManager.AppSettings["TicketInterval"]);
                    }
                    catch (Exception ex)
                    {
                        LotMachine.Log.Info(string.Concat("读取TicketInterval配置异常", ex.Message));
                        _TicketInterval = 2500;
                    }
                }
                return _TicketInterval;
            }
        }
        /// <summary>
        /// 大额票间隔
        /// </summary>
        public int BTicketInterval
        {
            get
            {
                if (_BTicketInterval < 0)
                {
                    try
                    {
                        _BTicketInterval = int.Parse(ConfigurationManager.AppSettings["BTicketInterval"]);
                    }
                    catch (Exception ex)
                    {
                        LotMachine.Log.Info(string.Concat("读取BTicketInterval配置异常", ex.Message));
                        _BTicketInterval = 3000;
                    }
                }
                return _BTicketInterval;
            }
        }
        private const string Fushiplays = "70502,70402,70302,70202,70203,70212,70222,70232,70206,70204,70214,70224,70205,70215,70225,70102,70103,70112,70113,70122,60302,60202,60102,60112";
        private void PrintOneTicket(L_LotTicketEntity ticket, DecodePrintData decodePrintData)
        {
            CurrentTicket = ticket;
            HasErrorTicket = false;
            Random random = new Random();

            //SetIsScan(ticket, LotMachine.MachineInfo);//设置是否扫描出票

            SetIsClearExpect(ticket);//设置是否出票前清除奖期已更新对话框


            if (LotMachine.MachineInfo.M_IsAutoClearTotal)
            {
                //被中心检测出异常终端，暂时停止清除合计
                //清除合计：判断上一次出票时间，如果超过设定值，就清一次合计，否则就随机1-5票清一次
                if (LastSucTicket == null || DateTime.Now.Subtract(LastSucTicket.L_SucTime).TotalSeconds > 2 * 60)
                {

                    LotMachine.ClearMahineMoney();
                    _clearMoneyWaitTicketNum = random.Next(1, 6);
                    LotMachine.Log.Info("出票间隔超过2分钟，清除合计。" + _clearMoneyWaitTicketNum.ToString() + "票后再清除");
                }
                else
                {
                    _clearMoneyWaitTicketNum--;
                    if (_clearMoneyWaitTicketNum == 0)
                    {
                        LotMachine.ClearMahineMoney();
                        _clearMoneyWaitTicketNum = random.Next(1, 6);
                        LotMachine.Log.Info("清除合计。" + _clearMoneyWaitTicketNum.ToString() + "票后再清除");
                    }
                }
            }
            


            if (ticket.LotId == (int)Lottype.Xs || ticket.LotId == (int)Lottype.Dl || ticket.LotId == (int)Lottype.Jd || ticket.LotId == (int)Lottype.Hd)
            {
                if (LastSucTicket == null)
                {
                    LotMachine.ReturnTopGui();//执行返回顶级界面
                    //if (ticket.LotId == (int)Lottype.Xs)
                    //{
                    //    LotMachine.ReturnTopGui();
                    //}
                }
                else
                {
                    if (LastSucTicket.L_Expect != ticket.L_Expect)
                    {
                        LotMachine.ReturnTopGui();//执行返回顶级界面
                        //if(ticket.LotId == (int)Lottype.Xs)
                        //{
                        //    LotMachine.ReturnTopGui();
                        //}
                    }
                }
            }
            if (ticket.LotId >= 601 && ticket.LotId <= 705)
            {
                if (LastSucTicket == null)
                {
                    LotMachine.ReturnTopGui();//执行返回顶级界面
                }
            }


            if (LastSucTicket != null)
            {
                

                //if(LastSucTicket.LotId==911 ||LastSucTicket.LotId==951||LastSucTicket.LotId==971)
                //{
                //    string address = ConfigurationManager.AppSettings["Address"];
                //    if (address.IndexOf("天津") >= 0 || address.IndexOf("湖北") >= 0)
                //    {
                //        //天津出票点
                //        if (DateTime.Now.Subtract(LastSucTicket.L_SucTime).TotalSeconds <= 6)
                //        {
                //            int r2 = 0;
                //            if (LastSucTicket.L_SpendTime < 5000)   //新机器出票时间会小于5秒
                //            {
                //                //r2 = random.Next(5000, 9000);   //5票/分   12秒一票  平均休眠7秒，出票时间算5秒 
                //                r2 = random.Next(8000, 12000);   //4票/分
                //                //r2 = random.Next(6500, 10500);   //4-5票/分
                //            }
                //            else
                //            {
                //                int r1 = random.Next(0, 100000);
                //                int i = 0;
                //                if (r1 < 80000)   //80%的概率走这条分支
                //                {
                //                    //r2 = random.Next(2000, 6000);//5票/分
                //                    r2 = random.Next(5000, 9000);//4票/分
                //                    //r2 = random.Next(3500, 7500);//4-5票/分
                //                    if (lastRandomWaitTime > 0)
                //                    {
                //                        while (i < 100 && Math.Abs(r2 - lastRandomWaitTime) < 1000)    //尝试100次，尽量让随机时间与上次的随机时间相差1秒以上
                //                        {
                //                            //r2 = random.Next(2000, 6000);  //5票/分
                //                            r2 = random.Next(5000, 9000);  //4票/分
                //                            //r2 = random.Next(3500, 7500);//4-5票/分
                //                            i++;
                //                        }
                //                    }
                //                }
                //                else
                //                {
                //                    //r2 = random.Next(14000, 28000);//16-30秒/票
                //                    //r2 = random.Next(10000, 18000);//12-20秒/票
                //                    //r2 = random.Next(8000, 14000);//10-16秒/票
                //                    //r2 = random.Next(2000, 6000);//5票/分
                //                    r2 = random.Next(5000, 9000);//4票/分
                //                    //r2 = random.Next(3500, 7500);//4-5票/分
                //                    if (lastRandomWaitTime > 0)
                //                    {
                //                        while (i < 100 && Math.Abs(r2 - lastRandomWaitTime) < 1000)
                //                        {
                //                            //r2 = random.Next(2000, 6000);//5票/分
                //                            r2 = random.Next(5000, 9000);//4票/分
                //                            //r2 = random.Next(3500, 7500);//4-5票/分
                //                            i++;
                //                        }
                //                    }
                //                }
                //            }

                //            //判断是不是截止前，截止前不休眠
                //            DateTime earlistEndTime = GetEarliestEndTime();
                //            TimeSpan timeSpan = earlistEndTime.Subtract(DateTime.Now);
                //            //截止前1个半小时以内
                //            if (timeSpan.TotalMinutes <= 90)
                //            {
                //                r2 -= random.Next(3000,7000); //6票   
                //            }

                //            lastRandomWaitTime = r2;
                //            LotMachine.Log.Info("随机休眠" + r2 + "毫秒");
                //            Wait(r2);
                //            //Wait(2000);   //至少要休眠1秒
                //        }


                //        /*int waitinterval = 500;
                //        LotMachine.Log.Info("连续出票，等待" + waitinterval + "毫秒再出当前票");
                //        Wait(waitinterval);*/
                //    }
                //    else 
                //    {
                //        //江西出票点
                //        if (DateTime.Now.Subtract(LastSucTicket.L_SucTime).TotalSeconds <= 3)
                //        {
                //            /*Random random = new Random();
                //            int r1 = random.Next(1000, 11000);
                //            if (lastRandomWaitTime > 0)
                //            {
                //                int i = 0;
                //                while (i < 100 && Math.Abs(r1 - lastRandomWaitTime) < 2000)
                //                {
                //                    r1 = random.Next(1000, 11000);
                //                    i++;
                //                }
                //            }
                //            lastRandomWaitTime = r1;
                //            Wait(r1);*/


                //            //int waitinterval = 500;
                //            //LotMachine.Log.Info("连续出票，等待" + waitinterval + "毫秒再出当前票");
                //            //Wait(waitinterval);
                //            if(ticket.IsUseScanner)
                //            {
                //                LotMachine.Log.Info("扫描连续出票，等待" + JcScanTicketInterval + "毫秒再出当前票");
                //                Wait(JcScanTicketInterval);
                //            }
                //            else
                //            {
                //                if ((LastSucTicket.L_Mutiple > 1 || LastSucTicket.L_Money > 500))
                //                {
                //                    LotMachine.Log.Info("键码出票前一张是倍投票或大额票，等待" + JcBTicketInterval + "毫秒再出当前票");
                //                    Wait(JcBTicketInterval);//前一张是倍投票，等待1秒再出下一张
                //                }
                //                else
                //                {
                //                    //int waitinterval = 2500;
                //                    LotMachine.Log.Info("键码连续出票，等待" + JcTicketInterval + "毫秒再出当前票");
                //                    Wait(JcTicketInterval);
                //                }
                //            }
                //        }
                //    }
                //}
                //else
                //{
                //    //if (DateTime.Now.Subtract(LastSucTicket.L_SucTime).TotalSeconds <= 3)
                //    //{
                //    //    if ((LastSucTicket.L_Mutiple > 1 || LastSucTicket.L_Money > 500))
                //    //    {
                //    //        LotMachine.Log.Info("键码出票前一张是倍投票或大额票，等待" + BTicketInterval + "毫秒再出当前票");
                //    //        Wait(BTicketInterval);//前一张是倍投票，等待1秒再出下一张
                //    //    }
                //    //    else
                //    //    {
                //    //        int waitinterval = TicketInterval;
                //    //        if (Fushiplays.IndexOf(ticket.L_PlayId.ToString()) > -1 && waitinterval<800)
                //    //        {
                //    //            waitinterval = FuShiTicketInterval;//800;
                //    //        }
                //    //        if(LastSucTicket.L_PlayId!=ticket.L_PlayId)
                //    //        {
                //    //            waitinterval = PlayChangeInterval;//2000;
                //    //        }

                //    //        LotMachine.Log.Info("键码连续出票，等待" + waitinterval + "毫秒再出当前票");
                //    //        Wait(waitinterval);
                //    //    }
                //    //}

                int min = LocalConfigUtil.TicketInterval - 500;
                int max = LocalConfigUtil.TicketInterval + 500;
                int r = random.Next(min, max); 
                LotMachine.Log.Info("随机休眠" + r + "毫秒--------------------------");
                Wait(r);
                //}


            }

            //出票前判断是否已截止，如果截止则设置为超时未出票，暂时只对多乐彩/幸运赛车
            if (DateTime.Now > ticket.L_EndTime)
            {
                //ticket.L_Status = (int)TicketStatus.Default;
                //ticket.L_NotifyStatus = (int)NotifyStatus.Default;
                //ticket.L_AllowPrint = (int)AllowPrintStatus.NotAllowPrint;

                //if (ticket.LotId == (int)Lottype.Bd)
                //{
                //    new BdL_LotTicketService().SetStopPrint(ticket);
                //}
                //else if (ticket.LotId == (int)Lottype.Jz || ticket.LotId == (int)Lottype.Jl || ticket.LotId == (int)Lottype.Jm)
                //{
                //    new JcL_LotTicketService().SetStopPrint(ticket);
                //}
                //else
                //{
                //    new L_LotTicketService().SetStopPrint(ticket);
                //}

                LotMachine.Log.Info(string.Concat("期号：", ticket.L_Expect, " 生产流水号：", ticket.L_TicketSn, " 金额：", ticket.L_Money, " 截止时间：", ticket.L_EndTime, " 已截止未出票"));
                OnPrinted(ticket);
                return;
            }

            DateTime beginTime = DateTime.Now;

            if (!LotMachine.MachineInfo.M_IsSimulate)
            {
                LotMachine.Print(ticket, decodePrintData);
            }
            else
            {
                //用于测试，构造出票成功
                decodePrintData.DecodeSuccess = true;
                ticket.L_TicketCode = DateTime.Now.ToString("yyyyMMddHHmmss");
                TicketSimulator.Build(ticket, decodePrintData);
                decodePrintData.L_PrintTicketEntity.P_PrnText = "test";
                decodePrintData.L_PrintTicketEntity.P_TicketCode = ticket.L_TicketCode;
                decodePrintData.L_PrintTicketEntity.L_CodeReference = ticket.L_CodeReference;
                decodePrintData.L_PrintTicketEntity.L_CodeRate = ticket.L_CodeRate;
                decodePrintData.L_PrintTicketEntity.P_SucTime = DateTime.Now;
                if (ticket.L_PlayId == 70111 || ticket.L_PlayId == 70112 || ticket.L_PlayId == 70113)
                {
                    ticket.L_AddType = random.Next(0, 5);
                }
            }

            DateTime endTime = DateTime.Now;
            int totalTime = (int)((endTime.Subtract(beginTime)).TotalMilliseconds);
            ticket.L_SpendTime = totalTime;

            if (decodePrintData.DecodeSuccess)
            {
                ////保存电子票文件
                //string ticketFilePath = FileService.GetTicketFilePath(LotMachine.MachineInfo.M_Number, ticket.L_TicketCode);
                //File.WriteAllText(ticketFilePath, decodePrintData.L_PrintTicketEntity.P_PrnText);
                //LotMachine.Log.Debug(string.Concat("保存电子票文件：", ticketFilePath));
                //if (LotMachine.MachineInfo.M_AllowPaperout)
                //{
                //    LotMachineService.PrintETicket(LotMachine.MachineInfo.M_Number, decodePrintData.InputData.CaptureDataBytes);
                //}
                try
                {
                    ////票号数据入库
                    //L_LotTicketService lotTicketService = new L_LotTicketService();
                    ////throw new Exception("System.Data.SqlClient.SqlException: A transport-level error has occurred when receiving results from the server");
                    //lotTicketService.AddPrintTicket(ticket, decodePrintData.L_PrintTicketEntity);
                    //LotMachine.Log.Debug(string.Concat("票号更新到数据库成功。生产流水号：", ticket.L_TicketSn, " 票号：", ticket.L_TicketCode, " 密码：", ticket.L_Password, " 出票时间：", ticket.L_SucTime));


                    //通知票号
                    A10002NotifyTicket pack = new A10002NotifyTicket();
                    pack.AgentId = LotMachine.MachineInfo.M_Number;
                    pack.Salt = LotMachine.MachineInfo.M_Salt;
                    ticket.L_TicketCode = decodePrintData.L_PrintTicketEntity.P_TicketCode;
                    ticket.L_CodeRate = decodePrintData.L_PrintTicketEntity.L_CodeRate;
                    ticket.L_CodeReference = decodePrintData.L_PrintTicketEntity.L_CodeReference;   //篮球
                    ticket.L_SucTime = decodePrintData.L_PrintTicketEntity.P_SucTime;
                    ticket.L_PrnText = decodePrintData.L_PrintTicketEntity.P_PrnText;
                    ticket.L_Status = (int)TicketStatus.Suc;
                    ticket.L_LimitType = 0;
                    pack.Ticket = ticket;

                    int retry = 0;
                    while (retry <3)
                    {
                        A10002NotifyTicketRet packRet = PackManager.Instance.Send(pack) as A10002NotifyTicketRet;
                        if (packRet.Code > 0)
                        {
                            break;
                        }

                        retry++;
                        if (retry==3)
                        {
                            LotMachine.Log.Warn("【操作提示】：请尝试点击“重新通知”！");
                            throw new Exception("票号通知失败（已自动尝试3次），" + packRet.Code.ToString() + " " + packRet.Message);
                        }

                        Thread.Sleep(retry * 1000);
                    }

                    //删除last目录下最后一个文件
                    LotMachine.VirtualPrinter.DeleteLastFile();

                    TotalMoney += ticket.L_Money;
                    TotalTicket += 1;
                    //LotMachine.Log.Info("报告出票完毕");

                    LotMachine.Log.Info(string.Concat("票号通知成功：", ticket.L_TicketSn, " 彩种：", ticket.L_LotName, ticket.LotId, "玩法：", ticket.L_PlayName, ticket.L_PlayId, "倍数：", ticket.L_Mutiple, "金额：", ticket.L_Money, " 出票耗时为：", totalTime.ToString("0"), "毫秒 ", ticket.IsUseScanner ? "扫描出票" : "键码出票"));

                    ticket.L_SucTime = DateTime.Now;//使用电脑时间判断两张票的间隔
                    LastSucTicket = ticket;
                    //OnPrinted(ticket);
                }
                catch (Exception exception)
                {
                    //FileService.SavePrintInfoToLocalFile(ticket, decodePrintData.L_PrintTicketEntity);
                    LotMachine.Log.Warn(string.Concat("票号通知失败。生产流水号：", ticket.L_TicketSn, " 票号：", ticket.L_TicketCode, " 密码：", ticket.L_Password));
                    ReportError(ticket, decodePrintData, string.Concat("通知票号失败：", exception.Message), exception.ToString());

                }
                OnPrinted(ticket);
            }
            else
            {
                LotMachine.Log.Warn(string.Concat("解析电子票失败。生产流水号：", ticket.L_TicketSn, " 错误信息：", decodePrintData.ErrorMessage));
                ReportError(ticket, decodePrintData, decodePrintData.ErrorMessage, decodePrintData.ErrorMessage);

                //string screenPicStr = "";
                //try
                //{
                //    DateTime startScreenCapture = DateTime.Now;
                //    screenPicStr = ScreenCaptureUtil.MachineScreenCaptureBase64(LotMachine.MachineInfo.M_SocketIp,
                //                                                                 LotMachine.MachineInfo.M_Number);
                //    DateTime endScreenCapture = DateTime.Now;
                //    LotMachine.Log.Info(string.Concat("彩票机截屏完成。耗时：", endScreenCapture.Subtract(startScreenCapture).TotalMilliseconds,"毫秒"));
                //}
                //catch (Exception ex)
                //{
                //    LotMachine.Log.Info(string.Concat("彩票机截屏错误：",ex));
                //}
                //ReportError(ticket, decodePrintData, decodePrintData.ErrorMessage, screenPicStr);
            }
        }

        public void ReGetdata(L_LotTicketEntity ticketEntity, DecodePrintData decodePrintData)
        {
            if (LotMachine.MachineInfo.M_Status == (int)MachineStatusEnum.Printing)
            {
                LotMachine.Log.Info("出票中不能执行二次获取");
                return;
            }
            LotMachine.Log.Info("执行二次获取数据……");
            LotMachine.ReGetdata(ticketEntity, decodePrintData);
            //if (!decodePrintData.DecodeSuccess)
            //{
            //    LotMachine.Log.Info(string.Concat("二次获取数据解析失败，请核对错票"));
            //    if (decodePrintData.InputData.CaptureDataBytes.Length > 0)
            //    {
            //        //保存错票电子票文件
            //        string errorticketFilePath = FileService.GetErrorTicketFilePath(LotMachine.MachineInfo.M_Number, ticketEntity.L_TicketSn + "_" + DateTime.Now.ToString("yyyyMMddHHmmss"));
            //        //decodePrintData.L_PrintTicketEntity.P_PrnText =
            //        //    TicketTextUtil.CompressAndEncrypt(decodePrintData.InputData.CaptureDataBytes);
            //        File.WriteAllText(errorticketFilePath, decodePrintData.L_PrintTicketEntity.P_PrnText);
            //        LotMachine.Log.Info(string.Concat("保存电子票文件：", errorticketFilePath));
            //        //LotMachineService.PrinterClient.AddFile(errorticketFilePath);
            //        LotMachineService.PrintETicket(LotMachine.MachineInfo.M_Number, errorticketFilePath, true);
            //        //保存错票信息到错票表
            //        //L_ErrorTicketService errorTicketService = new L_ErrorTicketService();
            //        //errorTicketService.AddErrorTicket(ticketEntity, decodePrintData.L_PrintTicketEntity);
            //        //LotMachine.Log.Info(string.Concat("错票信息入库，打印并保存错票文件：", errorticketFilePath));
            //    }
            //    Stop();
            //}
            //else
            //{
            //    LotMachine.Log.Info(string.Concat("二次获取数据解析成功"));
            //    //ticketEntity.L_TicketCode = decodePrintData.L_PrintTicketEntity.P_TicketCode;
            //    //ticketEntity.L_RandomCode = decodePrintData.L_PrintTicketEntity.P_RandomCode;
            //    //ticketEntity.L_Password = decodePrintData.L_PrintTicketEntity.P_Password;
            //    //ticketEntity.L_SucTime = decodePrintData.L_PrintTicketEntity.P_SucTime;
            //    //ticketEntity.L_Status = (int)TicketStatus.Suc;
            //    //ticketEntity.L_NotifyStatus = (int)NotifyStatus.NotifyAble;
            //    //保存电子票文件
            //    string ticketFilePath = FileService.GetTicketFilePath(LotMachine.MachineInfo.M_Number, ticketEntity.L_TicketCode); ;
            //    File.WriteAllText(ticketFilePath, decodePrintData.L_PrintTicketEntity.P_PrnText);
            //    LotMachine.Log.Debug(string.Concat("保存电子票文件：", ticketFilePath));
            //    if (LotMachine.MachineInfo.M_AllowPaperout)
            //    {
            //        //LotMachineService.PrinterClient.AddFile(ticketFilePath);
            //        LotMachineService.PrintETicket(LotMachine.MachineInfo.M_Number, ticketFilePath, true);
            //    }



            //        //通知票号
            //        A10002NotifyTicket pack = new A10002NotifyTicket();
            //        pack.AgentId = LotMachine.MachineInfo.M_Number;
            //        pack.Salt = LotMachine.MachineInfo.M_Salt;
            //        ticketEntity.L_TicketCode = decodePrintData.L_PrintTicketEntity.P_TicketCode;
            //        ticketEntity.L_CodeRate = decodePrintData.L_PrintTicketEntity.L_CodeRate;
            //        ticketEntity.L_SucTime = decodePrintData.L_PrintTicketEntity.P_SucTime;
            //        ticketEntity.L_PrnText = decodePrintData.L_PrintTicketEntity.P_PrnText;
            //        ticketEntity.L_Status = 1;
            //        pack.Ticket = ticketEntity;
            //        A10002NotifyTicketRet packRet = PackManager.Instance.Send(pack) as A10002NotifyTicketRet;
            //        if (packRet.Code != 0)
            //        {
            //            throw new Exception("票号通知失败，" + packRet.Message);
            //        }

            //        LotMachine.Log.Info(string.Concat("票号通知成功：", ticket.L_TicketSn, " 彩种：", ticket.L_LotName, ticket.LotId, "玩法：", ticket.L_PlayName, ticket.L_PlayId, "倍数：", ticket.L_Mutiple, "金额：", ticket.L_Money, " 出票耗时为：", totalTime.ToString("0"), "毫秒 ", ticket.IsUseScanner ? "扫描出票" : "键码出票"));


            //        TotalMoney += ticketEntity.L_Money;
            //        TotalTicket += 1;

            //        ticketEntity.L_SucTime = DateTime.Now;//使用电脑时间判断两张票的间隔
            //        LastSucTicket = ticketEntity;


            //    OnPrinted(ticketEntity);

            //    if (LotMachine.MachineInfo.M_Status == (int)MachineStatusEnum.Error)
            //    {
            //        UpdateMachineStatus(MachineStatusEnum.Printing);
            //    }
            //    else if (LotMachine.MachineInfo.M_Status == (int)MachineStatusEnum.Stopped)
            //    {
            //        Start();
            //    }
            //}
        }

        ///// <summary>
        ///// 获取最近截止时间
        ///// </summary>
        ///// <returns></returns>
        //private DateTime GetEarliestEndTime()
        //{
        //    DateTime endtime = DateTime.MaxValue;
        //    DateTime jzendtime = DateTime.MaxValue;
        //    DateTime jlendtime = DateTime.MaxValue;
        //    Database database = DBSetting.Instance.GetDataBase("lotdb");
        //    SqlConnection conn = null;
        //    try
        //    {
        //        conn = new SqlConnection(database.ConnectionString);
        //        conn.Open();
        //        string sql = "select min(e_apiendtime) from jz_expect with(nolock) where e_apiendtime>getdate()";
        //        object obj = SqlHelper.ExecuteScalar(conn, CommandType.Text, sql);
        //        if (obj != DBNull.Value)
        //        {
        //            jzendtime = Convert.ToDateTime(obj);
        //        }
        //        sql = "select min(e_apiendtime) from jl_expect with(nolock) where e_apiendtime>getdate()";
        //        obj = SqlHelper.ExecuteScalar(conn, CommandType.Text, sql);
        //        if (obj != DBNull.Value)
        //        {
        //            jlendtime = Convert.ToDateTime(obj);
        //        }
        //        endtime = jzendtime < jlendtime ? jzendtime : jlendtime;
        //    }
        //    finally
        //    {
        //        if (conn != null)
        //        {
        //            conn.Close();
        //        }
        //    }
        //    return endtime;
        //}

        ///// <summary>
        ///// 设置是否扫描出票
        ///// </summary>
        //public void SetIsScan(L_LotTicketEntity ticketEntity, M_MachineEntity MachineInfo)
        //{
        //    bool isusescanner = false;
        //    MachineType machineType = (MachineType)MachineInfo.M_Type;
        //    if(ticketEntity.LotId==911 ||ticketEntity.LotId==951||ticketEntity.LotId==971)
        //    {
        //        isusescanner = true;
        //        if (MachineInfo.M_InputDeviceType == (int)InputDeviceType.Scanner)
        //        {
        //            if (ticketEntity.LotId == (int)Lottype.Jz || ticketEntity.LotId == (int)Lottype.Jl)
        //            {
        //                //投注号码包含的场次个数
        //                int changcinum = ticketEntity.L_Code.Split('/').Length;
        //                Playtype playtype = (Playtype)ticketEntity.L_PlayId;

        //                if (machineType == MachineType.JsTiCai || machineType == MachineType.HnTiCai || machineType == MachineType.JxJingCaiV1)
        //                {
        //                    //放开8关投注单
        //                    switch (playtype)
        //                    {
        //                        case Playtype.JzSPF:
        //                            //竟足胜平负有3关、6关、8关投注单(旧版投注单)
        //                            break;
        //                        case Playtype.JzRQSPF:
        //                            //竟足让球胜平负有3关、6关、8关投注单(8关无效)
        //                            break;
        //                        case Playtype.JzBF:
        //                            //竟足比分仅有3关投注单
        //                            if (changcinum > 3)
        //                            {
        //                                isusescanner = false;
        //                            }
        //                            break;
        //                        case Playtype.JzJQS:
        //                            //竟足总进球数有3关、6关投注单
        //                            if (changcinum > 6)
        //                            {
        //                                isusescanner = false;
        //                            }
        //                            break;
        //                        case Playtype.JzBQC:
        //                            //竟足半全场仅有3关投注单
        //                            if (changcinum > 3)
        //                            {
        //                                isusescanner = false;
        //                            }
        //                            break;
        //                        case Playtype.JlRFSF:
        //                            //竟篮让分胜平负有3关、6关、8关投注单
        //                            break;
        //                        case Playtype.JlSF:
        //                            //竟篮胜平负有3关、6关、8关投注单
        //                            break;
        //                        case Playtype.JlSFC:
        //                            //竟篮胜分差仅有3关投注单
        //                            if (changcinum > 3)
        //                            {
        //                                isusescanner = false;
        //                            }
        //                            break;
        //                        case Playtype.JlDXF:
        //                            //竟篮大小分有3关、6关、8关投注单
        //                            break;
        //                        case Playtype.JzHHGG:
        //                            //竟足混合过关包含比分、半全场的没有3关以上投注单，包含比分、进球数、半全场没有6关以上投注单
        //                            if (changcinum > 6)
        //                            {
        //                                if (ticketEntity.L_Code.IndexOf("91102") > -1 || ticketEntity.L_Code.IndexOf("91103") > -1 || ticketEntity.L_Code.IndexOf("91104") > -1)
        //                                {
        //                                    isusescanner = false;
        //                                }
        //                            }
        //                            else
        //                            {
        //                                //新版混串投注单已经支持比分
        //                                /*if (ticketEntity.L_Code.IndexOf("91102") > -1)
        //                                {
        //                                    //含有比分，只能用第一版混合过关投注单（天津 3关 8倍以上的暂时用不了）
        //                                    if (ticketEntity.L_Code.IndexOf("91101") > -1)
        //                                    {
        //                                        isusescanner = false;
        //                                    }
        //                                }*/
        //                                //包含比分、半全场的没有3关以上投注单
        //                                if (ticketEntity.L_Code.IndexOf("91102") > -1 || ticketEntity.L_Code.IndexOf("91104") > -1)
        //                                {
        //                                    if (changcinum > 3)
        //                                    {
        //                                        isusescanner = false;
        //                                    }
        //                                }
        //                            }

        //                            break;
        //                        case Playtype.JlHHGG:
        //                            //竟篮混合过关包含胜分差的没有3关以上投注单
        //                            if (ticketEntity.L_Code.IndexOf("95103") > -1)
        //                            {
        //                                if (changcinum > 3)
        //                                {
        //                                    isusescanner = false;
        //                                }
        //                            }
        //                            break;
        //                    }
        //                }
        //                else
        //                {
        //                    //旧版投注单与新版混用--混串用新版投注单，其它全部用旧版的
        //                    switch (playtype)
        //                    {
        //                        case Playtype.JzSPF:
        //                            //竟足胜平负有3关、6关、8关投注单(旧版投注单)
        //                            break;
        //                        case Playtype.JzRQSPF:
        //                            //竟足让球胜平负有3关、6关、8关投注单(8关无效)
        //                            if (changcinum > 6)
        //                            {
        //                                isusescanner = false;
        //                            }

        //                            break;
        //                        case Playtype.JzBF:
        //                            //竟足比分仅有3关投注单
        //                            if (changcinum > 3)
        //                            {
        //                                isusescanner = false;
        //                            }
        //                            break;
        //                        case Playtype.JzJQS:
        //                            //竟足总进球数有3关、6关投注单
        //                            if (changcinum > 6)
        //                            {
        //                                isusescanner = false;
        //                            }
        //                            break;
        //                        case Playtype.JzBQC:
        //                            //竟足半全场仅有3关投注单
        //                            if (changcinum > 3)
        //                            {
        //                                isusescanner = false;
        //                            }
        //                            break;
        //                        case Playtype.JlRFSF:
        //                            //竟篮让分胜平负有3关、6关、8关投注单
        //                            break;
        //                        case Playtype.JlSF:
        //                            //竟篮胜平负有3关、6关、8关投注单
        //                            break;
        //                        case Playtype.JlSFC:
        //                            //竟篮胜分差仅有3关投注单
        //                            if (changcinum > 3)
        //                            {
        //                                isusescanner = false;
        //                            }
        //                            break;
        //                        case Playtype.JlDXF:
        //                            //竟篮大小分有3关、6关、8关投注单
        //                            break;
        //                        case Playtype.JzHHGG:
        //                            //竟足混合过关包含比分、半全场的没有3关以上投注单
        //                            /*if (ticketEntity.L_Code.IndexOf("91102") > -1 || ticketEntity.L_Code.IndexOf("91104") > -1)
        //                            {
        //                                if (changcinum > 3)
        //                                {
        //                                    isusescanner = false;
        //                                }
        //                            }
        //                            if (changcinum > 6)
        //                            {
        //                                //无8关投注单
        //                                isusescanner = false;
        //                            }*/
        //                            /*isusescanner = false;*/

        //                            if (changcinum > 6)
        //                            {
        //                                //无8关投注单
        //                                isusescanner = false;

        //                            }
        //                            else
        //                            {
        //                                if (ticketEntity.L_Code.IndexOf("91102") > -1)
        //                                {
        //                                    //含有比分，只能用第一版混合过关投注单（天津 3关 8倍以上的暂时用不了）
        //                                    //if (ticketEntity.L_Mutiple > 8 && changcinum <= 3)
        //                                    //{
        //                                    //    isusescanner = false;
        //                                    //}
        //                                    if (ticketEntity.L_Code.IndexOf("91101") > -1)
        //                                    {
        //                                        isusescanner = false;
        //                                    }
        //                                }
        //                                //包含比分、半全场的没有3关以上投注单
        //                                if (ticketEntity.L_Code.IndexOf("91102") > -1 || ticketEntity.L_Code.IndexOf("91104") > -1)
        //                                {
        //                                    if (changcinum > 3)
        //                                    {
        //                                        isusescanner = false;
        //                                    }
        //                                }
        //                            }

        //                            break;
        //                        case Playtype.JlHHGG:
        //                            //竟篮混合过关包含胜分差的没有3关以上投注单
        //                            if (ticketEntity.L_Code.IndexOf("95103") > -1)
        //                            {
        //                                if (changcinum > 3)
        //                                {
        //                                    isusescanner = false;
        //                                }
        //                            }
        //                            if (changcinum > 6)
        //                            {
        //                                //有8关投注单，但暂时无效，原因不详
        //                                isusescanner = false;
        //                            }
        //                            break;
        //                    }
        //                }


        //                //新版投注单
        //                /*switch (playtype)
        //                {
        //                    case Playtype.JzSPF:
        //                        //竟足胜平负有3关、6关、8关投注单
        //                        if (changcinum > 6)
        //                        {
        //                            //8关投注单暂时无效，原因不详
        //                            isusescanner = false;
        //                        }
        //                        break;
        //                    case Playtype.JzBF:
        //                        //竟足比分仅有3关投注单
        //                        if (changcinum > 3)
        //                        {
        //                            isusescanner = false;
        //                        }
        //                        break;
        //                    case Playtype.JzJQS:
        //                        //竟足总进球数有3关、6关投注单
        //                        if (changcinum > 6)
        //                        {
        //                            isusescanner = false;
        //                        }
        //                        break;
        //                    case Playtype.JzBQC:
        //                        //竟足半全场仅有3关投注单
        //                        if (changcinum > 3)
        //                        {
        //                            isusescanner = false;
        //                        }
        //                        break;
        //                    case Playtype.JlRFSF:
        //                        //竟篮让分胜平负有3关、6关、8关投注单
        //                        if (changcinum > 6)
        //                        {
        //                            //8关投注单暂时无效，原因不详
        //                            isusescanner = false;
        //                        }
        //                        break;
        //                    case Playtype.JlSF:
        //                        //竟篮胜平负有3关、6关、8关投注单
        //                        if (changcinum > 6)
        //                        {
        //                            //8关投注单暂时无效，原因不详
        //                            isusescanner = false;
        //                        }
        //                        break;
        //                    case Playtype.JlSFC:
        //                        //竟篮胜分差仅有3关投注单
        //                        if (changcinum > 3)
        //                        {
        //                            isusescanner = false;
        //                        }
        //                        break;
        //                    case Playtype.JlDXF:
        //                        //竟篮大小分有3关、6关、8关投注单
        //                        if (changcinum > 6)
        //                        {
        //                            //8关投注单暂时无效，原因不详
        //                            isusescanner = false;
        //                        }
        //                        break;
        //                    case Playtype.JzHHGG:
        //                        //竟足混合过关包含比分、半全场的没有3关以上投注单
        //                        if (ticketEntity.L_Code.IndexOf("91102") > -1 || ticketEntity.L_Code.IndexOf("91104") > -1)
        //                        {
        //                            if (changcinum > 3)
        //                            {
        //                                isusescanner = false;
        //                            }
        //                        }
        //                        if (changcinum > 6)
        //                        {
        //                            //暂无8关投注单
        //                            isusescanner = false;
        //                        }
        //                        break;
        //                    case Playtype.JlHHGG:
        //                        //竟篮混合过关包含胜分差的没有3关以上投注单
        //                        if (ticketEntity.L_Code.IndexOf("95103") > -1)
        //                        {
        //                            if (changcinum > 3)
        //                            {
        //                                isusescanner = false;
        //                            }
        //                        }
        //                        if (changcinum > 6)
        //                        {
        //                            //8关投注单暂时无效，原因不详
        //                            isusescanner = false;
        //                        }
        //                        break;
        //                }*/
        //            }
        //            else if (ticketEntity.LotId == (int)Lottype.Jm)
        //            {
        //                isusescanner = false;
        //            }
        //            else
        //            {
        //                isusescanner = false;
        //            }
        //        }
        //        else
        //        {
        //            isusescanner = false;
        //        }

        //        //竟彩大额票暂时不能扫描出票
        //        //if(ticketEntity.L_Money>=500)
        //        //{
        //        //    isusescanner = false;
        //        //}
        //    }
        //    //else if(ticketEntity.LotId==(int)Lottype.Lt)
        //    //{
        //    //    if (MachineInfo.M_InputDeviceType == (int)InputDeviceType.Scanner)
        //    //    {
        //    //        if(machineType == MachineType.HnTiCai || machineType == MachineType.JxTiCaiMachineV2)
        //    //        {
        //    //            isusescanner = true;
        //    //            if(ticketEntity.L_PlayId==(int)Playtype.LtDt || ticketEntity.L_PlayId==(int)Playtype.LtZhuiJiaDt)
        //    //            {
        //    //                isusescanner = false;
        //    //            }
        //    //        }
        //    //    }
        //    //    else
        //    //    {
        //    //        isusescanner = false;
        //    //    }
        //    //}

        //    ticketEntity.IsUseScanner = isusescanner;
        //}
        private void SetIsClearExpect(L_LotTicketEntity ticketEntity)
        {
            bool isclearexpect = false;
            if (ticketEntity.LotId == 911 || ticketEntity.LotId == 951 || ticketEntity.LotId == 971)
            {
                if (ticketEntity.IsUseScanner)
                {
                    if (DateTime.Now.Subtract(LastClearExpectTime).TotalSeconds > JcClearExpectInterval)
                    {
                        isclearexpect = true;
                        LastClearExpectTime = DateTime.Now;
                    }
                }
                else
                {
                    //键盘出票每次清除奖期更新
                    isclearexpect = true;
                    LastClearExpectTime = DateTime.Now;
                }

            }
            ticketEntity.IsClearExpect = isclearexpect;
        }
        public void RePrint(L_LotTicketEntity ticketEntity)
        {
            lock (WaitPrintTickets)
            {
                L_LotTicketEntity[] tickets = WaitPrintTickets.ToArray();
                WaitPrintTickets.Clear();
                WaitPrintTickets.Enqueue(ticketEntity);
                foreach (L_LotTicketEntity entity in tickets)
                {
                    WaitPrintTickets.Enqueue(entity);
                }
            }
        }

        public bool ReGetdataForBatch()
        {
            try
            {
                if (CurrentTicket != null)
                {
                    DecodePrintData decodePrintData = new DecodePrintData();
                    ReGetdata(CurrentTicket, decodePrintData);
                    if (decodePrintData.DecodeSuccess)
                    {
                        Wait4Job.Set();
                        OnErrorCleared();
                    }
                    return decodePrintData.DecodeSuccess;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception exception)
            {
                LotMachine.Log.Info(string.Concat("批量重新获取失败。错误信息：", exception));
                return false;
            }
        }



        private void Wait(int wait)
        {
            LotMachine.Log.Debug(string.Concat("等待", wait, "毫秒"));
            while (wait > 0)
            {
                wait -= 100;
                Thread.Sleep(100);
                if (LotMachine.MachineInfo.M_Status != (int)MachineStatusEnum.Printing)
                {
                    break;
                }
            }
        }
        public void OnPrinting(L_LotTicketEntity ticket)
        {
            if (Printing != null)
            {
                Printing(this, new TicketEventArgs(ticket));
            }
        }
        public void OnPrinted(L_LotTicketEntity ticket)
        {
            if (Printed != null)
            {
                Printed(this, new TicketEventArgs(ticket));
            }
        }
        public void OnAmountCleared()
        {
            if (AmountCleared != null)
            {
                AmountCleared(this, new EventArgs());
            }
        }
        public void OnErrorCleared()
        {
            if (ErrorCleared != null)
            {
                ErrorCleared(this, new EventArgs());
            }
        }

        //private List<L_LotTicketEntity> CreateTestTicketList()
        //{
        //    List<L_LotTicketEntity> list = new List<L_LotTicketEntity>();
        //    for (int i = 0; i < MaxOneLoad; i++)
        //    {
        //        Random random = new Random();
        //        L_LotTicketEntity ticket = new L_LotTicketEntity();
        //        ticket.L_TicketSn = random.Next(10000000, 999999999).ToString();
        //        ticket.L_TicketCode = random.Next(90000000, 999999999).ToString();
        //        ticket.L_Code = string.Concat(random.Next(1, 220000) % 22, ",", random.Next(1, 220000) % 22, ",", random.Next(1, 220000) % 22, ",", random.Next(1, 220000) % 22, ",", random.Next(1, 220000) % 22);
        //        ticket.L_OrderSn = string.Concat(random.Next(11000, 99999), "XW", random.Next(1000000, 9999999));
        //        ticket.L_Mutiple = random.Next(1, 99);
        //        ticket.L_Money = ticket.L_Mutiple * 10;
        //        ticket.LotId = 705;
        //        ticket.L_PlayId = 70501;
        //        ticket.MacLotId = 705;
        //        ticket.MacPlayId = 70501;
        //        ticket.MacModeId = 7050101;
        //        list.Add(ticket);
        //    }
        //    return list;
        //}

        //private void CreateTestPrintTicket(L_LotTicketEntity ticket, DecodePrintData decodePrintData)
        //{
        //    Random random = new Random();
        //    decodePrintData.L_PrintTicketEntity.P_AddTime = DateTime.Now;
        //    decodePrintData.L_PrintTicketEntity.P_Code = ticket.L_Code;
        //    decodePrintData.L_PrintTicketEntity.P_Expect = ticket.L_Expect;
        //    decodePrintData.L_PrintTicketEntity.P_Lid = ticket.L_Id;
        //    decodePrintData.L_PrintTicketEntity.P_Money = ticket.L_Money;
        //    decodePrintData.L_PrintTicketEntity.P_Mutiple = ticket.L_Mutiple;
        //    decodePrintData.L_PrintTicketEntity.P_Password = random.Next(111111, 999999).ToString();
        //    decodePrintData.L_PrintTicketEntity.P_RandomCode = random.Next(111111, 999999).ToString();
        //    decodePrintData.L_PrintTicketEntity.P_TicketCode = random.Next(90000000, 999999999).ToString();
        //    decodePrintData.L_PrintTicketEntity.P_SingleZhuShu = ticket.L_SingleZhuShu;
        //    decodePrintData.L_PrintTicketEntity.P_SucTime = DateTime.Now;
        //    decodePrintData.DecodeSuccess = true;
        //}

        ///// <summary>
        ///// 多乐彩截止前4分钟自动转移出票任务
        ///// </summary>
        //private bool AutoTransferTaskOfDlc(int lotId,out int waitTransferTicketNum,out int transferedTicketNum)
        //{
        //    waitTransferTicketNum = 0;
        //    transferedTicketNum = 0;
        //    try
        //    {
        //        //int lotId = (int) Lottype.Dl;
        //        L_ExpectService expectService=new L_ExpectService();
        //        L_ExpectEntity expect = expectService.GetActiveExpect(lotId);
        //        if (DateTime.Now > expect.E_ApiEndTime.AddMinutes(-4))
        //        {
        //            //当前期截止前4分钟

        //            //1.禁用机器，后续的票不再继续分配
        //            //Forbid();

        //            //2.当期已分配的票转移至其它正在出票任务数较少的机器
        //            L_LotTicketService lotTicketService = new L_LotTicketService();
        //            List<L_LotTicketEntity> waitTranferTickets = lotTicketService.GetWaitTransferTicketList(lotId, LotMachine.MachineInfo.M_Number, 0);
        //            if (waitTranferTickets == null || waitTranferTickets.Count == 0)
        //            {
        //                LotMachine.Log.Info(string.Concat("没有需要转移的票。"));
        //                return false;
        //            }
        //            waitTransferTicketNum = waitTranferTickets.Count;
        //            LotMachine.Log.Info(string.Concat("有可转移的票 ", waitTranferTickets.Count, " 张"));

        //            List<M_MachineEntity> desMachineList = new List<M_MachineEntity>();
        //            M_MachineService machineService = new M_MachineService();
        //            List<M_MachineEntity> machineList = machineService.GetMachineList();
        //            machineList.Sort(delegate(M_MachineEntity mac1, M_MachineEntity mac2)
        //            { return mac1.M_TicketNum.CompareTo(mac2.M_TicketNum); });
        //            foreach (M_MachineEntity entity in machineList)
        //            {
        //                if(entity.M_Number==LotMachine.MachineInfo.M_Number)
        //                {
        //                    continue;
        //                }

        //                if (entity.M_Status == (int)MachineStatusEnum.Printing && entity.M_IsUse)
        //                {
        //                    if (desMachineList.Contains(entity))
        //                    {
        //                        continue;
        //                    }
        //                    desMachineList.Add(entity);
        //                }
        //            }
        //            if (desMachineList.Count < 1)
        //            {
        //                LotMachine.Log.Error("当前没有可用的机器号！");
        //                return true;
        //            }

        //            foreach (L_LotTicketEntity ticket in waitTranferTickets)
        //            {
        //                if(ticket.L_PrintNum>1)
        //                {
        //                    LotMachine.Log.Warn(string.Concat("生产流水号：",ticket.L_TicketSn," 转移次数超过2次，不再自动转移"));
        //                    continue;
        //                }
        //                if (ticket.L_Money > 500)
        //                {
        //                    LotMachine.Log.Warn(string.Concat("生产流水号：", ticket.L_TicketSn, " 金额超过500元，不自动转移"));
        //                    continue;
        //                }

        //                bool isTransfered = false;
        //                while (desMachineList.Count >= 1)
        //                {
        //                    M_MachineEntity targetMachine = desMachineList[0];
        //                    if (targetMachine.M_Money < ticket.L_Money)
        //                    {
        //                        desMachineList.RemoveAt(0);
        //                        LotMachine.Log.Warn(string.Concat("转移票[", ticket.L_TicketSn, "]不成功：彩票机[", targetMachine.M_Number, "]余额不足。程序将尝试其它彩票机进行转移。"));
        //                        continue;
        //                    }
        //                    string macNumber = ticket.L_MacNumber;
        //                    ticket.L_MacNumber = targetMachine.M_Number;

        //                    try
        //                    {
        //                        lotTicketService.TransferTaskLottickets(ticket.LotId, ticket.L_Id, macNumber, targetMachine.M_Number);
        //                        targetMachine.M_TicketNum += 1;
        //                        transferedTicketNum++;
        //                        desMachineList.RemoveAt(0);
        //                        desMachineList.Add(targetMachine);
        //                        isTransfered = true;
        //                        LotMachine.Log.Info(string.Concat("转移票成功。彩种[", ticket.L_LotName, "] 玩法[", ticket.L_PlayName, "] 金额[", ticket.L_Money.ToString("0"), "] 生产流水号[" + ticket.L_TicketSn + "] 从彩票机[", LotMachine.MachineInfo.M_Number, "]到彩票机[", targetMachine.M_Number, "]"));
        //                    }
        //                    catch (Exception ex)
        //                    {
        //                        LotMachine.Log.Error(string.Concat("转移票[", ticket.L_TicketSn, "] 异常：", ex.Message));
        //                        continue;
        //                    }
        //                    break;
        //                }
        //                if (!isTransfered)
        //                {
        //                    LotMachine.Log.Warn(string.Concat("转移票[", ticket.L_TicketSn, "]不成功：所有符合条件的彩票机均余额不足。请充值或刷新机器额度。"));
        //                }
        //            }
        //        }
        //    }
        //    catch (Exception exception)
        //    {
        //        LotMachine.Log.Warn(string.Concat("截止前自动切票异常。错误信息：",exception));
        //    }
        //    return true;
        //}

        private void ReportError(L_LotTicketEntity ticket, DecodePrintData decodePrintData, string errorTitle, string errorMessage)
        {
            //_status = MachineStatusEnum.Error;
            LastSucTicket = null;
            try
            {
                if (null != PrintTicketError)
                {
                    //L_LotTicketEntity entity = ticket.Clone() as L_LotTicketEntity;
                    PrintTicketError(this, new ErrorTicketEventArgs(ticket, decodePrintData, errorTitle));
                }
                int waitTransferTicketNum = 0;
                int transferedTicketNum = 0;
                bool isAutoTransfer = false;

                //if(ticket.LotId==(int)Lottype.Dl)
                //{
                //    isAutoTransfer = AutoTransferTaskOfDlc(out waitTransferTicketNum, out transferedTicketNum);
                //}

                //if (ticket.LotId == (int)Lottype.Dl || ticket.LotId == (int)Lottype.Hd || ticket.LotId == (int)Lottype.Jd || ticket.LotId == (int)Lottype.Xs)
                //{
                //    isAutoTransfer = AutoTransferTaskOfDlc(ticket.LotId, out waitTransferTicketNum, out transferedTicketNum);
                //}

                //出错就置空彩票机的投注模式，处理完错误就重新切换投注模式
                LotMachine.MacCurrentMode = null;

                //更新机器状态
                LotMachine.MachineInfo.M_Status = (int)MachineStatusEnum.Error;
                LotMachine.MachineInfo.M_LastErrorTitle = isAutoTransfer ? "自动转移票" + transferedTicketNum + "张" : errorTitle;
                LotMachine.MachineInfo.M_LastErrorTime = DateTime.Now;
                LotMachine.MachineInfo.M_ErrorNum += 1;

                this.UpdateMachineErrorInfoAndStatus();
                //M_MachineService machineService = new M_MachineService();
                //LotMachine.Log.Debug("更新机器错误信息开始……");
                //machineService.UpdateMachineErrorInfo(LotMachine.MachineInfo);
                //LotMachine.Log.Debug("更新机器错误信息结束");
                //this.UpdateMachineStatus(MachineStatusEnum.Error);

                //try
                //{
                //    M_MachineErrorEntity errorEntity = new M_MachineErrorEntity();
                //    errorEntity.L_ErrorMessage = errorMessage;
                //    errorEntity.L_ErrorTime = DateTime.Now;
                //    errorEntity.L_ErrorTitle = errorTitle;
                //    errorEntity.L_TicketSn = ticket.L_TicketSn;
                //    errorEntity.L_LotId = ticket.LotId;
                //    errorEntity.L_MacNumber = LotMachine.MachineInfo.M_Number;
                //    //errorEntity.L_Type = 0;
                //    //M_MachineErrorService errorService=new M_MachineErrorService();
                //    //errorService.Add(errorEntity);
                //}
                //catch (Exception exception)
                //{
                //    LotMachine.Log.Info("记录机器报错信息异常。错误信息：" + exception.Message);
                //}

                ////自动弹出错票
                ////if (decodePrintData!=null && decodePrintData.InputData.CaptureDataBytes.Length > 60)
                //if (decodePrintData != null && decodePrintData.InputData.CaptureDataBytes.Length > 60)
                //{
                //    HasErrorTicket = true;
                //    LotMachineService.PrintETicket(LotMachine.MachineInfo.M_Number, decodePrintData.InputData.CaptureDataBytes);

                //    //记录错票信息到数据库
                //保存错票电子票文件
                string errorticketFilePath = FileService.GetErrorTicketFilePath(LotMachine.MachineInfo.M_Number, ticket.L_TicketSn + "_" + DateTime.Now.ToString("yyyyMMddHHmmss"));
                File.WriteAllText(errorticketFilePath, decodePrintData.L_PrintTicketEntity.P_PrnText);
                LotMachine.Log.Info("保存错票文件");
                //LotMachine.Log.Info(string.Concat("保存电子票文件：", errorticketFilePath));
                //    //LotMachineService.PrintETicket(LotMachine.MachineInfo.M_Number, errorticketFilePath, true);
                //    ////保存错票信息到错票表
                //    //L_ErrorTicketService errorTicketService = new L_ErrorTicketService();
                //    //errorTicketService.AddErrorTicket(ticket, decodePrintData.L_PrintTicketEntity);
                //    LotMachine.Log.Info(string.Concat("错票信息入库，打印并保存错票文件：", errorticketFilePath));

                //    //try
                //    //{
                //    //    ChuPiao.Common.Communication.CpdJson.Packs.P12014PrintTicketFile reqPack = new ChuPiao.Common.Communication.CpdJson.Packs.P12014PrintTicketFile();
                //    //    reqPack.MacNumber = LotMachine.MachineInfo.M_Number;
                //    //    reqPack.PrnText =
                //    //        HexStringUtil.ByteToString(decodePrintData.InputData.CaptureDataBytes);
                //    //    ChuPiao.Common.Communication.CpdJson.PackRetBase packRetBase = ChuPiao.Common.Communication.CpdJson.PackManager.Instance.Transaction(LotMachine.MachineInfo.M_Number, reqPack);
                //    //    if (packRetBase == null)
                //    //    {
                //    //        throw new Exception(string.Concat("执行命令失败。机器号：", LotMachine.MachineInfo.M_Number));
                //    //    }
                //    //    if (packRetBase.ReturnCode != 0)
                //    //    {
                //    //        throw new Exception(string.Concat("彩票机返回错误编码：", packRetBase.ReturnCode, " 错误信息：", packRetBase.ReturnMessage));
                //    //    }
                //    //}
                //    //catch (Exception ex1)
                //    //{
                //    //    LotMachine.Log.Error(string.Concat("打印错票文件异常：",ex1));
                //    //}
                //}

                LotMachine.Log.Info(string.Concat("报告错误：", errorTitle));
            }
            catch (Exception exc)
            {
                LotMachine.Log.Error("出票线程中彩票机出错时更新机器错误状态异常：" + exc.Message);
            }
            //LotMachine.Log.Error(string.Concat("出票线程异常：", ex.Message, Environment.NewLine, ex.StackTrace));
            //LotMachine.Log.Error(string.Concat("出票异常。错误信息：", ex));

            Wait4Job.Reset();
            Wait4Job.WaitOne();
        }
        /// <summary>
        /// 维护机器状态
        /// </summary>
        /// <param name="status"></param>
        public void UpdateMachineErrorInfoAndStatus()
        {
            try
            {
                MachineStatusEnum status = (MachineStatusEnum)LotMachine.MachineInfo.M_Status;
                //M_MachineService machineService = new M_MachineService();
                ////LotMachine.Log.Info(string.Concat("更新数据库机器错误信息及状态：", status, "开始"));
                ////Thread.Sleep(1*60*1000);
                //machineService.UpdateMachineErrorInfo(LotMachine.MachineInfo);
                //LotMachine.Log.Info(string.Concat("更新数据库机器错误信息及状态：", status, "完成"));
                OnStatusChanged(status);
            }
            catch (Exception exception)
            {
                LotMachine.Log.Info(string.Concat("更新机器错误信息及状态异常。错误信息：", exception.Message));
            }
        }
        /// <summary>
        /// 维护机器状态
        /// </summary>
        /// <param name="status"></param>
        public void UpdateMachineStatus(MachineStatusEnum status)
        {
            int status_bak = LotMachine.MachineInfo.M_Status;
            try
            {
                LotMachine.MachineInfo.M_Status = (int)status;
                //M_MachineService machineService = new M_MachineService();
                ////LotMachine.Log.Debug(string.Concat("更新数据库机器状态：", status, "开始"));
                //machineService.UpdateMachineStatus(LotMachine.MachineInfo);
                //LotMachine.Log.Debug(string.Concat("更新数据库机器状态：", status, "完成"));
                OnStatusChanged(status);
            }
            catch (Exception exception)
            {
                LotMachine.Log.Info(string.Concat("更新机器状态：", status, "异常。错误信息：", exception.Message));
                LotMachine.MachineInfo.M_Status = status_bak;
                throw exception;
            }

        }
        private ErrorProcessEnum _result;
        public ErrorProcessEnum Result
        {
            get
            {
                return _result;
            }
            set
            {
                _result = value;
            }
        }
        public decimal TotalMoney = 0;
        public int TotalTicket = 0;

        //public DecodeMachinePayMoneyReport PrintPayMoneyReport()
        //{
        //    DecodeMachinePayMoneyReport report=new DecodeMachinePayMoneyReport();
        //    LotMachine.PrintPayMoneyReport(report,true);
        //    return report;
        //}

        public void OnStatusChanged(MachineStatusEnum machineStatus)
        {
            EventHandler<MachineStatusArgs> handler = StatusChanged;
            if (handler != null)
            {
                handler(this, new MachineStatusArgs(machineStatus));
            }
        }

        public void UpdateMachineMoney()
        {
            DecodeMachinePayMoneyReport decodePrintData = new DecodeMachinePayMoneyReport();
            LotMachine.PrintPayMoneyReport(decodePrintData, false);

            if (decodePrintData.DecodeSuccess)
            {
                A10006UploadMachineBalance pack = new A10006UploadMachineBalance();
                pack.AgentId = LotMachine.MachineInfo.M_Number;
                pack.Salt = LotMachine.MachineInfo.M_Salt;

                pack.Balance = decodePrintData.MachinePayMoneyReportEntity.R_Balance;
                pack.QueryTime = decodePrintData.MachinePayMoneyReportEntity.R_QueryTime.ToString("yyyyMMddHHmmss");

                //天
                MachineReportTime reportTime = MachineReportTimeList.GetCurrentTime(1);
                pack.From = reportTime.From.ToString("yyyyMMdd");
                pack.To = reportTime.To.ToString("yyyyMMdd");
                pack.Type = 1;
                pack.TypeName = reportTime.ValueMember;
                pack.Prntext = decodePrintData.MachinePayMoneyReportEntity.R_PrnText;

                A10006UploadMachineBalanceRet packRet = PackManager.Instance.Send(pack) as A10006UploadMachineBalanceRet;
                if (packRet.Code <= 0)
                {
                    LotMachine.Log.Warn(LotMachine.MachineInfo.M_Number + " 上传缴款报表失败，请重试！");
                    throw new Exception("上传缴款报表中的余额失败，" + packRet.Code.ToString() + " " + packRet.Message);
                    
                }

                DateTime now = DateTime.Now.AddHours(-7);
                //归属到周余额
                reportTime = MachineReportTimeList.GetCurrentTime(2);
                if (reportTime.To.ToShortDateString() == now.ToShortDateString())
                {
                    pack.From = reportTime.From.ToString("yyyyMMdd");
                    pack.To = reportTime.To.ToString("yyyyMMdd");
                    pack.Type = 2;
                    pack.TypeName = reportTime.ValueMember;

                    packRet = PackManager.Instance.Send(pack) as A10006UploadMachineBalanceRet;
                    if (packRet.Code <= 0)
                    {
                        LotMachine.Log.Warn(LotMachine.MachineInfo.M_Number + " 上传缴款报表失败，请重试！");
                        throw new Exception("上传缴款报表中的余额失败，" + packRet.Code.ToString() + " " + packRet.Message);

                    }
                }
                //归属到月余额
                reportTime = MachineReportTimeList.GetCurrentTime(3);
                if (reportTime.To.ToShortDateString() == now.ToShortDateString())
                {
                    pack.From = reportTime.From.ToString("yyyyMMdd");
                    pack.To = reportTime.To.ToString("yyyyMMdd");
                    pack.Type = 3;
                    pack.TypeName = reportTime.ValueMember;

                    packRet = PackManager.Instance.Send(pack) as A10006UploadMachineBalanceRet;
                    if (packRet.Code <= 0)
                    {
                        LotMachine.Log.Warn(LotMachine.MachineInfo.M_Number + " 上传缴款报表失败，请重试！");
                        throw new Exception("上传缴款报表中的余额失败，" + packRet.Code.ToString() + " " + packRet.Message);

                    }
                }

                if (decodePrintData.MachinePayMoneyReportEntity.R_DataList.Count > 0)
                {
                    A10007UploadMachinePay pack1 = new A10007UploadMachinePay();
                    pack1.AgentId = LotMachine.MachineInfo.M_Number;
                    pack1.Salt = LotMachine.MachineInfo.M_Salt;

                    pack1.QueryTime = decodePrintData.MachinePayMoneyReportEntity.R_QueryTime;
                    foreach (PayMoneyDataItem item in decodePrintData.MachinePayMoneyReportEntity.R_DataList)
                    {
                        pack1.PaymentList.Add(new UploadMachinePayItem(item.PayType, item.PayMoney, item.PayTime,item.Fee));
                    }

                    A10007UploadMachinePayRet packRet1 = PackManager.Instance.Send(pack1) as A10007UploadMachinePayRet;
                    if (packRet1.Code <= 0)
                    {
                        LotMachine.Log.Warn(LotMachine.MachineInfo.M_Number + " 上传缴款报表失败，请重试！");
                        throw new Exception("上传缴款报表中的缴款记录失败，" + packRet1.Code.ToString() + " " + packRet1.Message);

                    }
                }

                LotMachine.Log.Info(LotMachine.MachineInfo.M_Number + " 上传缴款报表成功！");

            }
            else
            {
                LotMachine.Log.Warn(LotMachine.MachineInfo.M_Number + " 上传缴款报表失败，请重试！");
                throw new Exception(string.Concat("解析缴款报表失败。错误信息：", decodePrintData.ErrorMessage));
                
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="typename">日-20130101 周-201301-1 月201301</param>
        /// <param name="from"></param>
        /// <param name="to"></param>
        public void PrintDayReport(int type,string typename,DateTime from,DateTime to)
        {
            DecodeMachineReport decodeMachineReport = new DecodeMachineReport();
            LotMachine.PrintReport(from, to, decodeMachineReport, false);

            if (decodeMachineReport.DecodeSuccess)
            {
                A10005UploadMachineSale pack = new A10005UploadMachineSale();
                pack.AgentId = LotMachine.MachineInfo.M_Number;
                pack.Salt = LotMachine.MachineInfo.M_Salt;

                pack.SaleMoney = decodeMachineReport.MachineReportEntity.R_SaleMoney;
                pack.EncashMoney = decodeMachineReport.MachineReportEntity.R_EncashMoney;
                pack.ReturnMoney = decodeMachineReport.MachineReportEntity.R_ReturnMoney;
                pack.QueryTime = decodeMachineReport.MachineReportEntity.R_QueryTime.ToString("yyyyMMddHHmmss");
                pack.From = decodeMachineReport.MachineReportEntity.R_StartTime.ToString("yyyyMMdd");
                pack.To = decodeMachineReport.MachineReportEntity.R_EndTime.ToString("yyyyMMdd");
                pack.Type = type;
                pack.TypeName = typename; 
                pack.Prntext = decodeMachineReport.MachineReportEntity.R_PrnText;

                A10005UploadMachineSaleRet packRet = PackManager.Instance.Send(pack) as A10005UploadMachineSaleRet;
                if (packRet.Code <= 0)
                {
                    LotMachine.Log.Warn(LotMachine.MachineInfo.M_Number + " 上传时段报表失败，请重试！");
                    throw new Exception("上传时段报表失败，" + packRet.Code.ToString() + " " + packRet.Message);
                    
                }

                LotMachine.Log.Info(LotMachine.MachineInfo.M_Number + " 上传时段报表成功！");

            }
            else
            {
                LotMachine.Log.Warn(LotMachine.MachineInfo.M_Number + " 上传时段报表失败，请重试！");
                throw new Exception(string.Concat("解析时段报表失败。错误信息：", decodeMachineReport.ErrorMessage));
                
            }

        }

        /// <summary>
        /// 清除合计值
        /// </summary>
        public void ClearAmount()
        {
            try
            {
                LotMachine.ClearMahineMoney();
                TotalTicket = 0;
                TotalMoney = 0;
                OnAmountCleared();
            }
            catch (Exception exception)
            {
                LotMachine.Log.Info(string.Concat("清除彩票机合计失败。错误信息：", exception));
            }

        }
        /// <summary>
        /// 清除错误
        /// </summary>
        public void ClearError(int errorType)
        {
            try
            {
                if (CurrentTicket != null)
                {
                    //StopSync();
                    LotMachine.ClearError(errorType);
                    //Wait(3000);
                    //Start();
                    OnErrorCleared();
                }
            }
            catch (Exception exception)
            {
                LotMachine.Log.Info(string.Concat("清除彩票机报错失败。错误信息：", exception));
            }
        }


        public void GetAndPrintLastTicket()
        {
            try
            {
                LotMachine.Log.Info("获取最后一张票");
                CaptureDataInfo dataInfo = LotMachine.GetCacheTicket();
                if (dataInfo == null)
                {
                    return;
                }
                if (dataInfo.CaptureDataBytes.Length == 0)
                {
                    dataInfo = LotMachine.GetLastTicket();
                }
                if (dataInfo == null)
                {
                    return;
                }
                if (dataInfo.CaptureDataBytes.Length > 0)
                {
                    LotMachine.Log.Info("打印最后一张票");
                    LotMachineService.PrintETicket(LotMachine.MachineInfo.M_Number, dataInfo.CaptureDataBytes);
                }
            }
            catch (Exception exception)
            {
                LotMachine.Log.Info(string.Concat("打印最后一张电子票失败。错误信息：", exception));
            }
        }


        public bool StopSync()
        {
            bool success = false;
            MachineStatusEnum status = (MachineStatusEnum)LotMachine.MachineInfo.M_Status;
            if (status == MachineStatusEnum.Printing || status == MachineStatusEnum.Error)
            {
                Stop();
                Wait4Job.Set();//报错的机器也停止
                int waitTime = 0;
                while (waitTime < 30000)
                {
                    status = (MachineStatusEnum)LotMachine.MachineInfo.M_Status;
                    if (status == MachineStatusEnum.Stopped)
                    {
                        success = true;
                        break;
                    }
                    Thread.Sleep(100);
                    waitTime += 100;
                }
            }
            else if (status == MachineStatusEnum.Stopped)
            {
                success = true;
            }
            return success;
        }


        ///// <summary>
        ///// 转移出票任务
        ///// </summary>
        //public int TransferTasks()
        //{
        //    int _minMachineMoney = 2000;
        //    try
        //    {
        //        M_MachineEntity machine = this.LotMachine.MachineInfo;
        //        M_MachinePlayService _machinePlayService = new M_MachinePlayService();
        //        List<M_MachinePlayEntity> machinePlayEntityList = _machinePlayService.GetMachineLotListByMid(machine);
        //        if (null != machinePlayEntityList && machinePlayEntityList.Count > 0)
        //        {
        //            L_LotTicketService _lotTicketService = new L_LotTicketService();
        //            M_MachineService _machineService = new M_MachineService();
        //            foreach (M_MachinePlayEntity entity in machinePlayEntityList)
        //            {
        //                List<L_LotTicketEntity> waitTranferTickets = _lotTicketService.GetWaitTransferTicketList(entity.P_LotId, machine.M_Number, entity.P_PlayId);
        //                if (waitTranferTickets.Count == 0)
        //                {
        //                    this.LotMachine.Log.Info(string.Concat(LotPlayTypeHashTable.LotTypeHashTable[entity.P_LotId], LotPlayTypeHashTable.PlayTypeHashTable[entity.P_PlayId], "没有需要转移的票。"));
        //                    continue;
        //                }
        //                this.LotMachine.Log.Info(string.Concat(LotPlayTypeHashTable.LotTypeHashTable[entity.P_LotId], LotPlayTypeHashTable.PlayTypeHashTable[entity.P_PlayId], "有可转移的票 ", waitTranferTickets.Count, " 张"));
        //                List<M_MachineEntity> machineList = _machineService.GetEnableAndUseMachineList(entity.P_LotId, entity.P_PlayId);

        //                if (machineList.Count <= 0)
        //                {
        //                    this.LotMachine.Log.Warn(string.Concat(LotPlayTypeHashTable.LotTypeHashTable[entity.P_LotId], LotPlayTypeHashTable.PlayTypeHashTable[entity.P_PlayId], "的票没有可供转移的彩票机...",
        //                                       "请确认", LotPlayTypeHashTable.LotTypeHashTable[entity.P_LotId], LotPlayTypeHashTable.PlayTypeHashTable[entity.P_PlayId], "的可出票彩票机"));
        //                    continue;
        //                }
        //                int transferedTicketNum = 0;
        //                foreach (L_LotTicketEntity ticket in waitTranferTickets)
        //                {
        //                    machineList.Sort(delegate(M_MachineEntity mac1, M_MachineEntity mac2) { return mac1.M_TicketNum.CompareTo(mac2.M_TicketNum); });
        //                    bool isTransfered = false;
        //                    while (machineList.Count >= 1)
        //                    {
        //                        M_MachineEntity targetMachine = machineList[0];
        //                        if (targetMachine.M_Money < _minMachineMoney)
        //                        {
        //                            machineList.RemoveAt(0);
        //                            this.LotMachine.Log.Warn(string.Concat("转移票", ticket.L_TicketSn, "不成功：彩票机", targetMachine.M_Number, "余额不足。程序将尝试其它彩票机进行转移。"));
        //                            continue;
        //                        }
        //                        string macNumber = ticket.L_MacNumber;
        //                        ticket.L_MacNumber = targetMachine.M_Number;
        //                        targetMachine.M_TicketNum += 1;
        //                        transferedTicketNum++;
        //                        try
        //                        {
        //                            _lotTicketService.TransferTaskLottickets(ticket.LotId, ticket.L_Id, macNumber, targetMachine.M_Number);
        //                        }
        //                        catch (Exception ex)
        //                        {
        //                            this.LotMachine.Log.Error(string.Concat("转移票", ticket.L_TicketSn, "异常：", ex.Message));
        //                            continue;
        //                        }
        //                        isTransfered = true;
        //                        this.LotMachine.Log.Info(string.Concat("转移票" + ticket.L_TicketSn + "从彩票机", machine.M_Number, "成功转移到彩票机", targetMachine.M_Number));
        //                        break;
        //                    }
        //                    if (!isTransfered)
        //                    {
        //                        this.LotMachine.Log.Warn(string.Concat("转移票", ticket.L_TicketSn, "不成功：所有符合条件的彩票机均余额不足。请充值或刷新机器额度。"));
        //                    }
        //                }
        //                this.LotMachine.Log.Info(string.Concat(LotPlayTypeHashTable.LotTypeHashTable[entity.P_LotId], LotPlayTypeHashTable.PlayTypeHashTable[entity.P_PlayId], "成功转移的票 ", transferedTicketNum, " 张"));
        //            }
        //        }
        //        else
        //        {
        //            this.LotMachine.Log.Info(string.Concat("彩票机 ", machine.M_Number, " 没有配置可出票类型。"));
        //        }
        //        return (int)(WcfCodeEnum.TransferTasksSucess);
        //    }
        //    catch (Exception ex)
        //    {
        //        this.LotMachine.Log.Error(string.Format("【{0}】【{1}】异常：{2}\r\n{3}", "转移出票任务", this.LotMachine.MachineInfo.M_Number, ex.Message, ex.StackTrace));
        //        return (int)(WcfCodeEnum.TransferTasksException);
        //    }
        //}

        //public void TransferTasks(List<M_MachineEntity> machineList)
        //{
        //    M_LotTypeService lotTypeService=new M_LotTypeService();
        //    List<M_LotTypeEntity> lotTypeList = lotTypeService.GetEnabledLotTypeList();
        //    foreach (M_LotTypeEntity lotTypeEntity in lotTypeList)
        //    {
        //        int transferedTicketNum = 0;
        //        if(lotTypeEntity.L_LotId==(int)Lottype.Bd)
        //        {
        //            //北单转移票
        //            BdL_LotTicketService bdLotTicketService=new BdL_LotTicketService();
        //            List<L_LotTicketEntity> waitTranferTickets =
        //                bdLotTicketService.GetWaitTransferTicketList(lotTypeEntity.L_LotId,
        //                                                             LotMachine.MachineInfo.M_Number, 0);
        //            if (waitTranferTickets == null || waitTranferTickets.Count == 0)
        //            {
        //                LotMachine.Log.Info(string.Concat(lotTypeEntity.L_LotName, "没有需要转移的票。"));
        //                continue;
        //            }
        //            foreach (L_LotTicketEntity ticket in waitTranferTickets)
        //            {
        //                M_MachineEntity targetMachine = null;
        //                for (int i = 0; i < machineList.Count; i++)
        //                {
        //                    M_MachineEntity machine = machineList[i];
        //                    if (machine.M_Money < ticket.L_Money)
        //                    {
        //                        continue;
        //                    }
        //                    targetMachine = machine;
        //                    machineList.RemoveAt(i);
        //                    machineList.Add(machine);
        //                    break;
        //                }
        //                if (targetMachine == null)
        //                {
        //                    LotMachine.Log.Warn(string.Concat("转移票[", ticket.L_TicketSn, "]不成功，请检查目标机器额度"));
        //                    continue;
        //                }
        //                string macNumber = ticket.L_MacNumber;
        //                string targetMacNumber = targetMachine.M_Number;
        //                ticket.L_MacNumber = targetMacNumber;

        //                try
        //                {
        //                    bdLotTicketService.TransferTicket(ticket.LotId, ticket.L_Id, macNumber, targetMacNumber);
        //                    targetMachine.M_TicketNum += 1;
        //                    transferedTicketNum++;
        //                    LotMachine.Log.Info(string.Concat("转移票成功。彩种[", ticket.L_LotName, "] 玩法[", ticket.L_PlayName, "] 金额[", ticket.L_Money.ToString("0"), "] 生产流水号[" + ticket.L_TicketSn + "] 从彩票机[", macNumber, "]到彩票机[", targetMacNumber, "]"));
        //                }
        //                catch (Exception ex)
        //                {
        //                    LotMachine.Log.Error(string.Concat("转移票[", ticket.L_TicketSn, "] 异常：", ex.Message));
        //                    continue;
        //                }
        //            }
        //        }
        //        else if (lotTypeEntity.L_LotId == (int)Lottype.Jz || lotTypeEntity.L_LotId == (int)Lottype.Jl || lotTypeEntity.L_LotId == (int)Lottype.Jm)
        //        {
        //            //竟彩转移票
        //            JcL_LotTicketService jcLotTicketService=new JcL_LotTicketService();
        //            List<L_LotTicketEntity> waitTranferTickets=jcLotTicketService.GetWaitTransferTicketList(lotTypeEntity.L_LotId, LotMachine.MachineInfo.M_Number,
        //                                                         0);
        //            if(waitTranferTickets==null || waitTranferTickets.Count==0)
        //            {
        //                LotMachine.Log.Info(string.Concat(lotTypeEntity.L_LotName, "没有需要转移的票。"));
        //                continue;
        //            }
        //            foreach (L_LotTicketEntity ticket in waitTranferTickets)
        //            {
        //                M_MachineEntity targetMachine = null;
        //                for (int i = 0; i < machineList.Count; i++)
        //                {
        //                    M_MachineEntity machine = machineList[i];
        //                    if(machine.M_Money<ticket.L_Money)
        //                    {
        //                        continue;
        //                    }
        //                    targetMachine = machine;
        //                    machineList.RemoveAt(i);
        //                    machineList.Add(machine);
        //                    break;
        //                }
        //                if(targetMachine==null)
        //                {
        //                    LotMachine.Log.Warn(string.Concat("转移票[", ticket.L_TicketSn, "]不成功，请检查目标机器额度"));
        //                    continue;
        //                }
        //                string macNumber = ticket.L_MacNumber;
        //                string targetMacNumber = targetMachine.M_Number;
        //                ticket.L_MacNumber = targetMacNumber;

        //                try
        //                {
        //                    jcLotTicketService.TransferTicket(ticket.LotId, ticket.L_Id, macNumber, targetMacNumber);
        //                    targetMachine.M_TicketNum += 1;
        //                    transferedTicketNum++;
        //                    LotMachine.Log.Info(string.Concat("转移票成功。彩种[", ticket.L_LotName, "] 玩法[", ticket.L_PlayName, "] 金额[", ticket.L_Money.ToString("0"), "] 生产流水号[" + ticket.L_TicketSn + "] 从彩票机[", macNumber, "]到彩票机[", targetMacNumber, "]"));
        //                }
        //                catch (Exception ex)
        //                {
        //                    LotMachine.Log.Error(string.Concat("转移票[", ticket.L_TicketSn, "] 异常：", ex.Message));
        //                    continue;
        //                }
        //            }
        //        }
        //        else
        //        {
        //            //常规彩及多乐彩转移票
        //            L_LotTicketService lotTicketService = new L_LotTicketService();
        //            List<L_LotTicketEntity> waitTranferTickets = lotTicketService.GetWaitTransferTicketList(lotTypeEntity.L_LotId, LotMachine.MachineInfo.M_Number, 0);
        //            if (waitTranferTickets == null || waitTranferTickets.Count == 0)
        //            {
        //                LotMachine.Log.Info(string.Concat(lotTypeEntity.L_LotName, "没有需要转移的票。"));
        //                continue;
        //            }
        //            LotMachine.Log.Info(string.Concat(lotTypeEntity.L_LotName, "有可转移的票 ", waitTranferTickets.Count, " 张"));

        //            //waitTranferTickets.Sort(delegate(L_LotTicketEntity ticket1, L_LotTicketEntity ticket2)
        //            //                            { return ticket1.L_Money.CompareTo(ticket2.L_Money); });



        //            foreach (L_LotTicketEntity ticket in waitTranferTickets)
        //            {
        //                //machineList.Sort(delegate(M_MachineEntity mac1, M_MachineEntity mac2) { return mac1.M_TicketNum.CompareTo(mac2.M_TicketNum); });
        //                bool isTransfered = false;
        //                while (machineList.Count >= 1)
        //                {
        //                    M_MachineEntity targetMachine = machineList[0];
        //                    if (targetMachine.M_Money < ticket.L_Money)
        //                    {
        //                        machineList.RemoveAt(0);
        //                        LotMachine.Log.Warn(string.Concat("转移票[", ticket.L_TicketSn, "]不成功：彩票机[", targetMachine.M_Number, "]余额不足。程序将尝试其它彩票机进行转移。"));
        //                        continue;
        //                    }
        //                    string macNumber = ticket.L_MacNumber;
        //                    ticket.L_MacNumber = targetMachine.M_Number;

        //                    try
        //                    {
        //                        lotTicketService.TransferTaskLottickets(ticket.LotId, ticket.L_Id, macNumber, targetMachine.M_Number);
        //                        targetMachine.M_TicketNum += 1;
        //                        transferedTicketNum++;
        //                        machineList.RemoveAt(0);
        //                        machineList.Add(targetMachine);
        //                        isTransfered = true;
        //                        LotMachine.Log.Info(string.Concat("转移票成功。彩种[", ticket.L_LotName, "] 玩法[", ticket.L_PlayName, "] 金额[", ticket.L_Money.ToString("0"), "] 生产流水号[" + ticket.L_TicketSn + "] 从彩票机[", LotMachine.MachineInfo.M_Number, "]到彩票机[", targetMachine.M_Number, "]"));
        //                    }
        //                    catch (Exception ex)
        //                    {
        //                        LotMachine.Log.Error(string.Concat("转移票[", ticket.L_TicketSn, "] 异常：", ex.Message));
        //                        continue;
        //                    }
        //                    break;
        //                }
        //                if (!isTransfered)
        //                {
        //                    LotMachine.Log.Warn(string.Concat("转移票[", ticket.L_TicketSn, "]不成功：所有符合条件的彩票机均余额不足。请充值或刷新机器额度。"));
        //                }
        //            }
        //        }
        //        LotMachine.Log.Info(string.Concat(lotTypeEntity.L_LotName, "成功转移的票 ", transferedTicketNum, " 张"));
        //        LoggingService.Info(string.Concat("【", LotMachine.MachineInfo.M_Number, "】", lotTypeEntity.L_LotName, "成功转移的票 ", transferedTicketNum, " 张"));
        //    }
        //}

        ///// <summary>
        ///// 禁用机器
        ///// </summary>
        //public int Forbid()
        //{
        //    try
        //    {
        //        M_MachineService _machineService = new M_MachineService();
        //        LotMachine.MachineInfo.M_IsUse = false;
        //        //_machineService.Update(LotMachine.MachineInfo);
        //        _machineService.UpdateIsUse(LotMachine.MachineInfo);
        //        LotMachine.Log.Info("禁用机器成功");
        //        return (int)(WcfCodeEnum.SetNotUseSucess);
        //    }
        //    catch (Exception ex)
        //    {
        //        this.LotMachine.Log.Error(string.Format("【{0}】【{1}】异常：{2}\r\n{3}", "禁用机器", this.LotMachine.MachineInfo.M_Number, ex.Message, ex.StackTrace));
        //        return (int)(WcfCodeEnum.SetNotUseException);
        //    }
        //}
        /// <summary>
        /// 启用机器
        /// </summary>
        public bool UseMachine()
        {
            try
            {
                //M_MachineService _machineService = new M_MachineService();
                //LotMachine.MachineInfo.M_IsUse = true;
                ////_machineService.Update(LotMachine.MachineInfo);
                //_machineService.UpdateIsUse(LotMachine.MachineInfo);
                //LotMachine.Log.Info("启用机器成功");
                return true;
            }
            catch (Exception ex)
            {
                this.LotMachine.Log.Error(string.Format("【{0}】【{1}】异常：{2}\r\n{3}", "启用机器", this.LotMachine.MachineInfo.M_Number, ex.Message, ex.StackTrace));
                return false;
            }
        }
        /// <summary>
        /// 重新加载配置
        /// </summary>
        public bool ReloadConfig()
        {
            try
            {
                //M_MachineConfigService machineConfigService = new M_MachineConfigService();
                //M_MachineModeConfigService machineModeConfigService = new M_MachineModeConfigService();
                //LotMachine.MachineInfo.MachineConfigEntity = machineConfigService.GetMachineConfig(LotMachine.MachineInfo.M_Id);
                //LotMachine.MachineInfo.MachineModeConfigs = machineModeConfigService.GetMachineConfigSortedDictionary(LotMachine.MachineInfo.M_Id);
                //this.LotMachine.Log.Info("重新加载配置成功");
                return true;
            }
            catch (Exception exception)
            {
                this.LotMachine.Log.Info(string.Concat("重新加载配置异常。错误信息：", exception.Message));
                return false;
            }
        }

        public void PrintTestTicket()
        {
            try
            {
                CaptureDataInfo captureData = LotMachine.PrintTestTicket(true);
                //if(captureData.CaptureDataBytes.Length>0)
                //{
                //    if (LotMachineService.IsUseComputerPrinter)
                //    {
                //        //LotMachineService.PrintETicket(LotMachine.MachineInfo.M_Number, captureData.CaptureDataBytes);
                //        LotMachineService.PrinterClient.AddBytes(captureData.CaptureDataBytes);
                //    }
                //}
            }
            catch (Exception exception)
            {
                this.LotMachine.Log.Error(string.Concat("打印测试票异常。错误信息：", exception));
            }
        }
    }
}
