using System;
using System.Collections.Generic;
using System.Threading;
using ChuPiao.AutoPrint.Machine;
using ChuPiao.AutoPrint.Machine.Models;
using ChuPiao.Common.Enums;
using ChuPiao.Common.Models;
using ChuPiao.Common.Communication.GtdJson.Packs;
using ChuPiao.Common.Communication.GtdJson;
using ChuPiao.Common.Core.Utils;
using System.Text.RegularExpressions;

namespace ChuPiao.AutoPrint.Services.AutoEncash
{
    public class AutoEncashService
    {

        public int EncashOption;
        /// <summary>
        /// 兑奖中
        /// </summary>
        public event EventHandler<TicketEventArgs> Encashing;
        /// <summary>
        /// 兑奖完成
        /// </summary>
        public event EventHandler<TicketEventArgs> Encashed;
        /// <summary>
        /// 兑奖数据加载完毕
        /// </summary>
        public event EventHandler EncashTicketLoaded;
        /// <summary>
        /// 状态变化
        /// </summary>
        public event EventHandler<MachineStatusArgs> StatusChanged;
        public ILotMachine LotMachine;
        private Thread _workThread;
        public void Start()
        {
            if (LotMachine.MachineInfo.M_Status == (int)MachineStatusEnum.Stopped)
            {
                LotMachine.LastMachineReport = null;
                _isStop = false;
                //if (LotMachine.MachineInfo.M_Type == (int)MachineType.JxJingCaiV1 || LotMachine.MachineInfo.M_Type == (int)MachineType.TjJingCaiV1)
                //{
                //    _workThread = new Thread(new ThreadStart(DoTaskForJc));
                //}
                //else
                //{
                //    _workThread = new Thread(new ThreadStart(DoTask));
                //}
                _workThread = new Thread(new ThreadStart(DoTaskForJc));

                _workThread.Start();
                UpdateMachineStatus(MachineStatusEnum.Encashing);
                LotMachine.Log.Info("启动打印");
                LoggingService.Info(string.Concat(LotMachine.MachineInfo.M_Number, "启动打印"));
            }
        }

        public void Stop()
        {
            //if (LotMachine.MachineInfo.M_Status == (int)MachineStatusEnum.Encashing)
            if (!_isStop)
            {
                UpdateMachineStatus(MachineStatusEnum.Stopping);
                Wait4Job.Set();
                LotMachine.Log.Info("停止打印中");
                LoggingService.Info(string.Concat(LotMachine.MachineInfo.M_Number, "停止打印中"));
                _isStop = true;
            }
        }

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

        public EventWaitHandle Wait4Job
        {
            get
            {
                return _wait4Job;
            }
        }
        /// <summary>
        /// 兑奖错误
        /// </summary>
        public event EventHandler<TicketEventArgs> EncashTicketError;
        /// <summary>
        /// 等待兑奖队列
        /// </summary>
        public Queue<L_LotTicketEntity> WaitEncashTickets = new Queue<L_LotTicketEntity>();
        /// <summary>
        /// 全部兑奖数据
        /// </summary>
        public List<L_LotTicketEntity> AllEncashTickets=new List<L_LotTicketEntity>();
        /// <summary>
        /// 等待兑奖票数
        /// </summary>
        public int WaitEncashTicketCount
        {
            get
            {
                lock (WaitEncashTickets)
                {
                    return WaitEncashTickets.Count;
                }
            }
        }
        /// <summary>
        /// 漏兑票数
        /// </summary>
        public int LoseEncashTicket = 0;
        /// <summary>
        /// 漏兑金额
        /// </summary>
        public decimal LoseEncashMoney = 0;

        public const int WaitTime = 10;
        public const int MaxOneLoad = 100;
        /// <summary>
        /// 两张票的间隔
        /// </summary>
        public int TicketInterval = 5000;
        private bool _isStop = true;
        /*private void DoTask()
        {
            if (LotMachine.MachineInfo.M_Type == (int)MachineType.TjBeiDanV1 || LotMachine.MachineInfo.M_Type == (int)MachineType.TjBeiDanV2)
            {
                LotMachine.VirtualKeyboard.Stop();
                Thread.Sleep(1000);
            }
            DateTime startTime = DateTime.Now;
            int ticketcount = WaitEncashTicketCount;
            while (!_isStop)
            {
                if (WaitEncashTicketCount > 0)
                {
                    L_LotTicketEntity ticket;
                    lock (WaitEncashTickets)
                    {
                        ticket = WaitEncashTickets.Dequeue();
                    }

                    try
                    {

                        OnEncashing(ticket);
                        LotMachine.Log.Info(string.Concat("生产流水号：",ticket.L_TicketSn," 票号：",ticket.L_TicketCode," 奖金：",ticket.L_GetMoney," 开始兑奖……"));
                        ticket.EncashOption = EncashOption;//兑奖选项，1--首次兑奖，2--二次兑奖
                        LotMachine.Encash(ticket);
                        if (ticket.L_EncashStatus == (int)EncashStatus.Success)
                        {
                            EncashedTotalMoney += ticket.L_GetMoney;
                            EncashedTotalTicket += 1;
                            LotMachine.LastEncashSuc = true;
                        }
                        else
                        {
                            LotMachine.LastEncashSuc = false;
                        }
                        
                        //int a = LotMachine.MachineInfo.MachineConfigEntity.C_EncashInterval;
                        //Wait(TicketInterval);
                        Wait(LotMachine.MachineInfo.MachineConfigEntity.C_EncashInterval);
                        if(ticket.LotId==(int)Lottype.Bd)
                        {
                            if(ticket.L_EncashStatus==(int)EncashStatus.Success)
                            {
                                OnEncashed(ticket);
                            }
                        }
                        else
                        {
                            OnEncashed(ticket);
                        }
                        
                    }
                    catch (Exception ex)
                    {
                        ReportError(ticket, ex.Message);
                    }
                    
                }
                else
                {
                    Thread.Sleep(500);
                    break;
                }
            }
            DateTime endTime = DateTime.Now;
            TimeSpan timeSpan = endTime.Subtract(startTime);

            LotMachine.Log.Info(string.Concat("兑奖票数：",ticketcount," 总耗时：",timeSpan.Hours,"小时",timeSpan.Minutes,"分钟",timeSpan.Seconds,"秒 平均",timeSpan.TotalSeconds/ticketcount,"秒/票"));

            UpdateMachineStatus(MachineStatusEnum.Stopped);
            LotMachine.Log.Info("停止兑奖");
            LoggingService.Info(string.Concat(LotMachine.MachineInfo.M_Number, "停止兑奖"));
            if (LotMachine.MachineInfo.M_Type == (int)MachineType.TjBeiDanV1 || LotMachine.MachineInfo.M_Type == (int)MachineType.TjBeiDanV2)
            {
                //LotMachine.StartDriver();
                LotMachine.VirtualKeyboard.Start();
            }
        }*/
        private void DoTaskForJc()
        {
            DateTime startTime = DateTime.Now;
            int ticketcount = WaitEncashTicketCount;
            List<L_LotTicketEntity> waitSetEncashSucTickets=new List<L_LotTicketEntity>();
            LotMachine.LastMachineReport = null; 
            DecodeMachineReport decodeMachineReport=null;
            R_MachineReportEntity firstMachineReport=null;
            int ydticketcount = WaitEncashTickets.Count;
            decimal ydticketmoney = 0;
            foreach (L_LotTicketEntity entity in WaitEncashTickets)
            {
                ydticketmoney += entity.L_GetMoney;
            }
            LoseEncashTicket = 0;
            LoseEncashMoney = 0;
            while (!_isStop)
            {
                if (WaitEncashTicketCount > 0)
                {
                    L_LotTicketEntity ticket;
                    lock (WaitEncashTickets)
                    {
                        ticket = WaitEncashTickets.Dequeue();
                    }

                    try
                    {
                        if (!string.IsNullOrEmpty(ticket.L_PrnText.Trim()))
                        {
                            OnEncashing(ticket);

                            if (!LotMachine.MachineInfo.M_IsAutoEncash)
                            {
                                LotMachine.Log.Info(string.Concat(" 票号：", ticket.L_TicketCode, " 开始打印……"));
                                LotMachineService.PrintETicket(LotMachine.MachineInfo.M_Number, TicketTextUtil.DecryptAndDecompress(ticket.L_PrnText));
                            }
                            else
                            { 
                                LotMachine.Log.Info(string.Concat("票号：", ticket.L_TicketCode, " 开始兑奖……"));

                                LotMachine.Encash(ticket);
                            }

                            EncashedTotalTicket += 1;

                            Wait(1500);

                            OnEncashed(ticket);
                        }
                        else
                        {
                            LotMachine.Log.Info(string.Concat(" 票号：", ticket.L_TicketCode, " 非盒子出票，无法打印！"));
                            Wait(1500);
                        }

                    }
                    catch (Exception ex)
                    {
                        LotMachine.Log.Warn(string.Concat("打印异常，错误信息：", ex));
                        this.Stop();
                        //ReportError(ticket, ex.Message);
                        break;
                    }

                }
                else
                {
                    Thread.Sleep(500);
                    break;
                }
            }
            

            DateTime endTime = DateTime.Now;
            TimeSpan timeSpan = endTime.Subtract(startTime);

            LotMachine.Log.Info(string.Concat("打印票数：", ticketcount, " 总耗时：", timeSpan.Hours, "小时", timeSpan.Minutes, "分钟", timeSpan.Seconds, "秒 平均", timeSpan.TotalSeconds / ticketcount, "秒/票"));

            UpdateMachineStatus(MachineStatusEnum.Stopped);
            LotMachine.Log.Info("停止打印");
            LoggingService.Info(string.Concat(LotMachine.MachineInfo.M_Number, "停止打印"));
            //兑奖完成后进入销售界面
            //LotMachine.EnterSaleGui();
        }
        private bool SetEncashSuc(List<L_LotTicketEntity> waitSetEncashSucTickets)
        {
            DecodeMachineReport decodeMachineReport = new DecodeMachineReport();
            for (int i = 0; i < 1; i++)
            {
                LotMachine.PrintCurrentDayReport(decodeMachineReport,false);
                if (decodeMachineReport.DecodeSuccess)
                {
                    break;
                }
                else
                {
                    LotMachine.Log.Info(string.Concat("打印报表失败：", decodeMachineReport.ErrorMessage));
                }
            }
            if (decodeMachineReport.DecodeSuccess)
            {
                int tmpTotalTicket = waitSetEncashSucTickets.Count;
                decimal tmpTotalMoney = 0;
                List<string> ticketSns=new List<string>();
                foreach (L_LotTicketEntity entity in waitSetEncashSucTickets)
                {
                    tmpTotalMoney += entity.L_GetMoney;
                    ticketSns.Add(entity.L_TicketSn);
                }

                R_MachineReportEntity currentMachineReport = decodeMachineReport.MachineReportEntity;
                LotMachine.Log.Info(string.Concat("最近一次报表 已兑奖票数：", LotMachine.LastMachineReport.R_EncashTicket, " 已兑奖金额：", LotMachine.LastMachineReport.R_EncashMoney, "当前报表 已兑奖票数：", currentMachineReport.R_EncashTicket, " 已兑奖金额：", currentMachineReport.R_EncashMoney," 本批次应兑票数：",tmpTotalTicket," 应兑金额：",tmpTotalMoney));
                if (currentMachineReport.R_EncashTicket == LotMachine.LastMachineReport.R_EncashTicket + tmpTotalTicket && currentMachineReport.R_EncashMoney == LotMachine.LastMachineReport.R_EncashMoney + tmpTotalMoney)
                {
                    //兑奖成功
                    foreach (L_LotTicketEntity ticketEntity in waitSetEncashSucTickets)
                    {
                        //ticketEntity.L_EncashStatus = (int)EncashStatus.Success;
                        //L_LotTicketService lotTicketService =new L_LotTicketService();
                        //lotTicketService.SetTicketEncashed(ticketEntity);
                        //LotMachine.Log.Info(string.Concat("设置生产流水号：", ticketEntity.L_TicketSn, "兑奖成功"));
                    }
                }
                else
                {
                    LotMachine.Log.Info(string.Concat("报表已兑奖数据与实际应兑数据不符，未能设置兑奖成功，流水号：",string.Join(",",ticketSns.ToArray())));
                }
                LotMachine.LastMachineReport = currentMachineReport;
                return true;
            }
            else
            {
                LotMachine.Log.Warn(string.Concat("打印报表失败：", decodeMachineReport.ErrorMessage));
                Stop();
                return false;
            }
            
        }
        private void Wait(int wait)
        {
            LotMachine.Log.Info(string.Concat("等待：",wait,"毫秒"));
            while (wait > 0)
            {
                wait -= 100;
                Thread.Sleep(100);
                //Application.DoEvents();
                if (LotMachine.MachineInfo.M_Status != (int)MachineStatusEnum.Encashing)
                {
                    break;
                }
            }
        }
        public void OnEncashing(L_LotTicketEntity ticket)
        {
            if (Encashing != null)
            {
                Encashing(this, new TicketEventArgs(ticket));
            }
        }
        public void OnEncashed(L_LotTicketEntity ticket)
        {
            if (Encashed != null)
            {
                Encashed(this, new TicketEventArgs(ticket));
            }
        }
        public void OnEncashTicketLoaded()
        {
            if(EncashTicketLoaded!=null)
            {
                EncashTicketLoaded(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;
        }

        private void ReportError(L_LotTicketEntity ticket, string message)
        {
            //更新机器状态
            LotMachine.MachineInfo.M_Status = (int)MachineStatusEnum.Error;
            LotMachine.MachineInfo.M_LastErrorTitle = message;
            LotMachine.MachineInfo.M_LastErrorTime = DateTime.Now;
            LotMachine.MachineInfo.M_ErrorNum += 1;
            try
            {
                //M_MachineService machineService = new M_MachineService();
                //machineService.UpdateMachineErrorInfo(LotMachine.MachineInfo);
                this.UpdateMachineStatus(MachineStatusEnum.Error);
                LotMachine.Log.Info(string.Concat("报告错误：", message));
            }
            catch (Exception exc)
            {
                LotMachine.Log.Error("兑奖线程中彩票机出错时更新机器错误状态异常：" + exc.Message);
            }
            if (null != EncashTicketError)
            {
                EncashTicketError(this, new TicketEventArgs(ticket));
            }
            Wait4Job.Reset();
            Wait4Job.WaitOne();
        }

        public decimal TotalMoney = 0;
        public int TotalTicket = 0;
        public decimal EncashedTotalMoney = 0;
        public int EncashedTotalTicket = 0;
        public decimal TotalMoneyOfAssign = 0;
        public int TotalTicketOfAssign = 0;

        public void OnStatusChanged(MachineStatusEnum machineStatus)
        {
            EventHandler<MachineStatusArgs> handler = StatusChanged;
            if (handler != null)
            {
                handler(this, new MachineStatusArgs(machineStatus));
            }
        }
        /// <summary>
        /// 维护机器状态
        /// </summary>
        /// <param name="status"></param>
        public void UpdateMachineStatus(MachineStatusEnum status)
        {
            try
            {
                LotMachine.MachineInfo.M_Status = (int)status;
                //M_MachineService machineService = new M_MachineService();
                //machineService.UpdateMachineStatus(LotMachine.MachineInfo);
                LotMachine.Log.Info(string.Concat("更新机器状态：", status));
                OnStatusChanged(status);
            }
            catch (Exception exception)
            {
                LotMachine.Log.Info(string.Concat("更新机器状态：", status, "失败:", exception.Message));
            }

        }
        /// <summary>
        /// 按期加载兑奖票
        /// </summary>
        /// <param name="lotTypeEntity"></param>
        /// <param name="expectEntity"></param>
        /// <param name="encashLoadType"></param>
        public void LoadEncashTickets(M_LotTypeEntity lotTypeEntity, L_ExpectEntity expectEntityFrom,L_ExpectEntity expectEntityTo, EncashLoadType encashLoadType)
        {
            //this.TotalMoney = 0;
            //this.TotalTicket = 0;
            //this.EncashedTotalMoney = 0;
            //this.EncashedTotalTicket = 0;
            //this.TotalMoneyOfAssign = 0;
            //this.TotalTicketOfAssign = 0;
            //this.WaitEncashTickets.Clear();
            //L_LotTicketService _lotTicketService = new L_LotTicketService();
            //EncashTicketSummaryEntity encashTicketSummaryEntity = new EncashTicketSummaryEntity();
            //if(encashLoadType==EncashLoadType.ByMacNumber)
            //{
            //    AllEncashTickets = _lotTicketService.GetMachineEncashTickets(lotTypeEntity.L_LotId, expectEntityFrom.E_Expect, expectEntityTo.E_Expect, LotMachine.MachineInfo.M_Number);
            //    encashTicketSummaryEntity = _lotTicketService.GetMachineEncashTicketSummary(lotTypeEntity.L_LotId, expectEntityFrom.E_Expect, expectEntityTo.E_Expect, LotMachine.MachineInfo.M_Number);
            //    LotMachine.Log.Info(string.Concat("加载彩种：", lotTypeEntity.L_LotName, " 期号：", expectEntityFrom.E_Expect, "-", expectEntityTo.E_Expect, " 机器号：", LotMachine.MachineInfo.M_Number, " 可兑奖票", AllEncashTickets.Count, "张"));
            //}
            //else
            //{
            //    AllEncashTickets = _lotTicketService.GetMachineEncashTickets(lotTypeEntity.L_LotId, expectEntityFrom.E_Expect, expectEntityTo.E_Expect, string.Empty);
            //    encashTicketSummaryEntity = _lotTicketService.GetMachineEncashTicketSummary(lotTypeEntity.L_LotId, expectEntityFrom.E_Expect, expectEntityTo.E_Expect, string.Empty);
            //    LotMachine.Log.Info(string.Concat("加载彩种：", lotTypeEntity.L_LotName, " 期号：", expectEntityFrom.E_Expect, "-", expectEntityTo.E_Expect, " 全部机器可兑奖票", AllEncashTickets.Count, "张"));
            //}
            //TotalMoneyOfAssign = encashTicketSummaryEntity.GetMoney;
            //TotalTicketOfAssign = encashTicketSummaryEntity.Count;
            //foreach (L_LotTicketEntity entity in AllEncashTickets)
            //{
            //    TotalMoney += entity.L_GetMoney;
            //    TotalTicket += 1;
            //}
            //OnEncashTicketLoaded();

        }
        List<L_ExpectEntity> expects=new List<L_ExpectEntity>();
        private int sucLoadedExpectCount = 0;
        private DateTime beginTime=DateTime.Now;


        private M_LotTypeEntity currentLotEntity;
        private string currentAbbdate;
        private bool isBig=false;

        private void LoadMethod()
        {
            try
            {
                int page = 1;
                while (true)
                {
                    A10003GetBonus pack = new A10003GetBonus();
                    pack.AgentId = LotMachine.MachineInfo.M_Number;
                    pack.Salt = LotMachine.MachineInfo.M_Salt;
                    pack.LotId = currentLotEntity.L_LotId;
                    pack.AbbDate = Int32.Parse(currentAbbdate);
                    pack.Page = page;
                    pack.Size = 5;
                    pack.IsBig = isBig;
                    A10003GetBonusRet packRet = PackManager.Instance.Send(pack) as A10003GetBonusRet;
                    if (packRet.TicketList.Count == 0)
                    {
                        break;
                    }

                    //由于前期没有考虑会用票号密码自动兑奖（感觉是反出票点的东西），所以没有回写密码
                    //然后新老系统都没有时间搞接口加字段这个事情，所以反人类地，要从电子票中再解析密码
                    string RegexTicketCode = @"([0-9]{24}) (\d{8}) ";     //2020.9.3  竞足跟竞篮统一
                    string RegexTicketCode2 = @"([0-9]{6}-[0-9]{6}-[0-9]{6}-[0-9]{2}) (\d{8}) ";  //竞彩格式备用
                    string RegexTicketCode1 = @"([0-9]{6}-[0-9]{6}-[0-9]{6}-[0-9]{6}) (\d{6}) ";  //常规彩格式
                    
                    foreach (L_LotTicketEntity ticket in packRet.TicketList)
                    {
                        CaptureDataInfo info = new CaptureDataInfo(TicketTextUtil.DecryptAndDecompress(ticket.L_PrnText));

                        if (currentLotEntity.L_LotId == (int)Lottype.Jz || currentLotEntity.L_LotId == (int)Lottype.Jl)
                        {
                            Regex regex = new Regex(RegexTicketCode);
                            Match match = regex.Match(info.CaptureDataString);
                            if (match.Success)
                            {
                                ticket.L_TicketCode = match.Groups[1].Value.Replace("-", "");
                                ticket.L_Password = match.Groups[2].Value;
                            }
                            else
                            {
                                regex = new Regex(RegexTicketCode2);
                                match = regex.Match(info.CaptureDataString);
                                if (match.Success)
                                {
                                    ticket.L_TicketCode = match.Groups[1].Value.Replace("-", "");
                                    ticket.L_Password = match.Groups[2].Value;
                                }
                                else
                                {
                                    throw new Exception("没有解析出票号和密码！");
                                }
                            }
                        }
                        else
                        {
                            Regex regex = new Regex(RegexTicketCode1);
                            Match match = regex.Match(info.CaptureDataString);
                            if (match.Success)
                            {
                                ticket.L_TicketCode = match.Groups[1].Value.Replace("-", "");
                                ticket.L_Password = match.Groups[2].Value;
                            }
                            else
                            {
                                throw new Exception("没有解析出票号和密码！");
                            }
                        }
                    }

                    AllEncashTickets.AddRange(packRet.TicketList);
                    TotalTicket += packRet.TicketList.Count;
                    if (packRet.TicketList.Count < pack.Size)
                    {
                        break;
                    }
                    page++;
                    Thread.Sleep(1000);
                }

                if (TotalTicket == 0)
                {
                    LotMachine.Log.Info(LotMachine.MachineInfo.M_Number + "没有可兑奖的票！");
                }
            }
            catch (Exception ex)
            {
                LotMachine.Log.Error(string.Concat("获取中奖票列表失败：", ex.ToString()));
            }
            OnEncashTicketLoaded();
        }

        /// <summary>
        /// 按结算日期加载兑奖票
        /// </summary>
        /// <param name="lotTypeEntity"></param>
        /// <param name="abbdate"></param>
        /// <param name="encashLoadType"></param>
        public void LoadEncashTicketsByAbbdate(M_LotTypeEntity lotTypeEntity, string abbdate,bool isbig)
        {
            currentLotEntity = lotTypeEntity;
            currentAbbdate = abbdate;
            isBig = isbig;

            this.TotalTicket = 0;;
            this.EncashedTotalTicket = 0;

            this.WaitEncashTickets.Clear();

            AllEncashTickets.Clear();

            new Thread(LoadMethod).Start();
        }
        /// <summary>
        /// 按结算日期加载兑奖票
        /// </summary>
        /// <param name="lotTypeEntity"></param>
        /// <param name="abbdate"></param>
        /// <param name="encashLoadType"></param>
        public void LoadEncashTicketsByAbbdate(M_LotTypeEntity lotTypeEntity, string abbdate, EncashLoadType encashLoadType)
        {
            //this.TotalMoney = 0;
            //this.TotalTicket = 0;
            //this.EncashedTotalMoney = 0;
            //this.EncashedTotalTicket = 0;
            //this.TotalMoneyOfAssign = 0;
            //this.TotalTicketOfAssign = 0;
            //this.WaitEncashTickets.Clear();
            //this.sucLoadedExpectCount = 0;
            //JcL_LotTicketService jcLotTicketService=new JcL_LotTicketService();

            //AllEncashTickets.Clear();
            //List<L_LotTicketEntity> encashTickets=new List<L_LotTicketEntity>();
            //EncashTicketSummaryEntity encashTicketSummaryEntity=new EncashTicketSummaryEntity();
            //if (encashLoadType == EncashLoadType.ByMacNumber)
            //{
            //    beginTime = DateTime.Now;
            //    JcL_ExpectService jcLExpectService=new JcL_ExpectService();
            //    expects= jcLExpectService.GetExpectListByAbbDate(lotTypeEntity.L_LotId, int.Parse(abbdate));
            //    LotMachine.Log.Info(string.Concat("加载彩种：", lotTypeEntity.L_LotName, " 结算日期：", abbdate," 结算场次：",expects.Count,"场"));
            //    foreach (L_ExpectEntity expect in expects)
            //    {
            //        Thread thread=new Thread(new ParameterizedThreadStart(DoLoadByExpect));
            //        thread.Start(expect);
            //    }
            //}
            //else
            //{
            //    encashTickets = jcLotTicketService.GetMachineEncashTickets(lotTypeEntity.L_LotId, abbdate, string.Empty);
            //    encashTicketSummaryEntity = jcLotTicketService.GetMachineEncashTicketSummary(lotTypeEntity.L_LotId, abbdate,
            //                                                                          string.Empty);
            //    LotMachine.Log.Info(string.Concat("加载彩种：", lotTypeEntity.L_LotName, " 结算日期：", abbdate, " 全部机器可兑奖票", encashTickets.Count, "张"));

            //    TotalMoneyOfAssign = encashTicketSummaryEntity.GetMoney;
            //    TotalTicketOfAssign = encashTicketSummaryEntity.Count;
            //    if (LoseEncashTicket == 1)
            //    {
            //        foreach (L_LotTicketEntity entity in encashTickets)
            //        {
            //            if (entity.L_GetMoney == LoseEncashMoney)
            //            {
            //                AllEncashTickets.Add(entity);
            //            }
            //            else
            //            {
            //                LotMachine.Log.Info(string.Concat("流水号：", entity.L_TicketSn, " 票号：", entity.L_TicketCode, " 奖金：", entity.L_GetMoney,
            //                                                  " 奖金不等于漏兑金额，忽略加载"));
            //            }
            //        }
            //    }
            //    else if (LoseEncashTicket > 1)
            //    {
            //        foreach (L_LotTicketEntity entity in encashTickets)
            //        {
            //            if (entity.L_GetMoney < LoseEncashMoney)
            //            {
            //                AllEncashTickets.Add(entity);
            //            }
            //            else
            //            {
            //                LotMachine.Log.Info(string.Concat("流水号：", entity.L_TicketSn, " 票号：", entity.L_TicketCode, " 奖金：", entity.L_GetMoney,
            //                                                  " 奖金不小于漏兑金额，忽略加载"));
            //            }
            //        }
            //    }
            //    else
            //    {
            //        AllEncashTickets.AddRange(encashTickets);
            //    }
            //    foreach (L_LotTicketEntity entity in AllEncashTickets)
            //    {
            //        TotalMoney += entity.L_GetMoney;
            //        TotalTicket += 1;
            //    }
            //    OnEncashTicketLoaded();
            //}
        }

        private void DoLoadByExpect(object obj)
        {
            //L_ExpectEntity expect = obj as L_ExpectEntity;
            //if (expect == null) return;
            //try
            //{
                
            //    DateTime startTime = DateTime.Now;
            //    List<L_LotTicketEntity> tmpList = new JcL_LotTicketService().GetMachineEncashTickets(expect.LotId,
            //                                                                                 expect.E_AbbDate.ToString(),
            //                                                                                 expect.E_Expect,
            //                                                                                 LotMachine.MachineInfo.
            //                                                                                     M_Number);
            //    foreach (L_LotTicketEntity entity in tmpList)
            //    {
            //        if (entity.L_EncashStatus == (int)EncashStatus.EnacashAble)
            //        {
            //            if (LoseEncashTicket == 1)
            //            {
            //                if (entity.L_GetMoney == LoseEncashMoney)
            //                {
            //                    AllEncashTickets.Add(entity);
            //                }
            //                else
            //                {
            //                    LotMachine.Log.Info(string.Concat("流水号：", entity.L_TicketSn, " 票号：", entity.L_TicketCode, " 奖金：", entity.L_GetMoney,
            //                                                      " 奖金不等于漏兑金额，忽略加载"));
            //                }
            //            }
            //            else if (LoseEncashTicket > 1)
            //            {
            //                if (entity.L_GetMoney < LoseEncashMoney)
            //                {
            //                    AllEncashTickets.Add(entity);
            //                }
            //                else
            //                {
            //                    LotMachine.Log.Info(string.Concat("流水号：", entity.L_TicketSn, " 票号：", entity.L_TicketCode, " 奖金：", entity.L_GetMoney,
            //                                                      " 奖金不小于漏兑金额，忽略加载"));
            //                }
            //            }
            //            else
            //            {
            //                AllEncashTickets.Add(entity);
            //            }
            //        }
            //        TotalTicketOfAssign += 1;
            //        TotalMoneyOfAssign += entity.L_GetMoney;
            //    }
            //    LotMachine.Log.Info(string.Concat("加载彩种：", expect.LotId, " 结算日期：", expect.E_AbbDate, " 结算场次：", expect.E_Expect, " 机器号：", LotMachine.MachineInfo.M_Number, " 兑奖票", tmpList.Count, "张 耗时：", DateTime.Now.Subtract(startTime).TotalMilliseconds, "毫秒"));
            //}
            //catch (Exception ex)
            //{
            //    LotMachine.Log.Error(ex);
            //}
            //finally
            //{
            //    sucLoadedExpectCount++;
            //    if(sucLoadedExpectCount==expects.Count)
            //    {
            //        foreach (L_LotTicketEntity entity in AllEncashTickets)
            //        {
            //            TotalMoney += entity.L_GetMoney;
            //            TotalTicket += 1;
            //        }
            //        AllEncashTickets.Sort(delegate(L_LotTicketEntity x, L_LotTicketEntity y) { return y.L_GetMoney.CompareTo(x.L_GetMoney); });

            //        LotMachine.Log.Info(string.Concat("加载彩种：", expect.LotId, " 结算日期：", expect.E_AbbDate, " 机器号：", LotMachine.MachineInfo.M_Number, " 可兑奖票", TotalTicket, "张 耗时：", DateTime.Now.Subtract(beginTime).TotalSeconds, "秒"));
            //        OnEncashTicketLoaded();
            //    }
            //}
            
        }
        /// <summary>
        /// 按结算日期加载兑奖票
        /// </summary>
        /// <param name="lotTypeEntity"></param>
        /// <param name="abbdate"></param>
        /// <param name="encashLoadType"></param>
        public void LoadEncashTicketsByAbbdate2(M_LotTypeEntity lotTypeEntity, string abbdate, EncashLoadType encashLoadType)
        {
            this.TotalMoney = 0;
            this.TotalTicket = 0;
            this.EncashedTotalMoney = 0;
            this.EncashedTotalTicket = 0;
            this.TotalMoneyOfAssign = 0;
            this.TotalTicketOfAssign = 0;
            this.WaitEncashTickets.Clear();
            //JcL_LotTicketService jcLotTicketService = new JcL_LotTicketService();

            AllEncashTickets.Clear();
            //List<L_LotTicketEntity> encashTickets;
            //EncashTicketSummaryEntity encashTicketSummaryEntity;
            //if (encashLoadType == EncashLoadType.ByMacNumber)
            //{
            //    encashTickets = jcLotTicketService.GetMachineEncashTickets(lotTypeEntity.L_LotId, abbdate, LotMachine.MachineInfo.M_Number);
            //    encashTicketSummaryEntity = jcLotTicketService.GetMachineEncashTicketSummary(lotTypeEntity.L_LotId, abbdate,
            //                                                                          LotMachine.MachineInfo.M_Number);

            //    LotMachine.Log.Info(string.Concat("加载彩种：", lotTypeEntity.L_LotName, " 结算日期：", abbdate, " 机器号：", LotMachine.MachineInfo.M_Number, " 可兑奖票", AllEncashTickets.Count, "张"));
            //}
            //else
            //{
            //    encashTickets = jcLotTicketService.GetMachineEncashTickets(lotTypeEntity.L_LotId, abbdate, string.Empty);
            //    encashTicketSummaryEntity = jcLotTicketService.GetMachineEncashTicketSummary(lotTypeEntity.L_LotId, abbdate,
            //                                                                          string.Empty);
            //    LotMachine.Log.Info(string.Concat("加载彩种：", lotTypeEntity.L_LotName, " 结算日期：", abbdate, " 全部机器可兑奖票", AllEncashTickets.Count, "张"));
            //}
            //TotalMoneyOfAssign = encashTicketSummaryEntity.GetMoney;
            //TotalTicketOfAssign = encashTicketSummaryEntity.Count;

            //if (LoseEncashTicket == 1)
            //{
            //    foreach (L_LotTicketEntity entity in encashTickets)
            //    {
            //        if (entity.L_GetMoney == LoseEncashMoney)
            //        {
            //            AllEncashTickets.Add(entity);
            //        }
            //        else
            //        {
            //            LotMachine.Log.Info(string.Concat("流水号：", entity.L_TicketSn, " 票号：", entity.L_TicketCode, " 奖金：", entity.L_GetMoney,
            //                                              " 奖金不等于漏兑金额，忽略加载"));
            //        }
            //    }
            //}
            //else if (LoseEncashTicket > 1)
            //{
            //    foreach (L_LotTicketEntity entity in encashTickets)
            //    {
            //        if (entity.L_GetMoney < LoseEncashMoney)
            //        {
            //            AllEncashTickets.Add(entity);
            //        }
            //        else
            //        {
            //            LotMachine.Log.Info(string.Concat("流水号：", entity.L_TicketSn, " 票号：", entity.L_TicketCode, " 奖金：", entity.L_GetMoney,
            //                                              " 奖金不小于漏兑金额，忽略加载"));
            //        }
            //    }
            //}
            //else
            //{
            //    AllEncashTickets.AddRange(encashTickets);
            //}
            //foreach (L_LotTicketEntity entity in AllEncashTickets)
            //{
            //    TotalMoney += entity.L_GetMoney;
            //    TotalTicket += 1;
            //}
            //OnEncashTicketLoaded();

        }
    }
    [EnumDescription("兑奖数据加载方式")]
    public enum EncashLoadType
    {
        [EnumDescription("按分配的机器号")]
        ByMacNumber,
        [EnumDescription("全部")]
        All
    }
}
