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

namespace ChuPiao.AutoPrint.Machine.TjJingCaiV1.MacLotPlayMode
{
    /// <summary>
    /// 彩种玩法投注模式（键码发送、电子票解析）
    /// </summary>
    public class MacLotPlayModeQxFsService : TjJingCaiV1.MacLotPlayMode.MacLotPlayModeService
    {
        //public string RegexCode = @"第[①|②|③|④|⑤|⑥|⑦]{1}位:([^\d]+)([\d|.]){10}";//([\d|.]){10}
        public string RegexCode = @"第[①|②|③|④|⑤|⑥]{1}位:[^\d]+\d{1,2}(\s{1,4}\d{1,2}){0,9}";//([\d|.]){10}
        public string RegexMoney = @"\d{1,5}元";

        public MacLotPlayModeQxFsService()
        {
            base.SplitStr = "|";
        }
        #region 键码发送

        /// <summary>
        /// 获得投注需要发送的键码列表
        /// </summary>
        /// <param name="ticketEntity"></param>
        /// <param name="machineEntity"></param>
        /// <returns></returns>
        public override List<KeycodeInfo> GetSendKeycodeList(L_LotTicketEntity ticketEntity, M_MachineEntity machineEntity)
        {
            List<KeycodeInfo> keycodeList = new List<KeycodeInfo>();
            M_MachineModeConfigEntity machineModeConfig = machineEntity.MachineModeConfigs[ticketEntity.MacModeId];
            //初始化
            if(machineModeConfig.C_IsEveryInit)
            {
                if (!string.IsNullOrEmpty(machineModeConfig.C_MacModeKeys))
                {
                    foreach (string key in machineModeConfig.C_MacModeKeys.Split(','))
                    {
                        keycodeList.Add(new KeycodeInfo(key, machineModeConfig.C_MacModeKeysInterval));
                    }
                }
            }
            //投注号码  2|4|5|0,1|5,6|5|9,14
            List<string> codeList = SplitString(ticketEntity.L_Code, SplitStr);
            for (int n = 0; n < 6; n++)
            {
                string strTemp = codeList[n].Replace(",", "");
                for (int i = 0; i < strTemp.Length; i++)
                {
                    keycodeList.Add(new KeycodeInfo(strTemp.Substring(i, 1), machineModeConfig.C_SendKeyInterval));
                }
                //下个场次
                keycodeList.Add(new KeycodeInfo(machineModeConfig.C_NextKey, machineModeConfig.C_NextKeyInterval));
            }
            codeList = SplitString(codeList[6], ",");
            foreach (string onecode in codeList)
            {
                string strTemp = onecode;
                if (onecode.Length == 1)
                {
                    strTemp = "0" + strTemp;
                }
                for (int i = 0; i < strTemp.Length; i++)
                {
                    keycodeList.Add(new KeycodeInfo(strTemp.Substring(i, 1), machineModeConfig.C_SendKeyInterval));
                }
            }

            //foreach (string oneCode in codeList)
            //{
            //    string strTemp = oneCode;
            //    for (int i = 0; i < strTemp.Length; i++)
            //    {
            //        keycodeList.Add(new KeycodeInfo(strTemp.Substring(i, 1), machineModeConfig.C_SendKeyInterval));
            //    }
            //    //下个场次
            //    keycodeList.Add(new KeycodeInfo(machineModeConfig.C_NextKey, machineModeConfig.C_NextKeyInterval));
            //}
            ////删除最后一个NextKey
            //int delIndex = keycodeList.Count - 1;
            //keycodeList.RemoveAt(delIndex);

            //倍投);
            if(ticketEntity.L_Mutiple>1)
            {
                keycodeList.Add(new KeycodeInfo( machineModeConfig.C_MultipleKey, machineModeConfig.C_SendKeyInterval));
                string strTemp = ticketEntity.L_Mutiple.ToString();
                for (int i = 0; i < strTemp.Length; i++)
                {
                    keycodeList.Add(new KeycodeInfo( strTemp.Substring(i, 1), machineModeConfig.C_SendKeyInterval));
                }
                if(!string.IsNullOrEmpty(machineModeConfig.C_MultipleConfirmKey))
                {
                    keycodeList.Add(new KeycodeInfo( machineModeConfig.C_MultipleConfirmKey, machineModeConfig.C_MultipleConfirmKeyInterval));
                }
            }
            //打印确认
            keycodeList.Add(new KeycodeInfo( machineModeConfig.C_PrintConfirmKey, machineModeConfig.C_PrintConfirmKeyInterval));

            //是否输入密码
            //TODO 配置
            //if (ticketEntity.L_Money >= 500)
            //{
            //    string password = machineEntity.M_ZxPassword;
            //    for (int i = 0; i < password.Length; i++)
            //    {
            //        keycodeList.Add(new KeycodeInfo(password.Substring(i, 1), machineModeConfig.C_SendKeyInterval));
            //    }
            //    if (!string.IsNullOrEmpty(machineModeConfig.C_PasswordConfirmKey)) //确认输入密码
            //    {
            //        keycodeList.Add(new KeycodeInfo(machineModeConfig.C_PasswordConfirmKey, machineModeConfig.C_PasswordConfirmKeyInterval));
            //    }
            //}
            //是否输入密码
            keycodeList.AddRange(GetPasswordKeycodeList(ticketEntity, machineEntity, machineModeConfig));


            return keycodeList;
        }
        #endregion

        #region 电子票解析

        /// <summary>
        /// 解析电子票
        /// </summary>
        /// <param name="machineEntity"></param>
        /// <param name="decodePrintData"></param>
        /// <param name="ticketEntity"></param>
        public override void DecodeData(L_LotTicketEntity ticketEntity, M_MachineEntity machineEntity, DecodePrintData decodePrintData)
        {
            M_MachineModeConfigEntity machineModeConfig = machineEntity.MachineModeConfigs[ticketEntity.MacModeId];

            //抓取的返回
            decodePrintData.L_PrintTicketEntity.P_PrnText = TicketTextUtil.CompressAndEncrypt(decodePrintData.InputData.CaptureDataBytes);
            decodePrintData.L_PrintTicketEntity.P_SucTime = DateTime.Now;

            string input = decodePrintData.InputData.CaptureDataString;
            //input = input.Replace("大乐透12035期开奖01+04+30+32+35 08+12", "");
            string strTemp;
            //票号、密码、期号解析
            bool suc = DecodeHead(ticketEntity,decodePrintData);
            if(!suc)
            {
                decodePrintData.ErrorMessage = string.Format("头部解析错误：{0}", decodePrintData.ErrorMessage);
                decodePrintData.DecodeSuccess = false;
                return;
            }
            Regex regex;

            //金额
            //int position = input.IndexOf(decodePrintData.L_PrintTicketEntity.P_TicketCode) + 70;
            //Regex regex=new Regex(RegexMoney);
            //strTemp = input.Substring(position, 20);
            //Match match = regex.Match(strTemp);
            //if(!match.Success)
            //{
            //    decodePrintData.ErrorMessage += "没有找到金额";
            //    decodePrintData.DecodeSuccess = false;
            //    return;
            //}
            //string money = Regex.Replace(match.Value, @"\D", "");
            //decodePrintData.L_PrintTicketEntity.P_Money = decimal.Parse(money);
            //if (decimal.Parse(money) != ticketEntity.L_Money)
            //{
            //    decodePrintData.ErrorMessage += string.Format("金额不匹配，软件金额：{0} 电子票金额：{1}", ticketEntity.L_Money,
            //                                                  money);
            //    decodePrintData.DecodeSuccess = false;
            //    return;
            //}
            //投注号码
            //position += 40;
            //strTemp = input.Substring(position, 280);
            //strTemp = Regex.Replace(input.Substring(position), @"\n", "");
            strTemp = Regex.Replace(input, @"\n", "");
            regex=new Regex(RegexCode);
            MatchCollection matchCollection = regex.Matches(strTemp);
            decodePrintData.L_PrintTicketEntity.P_Code = ticketEntity.L_Code;
            if (machineModeConfig.C_IsCheckCode)
            {
                //进行号码检测
                string code = string.Empty;
                foreach (Match oneMatch in matchCollection)
                {
                    code += oneMatch.Value+SplitStr;
                }

                //因为最后一位是0到14，有可能换行，所以不能用正则式匹配第7位
                int startIndex = input.IndexOf("第⑦位");
                if (startIndex == -1)
                {
                    decodePrintData.ErrorMessage += "未解析到字符：第⑦位";
                    decodePrintData.DecodeSuccess = false;
                    return;
                }
                int endIndex = input.IndexOf("----------------", startIndex);
                if (endIndex == -1)
                {
                    endIndex = input.IndexOf("\n", startIndex);
                    endIndex = input.IndexOf("\n", endIndex+1);
                    
                }
                strTemp = input.Substring(startIndex, endIndex - startIndex);
                regex = new Regex(@"\s{1,4}\d{1,2}");
                matchCollection = regex.Matches(strTemp);
                foreach (Match oneMatch in matchCollection)
                {
                    code += oneMatch.Value;
                }


                string s1 = Regex.Replace(ticketEntity.L_Code, @"\D", "");
                string s2 = Regex.Replace(code, @"\D", "");
                if (s1 != s2)
                {
                    decodePrintData.ErrorMessage += string.Format("投注号码不匹配，软件号码：{0} 电子票号码：{1}", s1,
                                                          s2);
                    //把跟投注号码不匹配的电子票号设成"01,02,03,04,05"这种格式，以便入库

                    decodePrintData.L_PrintTicketEntity.P_Code = code;
                    decodePrintData.DecodeSuccess = false;
                    return;
                }
            }
            decodePrintData.L_PrintTicketEntity.P_SingleZhuShu = ticketEntity.L_SingleZhuShu;
            decodePrintData.DecodeSuccess = true;

        }
        #endregion
    }
}
