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 MacLotPlayModeLtZjDtService : TjJingCaiV1.MacLotPlayMode.MacLotPlayModeService
    {
        public string RegexCode = @"前区胆([\s\S]*)后区拖(([^\d]+)(\n{0,1}\s{1,10}\d{2}){1,}){1,}";//(\s{1,4}\d{2}){1,}
        public string RegexMoney = @"\d{1,5}元";
        public string ZjSendKey = "+";

        #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));
                    }
                }
            }
            //变成追加
            if (ZjSendKey != "")
            {
                keycodeList.Add(new KeycodeInfo(ZjSendKey, machineModeConfig.C_MacModeKeysInterval));
            }
            //投注号码
            List<string> codes = SplitString(ticketEntity.L_Code, "|");
            List<string> beforedancodes = new List<string>();
            List<string> beforetuocodes = new List<string>();
            if (codes[0].IndexOf("-") > -1)
            {
                List<string> beforecodes = SplitString(codes[0], "-");
                beforedancodes = SplitString(beforecodes[0], ",");
                beforetuocodes = SplitString(beforecodes[1], ",");
            }
            else
            {
                beforetuocodes = SplitString(codes[0], ",");
            }
            List<string> afterdancodes = new List<string>();
            List<string> aftertuocodes = new List<string>();
            if(codes[1].IndexOf("-")>-1)
            {
                List<string> aftercodes = SplitString(codes[1], "-");
                afterdancodes = SplitString(aftercodes[0], ",");
                aftertuocodes = SplitString(aftercodes[1], ",");
            }
            else
            {
                aftertuocodes = SplitString(codes[1], ",");
            }
            
            //前区胆码
            foreach (string oneCode in beforedancodes)
            {
                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));
            //前区拖码
            foreach (string oneCode in beforetuocodes)
            {
                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));
            //后区胆码
            foreach (string oneCode in afterdancodes)
            {
                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));
            //后区拖码
            foreach (string oneCode in aftertuocodes)
            {
                string strTemp = oneCode;
                for (int i = 0; i < strTemp.Length; i++)
                {
                    keycodeList.Add(new KeycodeInfo(strTemp.Substring(i, 1), machineModeConfig.C_SendKeyInterval));
                }
            }

            //倍投
            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));


            if (ticketEntity.L_Money >= 15)
            {
                //有赠票
                keycodeList.Add(new KeycodeInfo("enter", 1450));
                keycodeList.Add(new KeycodeInfo("enter", 1450));
                keycodeList.Add(new KeycodeInfo("enter", 100));
            }

            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;
            }
            int position;
            Regex regex;
            Match match;

            //金额
            //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, 400);
            //strTemp = Regex.Replace(strTemp, @"\n", "");
            position = input.IndexOf("合计");
            if (position > 0)
            {
                //strTemp = Regex.Replace(input.Substring(position, 400), @"\n", "");
                strTemp = Regex.Replace(input.Substring(position), @"\n", "");
            }
            else
            {
                strTemp = input;
            }

            regex=new Regex(RegexCode);
            //MatchCollection matchCollection = regex.Matches(strTemp);
            match = regex.Match(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;
                //}
                code = match.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"这种格式，以便入库
                    int temp = s2.Length / 2 - 1;
                    while (temp > 0)
                    {
                        s2 = s2.Insert(temp * 2, ",");
                        temp -= 1;
                    }
                    decodePrintData.L_PrintTicketEntity.P_Code = s2;
                    decodePrintData.DecodeSuccess = false;
                    return;
                }
            }
            decodePrintData.L_PrintTicketEntity.P_SingleZhuShu = ticketEntity.L_SingleZhuShu;
            decodePrintData.DecodeSuccess = true;

            //追加玩法解析大乐透加奖的乐善码
            //DecodeLotoCode(ticketEntity, decodePrintData);
            DecodeLotoAddType(ticketEntity, decodePrintData);
        }
        #endregion
    }
}
