using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using ChuPiao.AutoPrint.Machine.Models;
using ChuPiao.Common.Core.Utils;
using ChuPiao.Common.Enums;
using ChuPiao.Common.Models;
using System.Text;
using System.IO;

namespace ChuPiao.AutoPrint.Machine.TjJingCaiV1.MacReport
{
    /// <summary>
    /// 机器报表
    /// </summary>
    public class MacReportService : IMacReportService
    {
        #region Implementation of IMacReportService

        /// <summary>
        /// 获取缴款报表的键码
        /// </summary>
        /// <param name="machineEntity"></param>
        /// <returns></returns>
        public List<KeycodeInfo> GetMachinePayMoneyReportKeycodeList(M_MachineEntity machineEntity)
        {
            List<KeycodeInfo> keycodeList = new List<KeycodeInfo>();
            if (!string.IsNullOrEmpty(machineEntity.MachineConfigEntity.C_UpdateMoneyKeys))
            {
                foreach (string key in machineEntity.MachineConfigEntity.C_UpdateMoneyKeys.Split(','))
                {
                    keycodeList.Add(new KeycodeInfo(key, machineEntity.MachineConfigEntity.C_SendCommandInterval));
                }
            }
            return keycodeList;
        }

        /// <summary>
        /// 解析缴款报表
        /// </summary>
        /// <param name="machineEntity"></param>
        /// <param name="decodeMachinePayMoneyReport"></param>
        public void DecodeMachinePayMoneyReport(M_MachineEntity machineEntity, DecodeMachinePayMoneyReport decodeMachinePayMoneyReport)
        {
            //TODO 报表打印测试
            //string filepath = @"E:\e-ticket\江西\缴款报表.prn";
            //decodeMachinePayMoneyReport.InputData.CaptureDataString = File.ReadAllText(filepath, Encoding.GetEncoding("gb2312"));
            //decodeMachinePayMoneyReport.InputData.CaptureDataBytes = File.ReadAllBytes(filepath);
            //System.IO.File.WriteAllBytes(@"c:\a.prn", ChuPiao.Common.Core.Utils.TicketTextUtil.DecryptAndDecompress(machinereport.R_PrnText));
            //电子票文本
            decodeMachinePayMoneyReport.MachinePayMoneyReportEntity.R_PrnText = TicketTextUtil.CompressAndEncrypt(decodeMachinePayMoneyReport.InputData.CaptureDataBytes);

            decodeMachinePayMoneyReport.DecodeSuccess = true;
            string input = decodeMachinePayMoneyReport.InputData.CaptureDataString;
            string strTemp;
            bool result;

            //            缴款报表

            //门店编号：13-013968
            //数据截止时间：2017-05-17 15:13:02
            //当前账户余额：4798.00元
            //账户信用额度：0.00元
            //临时信用额度：0.00元
            //当前可用额度：4798.00元
            //最新应缴款：0.00元


            //账户缴款明细：
            //   缴款金额         缴款时间
            //----------------------------------------
            //+5000.00元     2017-05-11 14:42:17
            //天津建行：78078831
            //----------------------------------------
            //报表查询时间:2017-05-17 15:13:53

            //销售点（中心机器号）
            Regex regex = new Regex(@"门店编号(:|：)\d{2}-\d{6}");
            Match match = regex.Match(input);
            if (!match.Success)
            {
                decodeMachinePayMoneyReport.ErrorMessage += "没有找到销售点";
                decodeMachinePayMoneyReport.DecodeSuccess = false;
                return;
            }
            strTemp = match.Value;
            strTemp = Regex.Replace(strTemp, @"门店编号(:|：)\d{2}-", "");
            strTemp = strTemp.Trim();
            decodeMachinePayMoneyReport.MachinePayMoneyReportEntity.R_ZxMacNumber = strTemp.Substring(1);

            //当前账户余额
            regex = new Regex(@"当前账户余额(:|：)\s{0,}\d{1,}\.\d{2}元");
            match = regex.Match(input);
            if (!match.Success)
            {
                decodeMachinePayMoneyReport.ErrorMessage += "没有找到当前账户余额";
                decodeMachinePayMoneyReport.DecodeSuccess = false;
                return;
            }
            strTemp = match.Value;
            strTemp = Regex.Replace(strTemp, @"当前账户余额(:|：)\s{0,}", "");
            strTemp = strTemp.Replace("元", "");
            strTemp = strTemp.Trim();
            decimal balance;
            result = decimal.TryParse(strTemp, out balance);
            if (result)
            {
                decodeMachinePayMoneyReport.MachinePayMoneyReportEntity.R_Balance = balance;
            }

            //本销售点信用额度
            regex = new Regex(@"账户信用额度(:|：)\s{0,}\d{1,}\.\d{2}元");
            match = regex.Match(input);
            if (!match.Success)
            {
                decodeMachinePayMoneyReport.ErrorMessage += "没有找到本销售点信用额度";
                decodeMachinePayMoneyReport.DecodeSuccess = false;
                return;
            }
            strTemp = match.Value;
            strTemp = Regex.Replace(strTemp, @"账户信用额度(:|：)\s{0,}", "");
            strTemp = strTemp.Replace("元", "");
            strTemp = strTemp.Trim();
            decimal creditline;
            result = decimal.TryParse(strTemp, out creditline);
            if (result)
            {
                decodeMachinePayMoneyReport.MachinePayMoneyReportEntity.R_CreditLine = creditline;
            }

            //临时信用额度
            regex = new Regex(@"临时信用额度(:|：)\s{0,}\d{1,}\.\d{2}元");
            match = regex.Match(input);
            //if (!match.Success)
            //{
            //    decodeMachinePayMoneyReport.ErrorMessage += "没有找到临时信用额度";
            //    decodeMachinePayMoneyReport.DecodeSuccess = false;
            //    return;
            //}
            if (match.Success)
            {
                strTemp = match.Value;
                strTemp = Regex.Replace(strTemp, @"临时信用额度(:|：)\s{0,}", "");
                strTemp = strTemp.Replace("元", "");
                strTemp = strTemp.Trim();
                decimal outstandingmoney;
                result = decimal.TryParse(strTemp, out outstandingmoney);
                if (result)
                {
                    decodeMachinePayMoneyReport.MachinePayMoneyReportEntity.R_OutstandingMoney = outstandingmoney;
                }
            }

            //当前售票额度
            regex = new Regex(@"当前可用额度(:|：)\s{0,}\d{1,}\.\d{2}元");
            match = regex.Match(input);
            if (!match.Success)
            {
                decodeMachinePayMoneyReport.ErrorMessage += "没有找到当前售票额度";
                decodeMachinePayMoneyReport.DecodeSuccess = false;
                return;
            }
            strTemp = match.Value;
            strTemp = Regex.Replace(strTemp, @"当前可用额度(:|：)\s{0,}", "");
            strTemp = strTemp.Replace("元", "");
            strTemp = strTemp.Trim();
            decimal cansalemoney;
            result = decimal.TryParse(strTemp, out cansalemoney);
            if (result)
            {
                decodeMachinePayMoneyReport.MachinePayMoneyReportEntity.R_CanSaleMoney = cansalemoney;
            }

            //最新应缴款
            regex = new Regex(@"最新应缴款(:|：)\s{0,}\d{1,}\.\d{2}元");
            match = regex.Match(input);
            if (!match.Success)
            {
                decodeMachinePayMoneyReport.ErrorMessage += "没有找到最新应缴款";
                decodeMachinePayMoneyReport.DecodeSuccess = false;
                return;
            }
            strTemp = match.Value;
            strTemp = Regex.Replace(strTemp, @"最新应缴款(:|：)\s{0,}", "");
            strTemp = strTemp.Replace("元", "");
            strTemp = strTemp.Trim();
            decimal payablemoney;
            result = decimal.TryParse(strTemp, out payablemoney);
            if (result)
            {
                decodeMachinePayMoneyReport.MachinePayMoneyReportEntity.R_PayableMoney = payablemoney;
            }

            //交款明细
            regex = new Regex(@"缴款明细[^-]+----------------------------------------(.*?)----------------------------------------", RegexOptions.Singleline);
            match = regex.Match(input);
            if (match.Success)
            {
                Regex regexPayDetail = new Regex(@"-{0,1}\d{1,}\.\d{2}元\s{1,}\d{4}-\d{2}-\d{2}\s{1,}\d{2}:\d{2}:\d{2}", RegexOptions.Multiline);
                MatchCollection matchCollectionPayDetail = regexPayDetail.Matches(match.Value);
                if (matchCollectionPayDetail.Count > 0)
                {
                    foreach (Match matchPayDetail in matchCollectionPayDetail)
                    {
                        int position = matchPayDetail.Value.IndexOf("元");
                        if (position > 0)
                        {
                            decimal paymoney;
                            DateTime paytime;
                            strTemp = matchPayDetail.Value.Substring(0, position);
                            strTemp = strTemp.Trim();
                            bool result1 = decimal.TryParse(strTemp, out paymoney);
                            strTemp = matchPayDetail.Value.Substring(position + 1);
                            strTemp = strTemp.Trim();
                            strTemp = Regex.Replace(strTemp, @"\s+", " ");
                            bool result2 = DateTime.TryParse(strTemp, out paytime);
                            if (result1 && result2)
                            {
                                decodeMachinePayMoneyReport.MachinePayMoneyReportEntity.R_DataList.Add(new PayMoneyDataItem(1, paymoney, paytime));
                            }
                        }
                    }
                }
            }

            //移动充值
            regex = new Regex(@"移动支付[^-]+----------------------------------------(.*?)----------------------------------------", RegexOptions.Singleline);
            match = regex.Match(input);
            if (match.Success)
            {
                Regex regexPayDetail = new Regex(@"(-{0,1}\d{1,}\.\d{2})元\s{1,}(\d{4}-\d{2}-\d{2})\s{1,}\+(\d{1,}\.\d{2})元\n([支微])", RegexOptions.Multiline);
                MatchCollection matchCollectionPayDetail = regexPayDetail.Matches(match.Value);

                string lasttype = null;
                string lastpaytime = null;
                decimal lastmoney = 0M;
                decimal lastfee = 0M;
                foreach (Match matchPayDetail in matchCollectionPayDetail)
                {
                    string type = matchPayDetail.Groups[4].Value;
                    string paytime = matchPayDetail.Groups[2].Value;
                    decimal money=decimal.Parse(matchPayDetail.Groups[1].Value);
                    decimal fee = decimal.Parse(matchPayDetail.Groups[3].Value);

                    if (lasttype == null)
                    {
                        lastmoney = money;
                        lastpaytime = paytime;
                        lastfee = fee;
                        lasttype = type;
                    }
                    else
                    {
                        if (type == lasttype && paytime == lastpaytime)   //同天同类型的记录，多条合并成一条
                        {
                            lastmoney += money;
                            lastfee += fee;
                        }
                        else  //不同日期或不同类型，上一条记录就可以添加
                        {
                            decodeMachinePayMoneyReport.MachinePayMoneyReportEntity.R_DataList.Add(new PayMoneyDataItem(lasttype == "支" ? 4 : 5, lastmoney, DateTime.Parse(lastpaytime), lastfee));

                            lastmoney = money;
                            lastpaytime = paytime;
                            lastfee = fee;
                            lasttype = type;
                        }
                    }    
                }
                if (lasttype != null)
                {
                    decodeMachinePayMoneyReport.MachinePayMoneyReportEntity.R_DataList.Add(new PayMoneyDataItem(lasttype == "支" ? 4 : 5, lastmoney, DateTime.Parse(lastpaytime), lastfee));
                }

            }

            //佣金明细
            regex = new Regex(@"佣金转[^-]+----------------------------------------(.*?)----------------------------------------", RegexOptions.Singleline);
            match = regex.Match(input);
            if (match.Success)
            {
                Regex regexPayDetail = new Regex(@"-{0,1}\d{1,}\.\d{2}元\s{1,}\d{4}-\d{2}-\d{2}\s{1,}\d{2}:\d{2}:\d{2}", RegexOptions.Multiline);
                MatchCollection matchCollectionPayDetail = regexPayDetail.Matches(match.Value);
                if (matchCollectionPayDetail.Count > 0)
                {
                    foreach (Match matchPayDetail in matchCollectionPayDetail)
                    {
                        int position = matchPayDetail.Value.IndexOf("元");
                        if (position > 0)
                        {
                            decimal paymoney;
                            DateTime paytime;
                            strTemp = matchPayDetail.Value.Substring(0, position);
                            strTemp = strTemp.Trim();
                            bool result1 = decimal.TryParse(strTemp, out paymoney);
                            strTemp = matchPayDetail.Value.Substring(position + 1);
                            strTemp = strTemp.Trim();
                            strTemp = Regex.Replace(strTemp, @"\s+", " ");
                            bool result2 = DateTime.TryParse(strTemp, out paytime);
                            if (result1 && result2)
                            {
                                //paymoney += 0.0001m;   //佣金只有2位小数，小数点后第4位是1的，就是佣金
                                decodeMachinePayMoneyReport.MachinePayMoneyReportEntity.R_DataList.Add(new PayMoneyDataItem(2, paymoney, paytime));
                            }
                        }
                    }
                }
            }

            //转入即开
            regex = new Regex(@"转入即开[^-]+----------------------------------------(.*?)----------------------------------------", RegexOptions.Singleline);
            match = regex.Match(input);
            if (match.Success)
            {
                Regex regexPayDetail = new Regex(@"-{0,1}\d{1,}\.\d{2}元\s{1,}\d{4}-\d{2}-\d{2}\s{1,}\d{2}:\d{2}:\d{2}", RegexOptions.Multiline);
                MatchCollection matchCollectionPayDetail = regexPayDetail.Matches(match.Value);
                if (matchCollectionPayDetail.Count > 0)
                {
                    foreach (Match matchPayDetail in matchCollectionPayDetail)
                    {
                        int position = matchPayDetail.Value.IndexOf("元");
                        if (position > 0)
                        {
                            decimal paymoney;
                            DateTime paytime;
                            strTemp = matchPayDetail.Value.Substring(0, position);
                            strTemp = strTemp.Trim();
                            bool result1 = decimal.TryParse(strTemp, out paymoney);
                            strTemp = matchPayDetail.Value.Substring(position + 1);
                            strTemp = strTemp.Trim();
                            strTemp = Regex.Replace(strTemp, @"\s+", " ");
                            bool result2 = DateTime.TryParse(strTemp, out paytime);
                            if (result1 && result2)
                            {
                                //paymoney += 0.0001m;   //佣金只有2位小数，小数点后第4位是1的，就是佣金
                                decodeMachinePayMoneyReport.MachinePayMoneyReportEntity.R_DataList.Add(new PayMoneyDataItem(3, paymoney, paytime));
                            }
                        }
                    }
                }
            }

            //报表查询时间

            strTemp = input.Substring(input.LastIndexOf("----------------------------------------"));

            regex = new Regex(@"\d{4}-\d{2}-\d{2}\s{1,}\d{2}:\d{2}:\d{2}");
            match = regex.Match(strTemp);
            if (!match.Success)
            {
                decodeMachinePayMoneyReport.ErrorMessage += "没有找到报表查询时间";
                decodeMachinePayMoneyReport.DecodeSuccess = false;
                return;
            }
            strTemp = match.Value;
            strTemp = Regex.Replace(strTemp, @"\s+", " ");
            DateTime querytime;
            result = DateTime.TryParse(strTemp, out querytime);
            if (result)
            {
                decodeMachinePayMoneyReport.MachinePayMoneyReportEntity.R_QueryTime = querytime;
            }

        }

        /// <summary>
        /// 获取机器报表的键码
        /// </summary>
        /// <param name="machineEntity"></param>
        /// <param name="startDate"></param>
        /// <param name="enddate"></param>
        /// <returns></returns>
        public List<KeycodeInfo> GetMachineReportKeycodeList(M_MachineEntity machineEntity, DateTime startDate, DateTime enddate)
        {
            List<KeycodeInfo> keycodeList = new List<KeycodeInfo>();

            if (!machineEntity.M_HasJc)
            {
                machineEntity.MachineConfigEntity.C_PrintTimeReportKeys = machineEntity.MachineConfigEntity.C_PrintTimeReportKeys.Replace(",1,0,", ",0,9,");
            }

            if (!string.IsNullOrEmpty(machineEntity.MachineConfigEntity.C_PrintTimeReportKeys))
            {
                string strTemp = "";
                string startDateStr = startDate.ToString("yyMMdd");
                string endDateStr = enddate.ToString("yyMMdd");
                string todayDataStr = DateTime.Now.ToString("yyMMdd");

                foreach (string key in machineEntity.MachineConfigEntity.C_PrintTimeReportKeys.Split(','))
                {
                    if (key.ToLower() == "startdate")
                    {
                        if (startDateStr != todayDataStr)
                        {
                            //清除日期
                            for (int i = 0; i < startDateStr.Length; i++)
                            {
                                keycodeList.Add(new KeycodeInfo("break", machineEntity.MachineConfigEntity.C_SendCommandInterval));
                            }

                            for (int i = 0; i < startDateStr.Length; i++)
                            {
                                keycodeList.Add(new KeycodeInfo(startDateStr.Substring(i, 1), machineEntity.MachineConfigEntity.C_SendCommandInterval));
                            }
                        }
                    }
                    else if (key.ToLower() == "enddate")
                    {
                        if (endDateStr != todayDataStr)
                        {
                            //清除日期
                            for (int i = 0; i < endDateStr.Length; i++)
                            {
                                keycodeList.Add(new KeycodeInfo("break", machineEntity.MachineConfigEntity.C_SendCommandInterval));
                            }

                            for (int i = 0; i < endDateStr.Length; i++)
                            {
                                keycodeList.Add(new KeycodeInfo(endDateStr.Substring(i, 1), machineEntity.MachineConfigEntity.C_SendCommandInterval));
                            }
                        }
                    }
                    else
                    {
                        keycodeList.Add(new KeycodeInfo(key, machineEntity.MachineConfigEntity.C_SendCommandInterval));
                    }
                }
            }
            return keycodeList;
        }

        /// <summary>
        /// 获取机器报表的键码
        /// </summary>
        /// <param name="machineEntity"></param>
        /// <param name="startDate"></param>
        /// <param name="enddate"></param>
        /// <returns></returns>
        public List<KeycodeInfo> GetJcMachineReportKeycodeList(M_MachineEntity machineEntity, DateTime startDate, DateTime enddate)
        {
            List<KeycodeInfo> keycodeList = new List<KeycodeInfo>();
            if (!string.IsNullOrEmpty(machineEntity.MachineConfigEntity.C_PrintJcTimeReportKeys))
            {
                string strTemp = "";
                string startDateStr = startDate.ToString("yyMMdd");
                string endDateStr = enddate.ToString("yyMMdd");
                string todayDataStr = DateTime.Now.ToString("yyMMdd");

                foreach (string key in machineEntity.MachineConfigEntity.C_PrintJcTimeReportKeys.Split(','))
                {
                    if (key.ToLower() == "startdate")
                    {
                        if (startDateStr != todayDataStr)
                        {
                            //清除日期
                            for (int i = 0; i < startDateStr.Length; i++)
                            {
                                keycodeList.Add(new KeycodeInfo("break", machineEntity.MachineConfigEntity.C_SendCommandInterval));
                            }

                            for (int i = 0; i < startDateStr.Length; i++)
                            {
                                keycodeList.Add(new KeycodeInfo(startDateStr.Substring(i, 1), machineEntity.MachineConfigEntity.C_SendCommandInterval));
                            }
                        }
                    }
                    else if (key.ToLower() == "enddate")
                    {
                        if (endDateStr != todayDataStr)
                        {
                            //清除日期
                            for (int i = 0; i < endDateStr.Length; i++)
                            {
                                keycodeList.Add(new KeycodeInfo("break", machineEntity.MachineConfigEntity.C_SendCommandInterval));
                            }

                            for (int i = 0; i < endDateStr.Length; i++)
                            {
                                keycodeList.Add(new KeycodeInfo(endDateStr.Substring(i, 1), machineEntity.MachineConfigEntity.C_SendCommandInterval));
                            }
                        }
                    }
                    else
                    {
                        keycodeList.Add(new KeycodeInfo(key, machineEntity.MachineConfigEntity.C_SendCommandInterval));
                    }
                }
            }
            return keycodeList;
        }


        /// <summary>
        /// 解析竞彩时段报表
        /// </summary>
        /// <param name="machineEntity"></param>
        /// <param name="decodeMachineReport"></param>
        public void DecodeMachineReportReport(M_MachineEntity machineEntity, DecodeMachineReport decodeMachineReport)
        {
            //TODO 报表打印测试
            //string filepath = @"D:\data\logs\C3-02-01\2018-01-23\last\26.prn";
            //string temp = Encoding.GetEncoding("GB18030").GetString(ChuPiao.Common.Core.Utils.TicketTextUtil.DecryptAndDecompress(File.ReadAllText(filepath)));
            //decodeMachineReport.InputData.CaptureDataString = Regex.Replace(temp, @"U\?\0[\s\S]{1}", "");

            //            竞彩时段报表

            //开始日期: 2017-06-01 
            //截止日期: 2017-06-06 
            //终端编号: 13-013968-101

            //销售员：001 
            //                         金额      票数
            //------------------------------------------
            //销售(已减取消)：         266.00元   22张
            //取消：　　　　             0.00元    0张
            //兑奖：　　　　            78.73元    --
            //实退：　　　　             0.00元    --
            //兑退合计：　　　　        78.73元   14张
            //------------------------------------------
            //销售员：合计 
            //                         金额      票数
            //------------------------------------------
            //销售(已减取消)：         266.00元   22张
            //取消：　　　　             0.00元    0张
            //兑奖：　　　　            78.73元    --
            //实退：　　　　             0.00元    --
            //兑退合计：　　　　        78.73元   14张
            //------------------------------------------
            //已结销量数据
            //开始日期: 2017-06-01 
            //截止日期: 2017-06-05 
            //终端编号: 13-013968-101
            //已结销量                266.00元  --
            //中奖                   72.70元  --
            //应退                    0.00元  --
            //------------------------------------------
            //报表查询时间:2017-06-06 15:42:01

            //电子票文本
            decodeMachineReport.MachineReportEntity.R_PrnText = TicketTextUtil.CompressAndEncrypt(decodeMachineReport.InputData.CaptureDataBytes);

            decodeMachineReport.DecodeSuccess = true;
            string input = decodeMachineReport.InputData.CaptureDataString;
            string strTemp;

            Regex regex = new Regex(@"开始日期(:|：)\s{0,}\d{4}-\d{2}-\d{2}");
            Match match = regex.Match(input);
            if (!match.Success)
            {
                decodeMachineReport.ErrorMessage += "没有找到开始日期";
                decodeMachineReport.DecodeSuccess = false;
                return;
            }
            strTemp = Regex.Replace(match.Value, @"开始日期(:|：)\s{0,}", "");
            decodeMachineReport.MachineReportEntity.R_StartTime = DateTime.Parse(strTemp);


            regex = new Regex(@"截止日期(:|：)\s{0,}\d{4}-\d{2}-\d{2}");
            match = regex.Match(input);
            if (!match.Success)
            {
                decodeMachineReport.ErrorMessage += "没有找到截止日期";
                decodeMachineReport.DecodeSuccess = false;
                return;
            }
            strTemp = Regex.Replace(match.Value, @"截止日期(:|：)\s{0,}", "");
            decodeMachineReport.MachineReportEntity.R_EndTime = DateTime.Parse(strTemp);

            //销售点（中心机器号）
            regex = new Regex(@"终端编号(:|：)\s{0,}\d{2}-\d{6}-\d{3}");
            match = regex.Match(input);
            if (match.Success)    //竞彩时段报表
            {
                strTemp = Regex.Replace(match.Value, @"终端编号(:|：)\s{0,}\d{2}-", "");
                decodeMachineReport.MachineReportEntity.R_ZxMacNumber = strTemp.Substring(1, 5);
            }
            else   //时段报表二
            {
                //销售点（中心机器号）
                regex = new Regex(@"门店编号(:|：)\d{2}-\d{6}");
                match = regex.Match(input);
                if (!match.Success)
                {
                    decodeMachineReport.ErrorMessage += "没有找到销售点";
                    decodeMachineReport.DecodeSuccess = false;
                    return;
                }
                strTemp = Regex.Replace(match.Value, @"门店编号(:|：)\d{2}-", "");
                decodeMachineReport.MachineReportEntity.R_ZxMacNumber = strTemp.Substring(1);
            }

            //解析合计后面的文本
            string inputTemp = input;
            //int index = input.IndexOf("销售员：合计");
            int index = input.IndexOf("销售员：合");
            if (index != -1)
            {
                inputTemp = input.Substring(index);
            }

            //regex = new Regex(@"其中竞彩\(已减取消\)(:|：)\s{0,}\d{1,}\.\d{2}元\s{0,}\d{1,}");
            //match = regex.Match(inputTemp);
            //if (match.Success)    //时段报表
            //{
            //    strTemp = Regex.Replace(match.Value, @"其中竞彩\(已减取消\)(:|：)\s{0,}", "");
            //    strTemp = Regex.Replace(strTemp, @"元\s{0,}", ",");
            //    string[] arr = strTemp.Split(',');
            //    if (arr.Length != 2)
            //    {
            //        decodeMachineReport.ErrorMessage += "解析时段报表竞彩销售数据错误";
            //        decodeMachineReport.DecodeSuccess = false;
            //        return;
            //    }
            //    decodeMachineReport.MachineReportEntity.R_SaleMoney = decimal.Parse(arr[0]);
            //    decodeMachineReport.MachineReportEntity.R_SaleTicket = int.Parse(arr[1]);
            //}
            //else     //竞彩时段报表
            //{
            regex = new Regex(@"销售\(已减取消\)(:|：)\s{0,}\d{1,}\.\d{2}元\s{0,}\d{1,}");
            match = regex.Match(inputTemp);
            if (!match.Success)
            {
                decodeMachineReport.ErrorMessage += "没有找到销售数据";
                decodeMachineReport.DecodeSuccess = false;
                return;
            }
            strTemp = Regex.Replace(match.Value, @"销售\(已减取消\)(:|：)\s{0,}", "");
            strTemp = Regex.Replace(strTemp, @"元\s{0,}", ",");
            string[] arr = strTemp.Split(',');
            if (arr.Length != 2)
            {
                decodeMachineReport.ErrorMessage += "解析销售数据错误";
                decodeMachineReport.DecodeSuccess = false;
                return;
            }
            decodeMachineReport.MachineReportEntity.R_SaleMoney = decimal.Parse(arr[0]);
            decodeMachineReport.MachineReportEntity.R_SaleTicket = int.Parse(arr[1]);
            //}


            regex = new Regex(@"兑奖(:|：)\s{0,}\d{1,}\.\d{2}元\s{0,}\d{1,}");
            match = regex.Match(inputTemp);
            if (match.Success)   //时段报表带张数，如：     兑奖：                   0.00元     0张
            {
                strTemp = Regex.Replace(regex.Match(inputTemp).Value, @"兑奖(:|：)\s{0,}", "");
                strTemp = Regex.Replace(strTemp, @"元\s{0,}", ",");
                if (strTemp == "")
                {
                    decodeMachineReport.ErrorMessage += "没有获取到兑奖数据";
                    decodeMachineReport.DecodeSuccess = false;
                    return;
                }
                string[] arr1 = strTemp.Split(',');
                if (arr1.Length != 2)
                {
                    decodeMachineReport.DecodeSuccess = false;
                    return;
                }
                else
                {
                    try
                    {

                        decodeMachineReport.MachineReportEntity.R_EncashMoney = decimal.Parse(arr1[0].Trim());
                        decodeMachineReport.MachineReportEntity.R_EncashTicket = int.Parse(arr1[1].Trim());
                    }
                    catch
                    {
                        decodeMachineReport.DecodeSuccess = false;
                        return;
                    }
                }
            }
            else  //竞彩时段报表不带张数，如：     兑奖：                   0.00元     --
            {
                //regex = new Regex(@"兑奖(:|：)\s{0,}\d{1,}\.\d{2}元");
                regex = new Regex(@"兑奖\D{1,}\d{1,}\.\d{2}元");
                match = regex.Match(inputTemp);
                if (!match.Success)
                {
                    decodeMachineReport.ErrorMessage += "没有获取到兑奖数据";
                    decodeMachineReport.DecodeSuccess = false;
                    return;
                }
                strTemp = Regex.Replace(regex.Match(inputTemp).Value, @"兑奖\D{1,}", "");
                strTemp = Regex.Replace(strTemp, "元", "");

                decodeMachineReport.MachineReportEntity.R_EncashMoney = decimal.Parse(strTemp);
            }

            //如果是竞彩时段报表，解析退票
            regex = new Regex(@"实退(:|：)\s{0,}\d{1,}\.\d{2}元");
            match = regex.Match(inputTemp);
            if (match.Success)
            {
                strTemp = Regex.Replace(regex.Match(inputTemp).Value, @"实退(:|：)\s{0,}", "");
                strTemp = Regex.Replace(strTemp, "元", "");

                decodeMachineReport.MachineReportEntity.R_ReturnMoney = decimal.Parse(strTemp);
            }

            regex = new Regex(@"报表查询时间(:|：)\s{0,}\d{4}-\d{2}-\d{2}\s{0,}\d{2}:\d{2}:\d{2}");
            strTemp = Regex.Replace(regex.Match(input).Value, @"报表查询时间(:|：)\s{0,}", "");
            strTemp = Regex.Replace(strTemp, @"\s+", " ");

            DateTime querytime;
            if (DateTime.TryParse(strTemp, out querytime))
            {
                decodeMachineReport.MachineReportEntity.R_QueryTime = querytime;
            }

        }

        /// <summary>
        /// 获取机器玩法报表的键码
        /// </summary>
        /// <param name="machineEntity"></param>
        /// <param name="lotTypeEntity"></param>
        /// <param name="startDate"></param>
        /// <param name="enddate"></param>
        /// <returns></returns>
        public List<KeycodeInfo> GetMachinePlayReportKeycodeList(M_MachineEntity machineEntity, M_PlayTypeEntity playTypeEntity, DateTime startDate, DateTime enddate)
        {
            List<KeycodeInfo> keycodeList = new List<KeycodeInfo>();
            if (!string.IsNullOrEmpty(machineEntity.MachineConfigEntity.C_PrintPlayTimeReportKeys))
            {
                string strTemp = "";
                string startDateStr = startDate.ToString("yyMMdd");
                string endDateStr = enddate.ToString("yyMMdd");
                string todayDataStr = DateTime.Now.ToString("yyMMdd");

                foreach (string key in machineEntity.MachineConfigEntity.C_PrintPlayTimeReportKeys.Split(','))
                {
                    if (key.ToLower() == "lottype")
                    {
                        switch ((Lottype)playTypeEntity.P_LotId)
                        {
                            case Lottype.Ps:
                                strTemp = "01";
                                break;
                            case Lottype.Sf:
                                strTemp = "02";
                                break;
                            case Lottype.Jq:
                                strTemp = "03";
                                break;
                            case Lottype.Bq:
                                strTemp = "04";
                                break;
                            case Lottype.Lt:
                                strTemp = "05";
                                break;
                            case Lottype.Qx:
                                strTemp = "06";
                                break;
                            case Lottype.Pw:
                                strTemp = "07";
                                break;

                        }
                        if (playTypeEntity.P_PlayId > 0)
                        {
                            //竟彩
                            switch ((Playtype)playTypeEntity.P_PlayId)
                            {
                                case Playtype.JzSPF:
                                    strTemp = "05";
                                    break;
                                case Playtype.JzRQSPF:
                                    strTemp = "03";
                                    break;
                                case Playtype.JzBF:
                                    strTemp = "01";
                                    break;
                                case Playtype.JzJQS:
                                    strTemp = "02";
                                    break;
                                case Playtype.JzBQC:
                                    strTemp = "04";
                                    break;
                                case Playtype.JzHHGG:
                                    strTemp = "12";
                                    break;
                                case Playtype.JlRFSF:
                                    strTemp = "09";
                                    break;
                                case Playtype.JlSF:
                                    strTemp = "06";
                                    break;
                                case Playtype.JlSFC:
                                    strTemp = "07";
                                    break;
                                case Playtype.JlDXF:
                                    strTemp = "08";
                                    break;
                                case Playtype.JlHHGG:
                                    strTemp = "13";
                                    break;
                                case Playtype.JmGj:
                                case Playtype.JmGyj:
                                    strTemp = "10";
                                    break;
                            }
                        }
                        for (int i = 0; i < strTemp.Length; i++)
                        {
                            keycodeList.Add(new KeycodeInfo(strTemp.Substring(i, 1), machineEntity.MachineConfigEntity.C_SendCommandInterval));
                        }
                    }
                    else if (key.ToLower() == "startdate")
                    {
                        if (startDateStr != todayDataStr)
                        {
                            //清除日期
                            for (int i = 0; i < startDateStr.Length; i++)
                            {
                                keycodeList.Add(new KeycodeInfo("break", machineEntity.MachineConfigEntity.C_SendCommandInterval));
                            }
                            for (int i = 0; i < startDateStr.Length; i++)
                            {
                                keycodeList.Add(new KeycodeInfo(startDateStr.Substring(i, 1), machineEntity.MachineConfigEntity.C_SendCommandInterval));
                            }
                        }
                    }
                    else if (key.ToLower() == "enddate")
                    {
                        if (endDateStr != todayDataStr)
                        {
                            //清除日期
                            for (int i = 0; i < endDateStr.Length; i++)
                            {
                                keycodeList.Add(new KeycodeInfo("break", machineEntity.MachineConfigEntity.C_SendCommandInterval));
                            }
                            for (int i = 0; i < endDateStr.Length; i++)
                            {
                                keycodeList.Add(new KeycodeInfo(endDateStr.Substring(i, 1), machineEntity.MachineConfigEntity.C_SendCommandInterval));
                            }
                        }
                    }
                    else
                    {
                        keycodeList.Add(new KeycodeInfo(key, machineEntity.MachineConfigEntity.C_SendCommandInterval));
                    }
                }
            }
            return keycodeList;
        }

        /// <summary>
        /// 解析机器玩法报表
        /// </summary>
        /// <param name="machineEntity"></param>
        /// <param name="decodeMachineReport"></param>
        public void DecodeMachinePlayReportReport(M_MachineEntity machineEntity, DecodeMachinePlayReport decodeMachineReport)
        {
            //TODO 报表打印测试
            //string filepath = @"E:\e-ticket\江西\玩法报表2011-07-12\tc_2_20026_2011-07-12_0.prn";
            //decodeMachineReport.InputData.CaptureDataString = File.ReadAllText(filepath, Encoding.GetEncoding("gb2312"));
            //decodeMachineReport.InputData.CaptureDataBytes = File.ReadAllBytes(filepath);
            //System.IO.File.WriteAllBytes(@"c:\a.prn", ChuPiao.Common.Core.Utils.TicketTextUtil.DecryptAndDecompress(machinereport.R_PrnText));

            //电子票文本
            decodeMachineReport.MachinePlayReportEntity.R_PrnText = TicketTextUtil.CompressAndEncrypt(decodeMachineReport.InputData.CaptureDataBytes);

            decodeMachineReport.DecodeSuccess = true;
            string input = decodeMachineReport.InputData.CaptureDataString;
            string strTemp;

            //            其他游戏时段报表

            //开始日期: 2017-06-01
            //截止日期: 2017-06-05
            //终端编号: 13-013968-101

            //玩法名称: 竞彩足球-让球胜平负
            //                        金额          票数
            //-----------------------------------------
            //销售(已减取消应退):      2.00元       1张
            //兑奖:　　　　　　        0.00元       0张
            //取消:　　　　　　        0.00元       0张
            //应退:　　　　　　        0.00元       0张
            //-----------------------------------------

            //报表查询时间:2017-06-06 15:18:53

            Regex regex = new Regex(@"开始日期(:|：)\s{0,}\d{4}-\d{2}-\d{2}");
            Match match = regex.Match(input);
            if (!match.Success)
            {
                decodeMachineReport.ErrorMessage += "没有找到开始日期";
                decodeMachineReport.DecodeSuccess = false;
                return;
            }
            strTemp = Regex.Replace(match.Value, @"开始日期(:|：)\s{0,}", "");
            decodeMachineReport.MachinePlayReportEntity.R_StartTime = DateTime.Parse(strTemp);


            regex = new Regex(@"截止日期(:|：)\s{0,}\d{4}-\d{2}-\d{2}");
            match = regex.Match(input);
            if (!match.Success)
            {
                decodeMachineReport.ErrorMessage += "没有找到截止日期";
                decodeMachineReport.DecodeSuccess = false;
                return;
            }
            strTemp = Regex.Replace(match.Value, @"截止日期(:|：)\s{0,}", "");
            decodeMachineReport.MachinePlayReportEntity.R_EndTime = DateTime.Parse(strTemp);

            //销售点（中心机器号）
            regex = new Regex(@"门店编号(:|：)\d{2}-\d{6}");
            match = regex.Match(input);
            if (!match.Success)
            {
                decodeMachineReport.ErrorMessage += "没有找到销售点";
                decodeMachineReport.DecodeSuccess = false;
                return;
            }
            strTemp = Regex.Replace(match.Value, @"门店编号(:|：)\d{2}-", "");
            decodeMachineReport.MachinePlayReportEntity.R_ZxMacNumber = strTemp.Substring(1);

            decodeMachineReport.MachinePlayReportEntity.R_SaleMoney = 0;
            decodeMachineReport.MachinePlayReportEntity.R_SaleTicket = 0;
            int index = input.IndexOf(@"合计");
            if (index > 0)
            {
                string inputTemp = input.Substring(index);

                regex = new Regex(@"销售\(已减取消\)(:|：)\s{0,}\d{1,}\.\d{2}元\s{0,}\d{1,}");
                match = regex.Match(inputTemp);
                if (!match.Success)
                {
                    decodeMachineReport.ErrorMessage += "没有找到销售数据";
                    decodeMachineReport.DecodeSuccess = false;
                    return;
                }
                strTemp = Regex.Replace(match.Value, @"销售\(已减取消\)(:|：)\s{0,}", "");
                strTemp = Regex.Replace(strTemp, @"元\s{0,}", ",");
                if (strTemp == "")
                {
                    decodeMachineReport.ErrorMessage += "没有获取到销售数据";
                    decodeMachineReport.DecodeSuccess = false;
                    return;
                }
                string[] TmpArr = strTemp.Split(',');
                if (TmpArr.Length != 2)
                {
                    decodeMachineReport.DecodeSuccess = false;
                    return;
                }
                else
                {
                    try
                    {

                        decodeMachineReport.MachinePlayReportEntity.R_SaleMoney = decimal.Parse(TmpArr[0].Trim());
                        decodeMachineReport.MachinePlayReportEntity.R_SaleTicket = int.Parse(TmpArr[1].Trim());
                    }
                    catch
                    {
                        decodeMachineReport.DecodeSuccess = false;
                        return;
                    }
                }

                regex = new Regex(@"兑奖(:|：)\s{0,}\d{1,}\.\d{2}元\s{0,}\d{1,}");
                match = regex.Match(inputTemp);
                if (!match.Success)
                {
                    decodeMachineReport.ErrorMessage += "没有找到兑奖数据";
                    decodeMachineReport.DecodeSuccess = false;
                    return;
                }
                strTemp = Regex.Replace(match.Value, @"兑奖(:|：)\s{0,}", "");
                strTemp = Regex.Replace(strTemp, @"元\s{0,}", ",");
                if (strTemp == "")
                {
                    decodeMachineReport.ErrorMessage += "没有获取到兑奖数据";
                    decodeMachineReport.DecodeSuccess = false;
                    return;
                }
                TmpArr = strTemp.Split(',');
                if (TmpArr.Length != 2)
                {
                    decodeMachineReport.DecodeSuccess = false;
                    return;
                }
                else
                {
                    try
                    {

                        decodeMachineReport.MachinePlayReportEntity.R_EncashMoney = decimal.Parse(TmpArr[0].Trim());
                        decodeMachineReport.MachinePlayReportEntity.R_EncashTicket = int.Parse(TmpArr[1].Trim());
                    }
                    catch
                    {
                        decodeMachineReport.DecodeSuccess = false;
                        return;
                    }
                }

            }
            else
            {

                MatchCollection matchCollection;
                regex = new Regex(@"销售\(已减取消\)(:|：)\s{0,}\d{1,}\.\d{2}元\s{0,}\d{1,}");
                matchCollection = regex.Matches(input);
                foreach (Match amatch in matchCollection)
                {
                    strTemp = Regex.Replace(amatch.Value, @"销售\(已减取消\)(:|：)\s{0,}", "");
                    strTemp = Regex.Replace(strTemp, @"元\s{0,}", ",");
                    if (strTemp == "")
                    {
                        decodeMachineReport.ErrorMessage += "没有获取到销售数据";
                        decodeMachineReport.DecodeSuccess = false;
                        return;
                    }
                    string[] TmpArr = strTemp.Split(',');
                    if (TmpArr.Length != 2)
                    {
                        decodeMachineReport.DecodeSuccess = false;
                        return;
                    }
                    else
                    {
                        try
                        {

                            decodeMachineReport.MachinePlayReportEntity.R_SaleMoney += decimal.Parse(TmpArr[0].Trim());
                            decodeMachineReport.MachinePlayReportEntity.R_SaleTicket += int.Parse(TmpArr[1].Trim());
                        }
                        catch
                        {
                            decodeMachineReport.DecodeSuccess = false;
                            return;
                        }
                    }
                }

                regex = new Regex(@"兑奖(:|：)\s{0,}\d{1,}\.\d{2}元\s{0,}\d{1,}");
                matchCollection = regex.Matches(input);
                decodeMachineReport.MachinePlayReportEntity.R_EncashMoney = 0;
                decodeMachineReport.MachinePlayReportEntity.R_EncashTicket = 0;
                foreach (Match amatch in matchCollection)
                {
                    strTemp = Regex.Replace(amatch.Value, @"兑奖(:|：)\s{0,}", "");
                    strTemp = Regex.Replace(strTemp, @"元\s{0,}", ",");
                    if (strTemp == "")
                    {
                        decodeMachineReport.ErrorMessage += "没有获取到兑奖数据";
                        decodeMachineReport.DecodeSuccess = false;
                        return;
                    }
                    string[] TmpArr = strTemp.Split(',');
                    if (TmpArr.Length != 2)
                    {
                        decodeMachineReport.DecodeSuccess = false;
                        return;
                    }
                    else
                    {
                        try
                        {

                            decodeMachineReport.MachinePlayReportEntity.R_EncashMoney += decimal.Parse(TmpArr[0].Trim());
                            decodeMachineReport.MachinePlayReportEntity.R_EncashTicket += int.Parse(TmpArr[1].Trim());
                        }
                        catch
                        {
                            decodeMachineReport.DecodeSuccess = false;
                            return;
                        }
                    }
                }
            }

            //decodeMachineReport.MachinePlayReportEntity.R_ZxMacNumber = machineEntity.M_ZxNumber;//票面上没有中心机器号，手工添加


            regex = new Regex(@"报表查询时间(:|：)\s{0,}\d{4}-\d{2}-\d{2}\s{0,}\d{2}:\d{2}:\d{2}");
            strTemp = Regex.Replace(regex.Match(input).Value, @"报表查询时间(:|：)\s{0,}", "");
            strTemp = Regex.Replace(strTemp, @"\s+", " ");

            DateTime querytime;
            if (DateTime.TryParse(strTemp, out querytime))
            {
                decodeMachineReport.MachinePlayReportEntity.R_QueryTime = querytime;
            }
        }

        #endregion
    }
}
