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 MacLotPlayModeSfR9DsService : TjJingCaiV1.MacLotPlayMode.MacLotPlayModeService
    {
        public string RegexCode = @"([3|1|0|\-|*]\s{1,4}){13}[3|1|0|\-|*]";//([3|1|0|\-]\s{1,4}){13}[3|1|0|\-]
        public string RegexMoney = @"\d{1,5}元";

        public MacLotPlayModeSfR9DsService()
        {
            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));
                    }
                }
            }
            //投注号码
            foreach (string oneCode in SplitString(ticketEntity.L_Code, CodeSplitStr_Cg))
            {
                string strTemp = oneCode.Replace(SplitStr, "");
                strTemp = strTemp.TrimEnd('*');
                for (int i = 0; i < strTemp.Length; i++)
                {
                    keycodeList.Add(new KeycodeInfo(strTemp.Substring(i, 1), machineModeConfig.C_SendKeyInterval));
                    //keycodeList.Add(new KeycodeInfo(strTemp.Substring(i, 1), machineModeConfig.C_SendKeyInterval*2));
                }
            }
            //倍投
            if(ticketEntity.L_Mutiple>1)
            {
                keycodeList.Add(new KeycodeInfo( machineModeConfig.C_MultipleKey, machineModeConfig.C_MultipleKeyInterval));
                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 = input.IndexOf("任选9场胜负");
            //strTemp = Regex.Replace(input.Substring(position), @"\n", "");

            strTemp = Regex.Replace(input, @"([@|*]\s{1,4}){13}[@|*]", "");     //去掉全是*的行

            regex=new Regex(RegexCode);
            MatchCollection matchCollection = regex.Matches(strTemp);
            decodePrintData.L_PrintTicketEntity.P_SingleZhuShu = matchCollection.Count;
            List<string> codes = SplitString(ticketEntity.L_Code, CodeSplitStr_Cg);
            if (codes.Count!= matchCollection.Count)
            {
                decodePrintData.ErrorMessage += string.Format("注数不匹配，软件注数：{0} 电子票注数：{1}", codes.Count,
                                                              matchCollection.Count);
                decodePrintData.DecodeSuccess = false;
                return;
            }
            decodePrintData.L_PrintTicketEntity.P_Code = ticketEntity.L_Code;
            if (machineModeConfig.C_IsCheckCode)
            {
                //进行号码检测
                for (int i = 0; i < matchCollection.Count; i++)
                {
                    string s1 = Regex.Replace(codes[i],@"\|","");//Regex.Replace(codes[i], @"\D", "");
                    string s2 = Regex.Replace(matchCollection[i].Value,"-","*");//Regex.Replace(matchCollection[i].Value, @"\D", "");
                    s2 = Regex.Replace(s2, " ", "");
                    if (s1 != s2)
                    {
                        decodePrintData.ErrorMessage += string.Format("投注号码不匹配，软件号码：{0} 电子票号码：{1}", s1,
                                                              s2);
                        //把跟投注号码不匹配的电子票号设成"1|2|3|4|5|6|7"这种格式，以便入库
                        s2 = base.InsertChar(s2, "|");
                        decodePrintData.L_PrintTicketEntity.P_Code = s2;
                        decodePrintData.DecodeSuccess = false;
                        return;
                    }
                }
            }
            decodePrintData.DecodeSuccess = true;
        }
        #endregion
    }
}
