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

namespace ChuPiao.AutoPrint.Machine.TjJingCaiV1.MacLotPlayMode
{
    /// <summary>
    /// 竞彩篮球混合过关
    /// </summary>
    public class MacLotPlayModeJlHhggService : MacLotPlayModeService
    {
        public MacLotPlayModeJlHhggService()
        {
            PlayFullName = "竞彩篮球混合过关";
        }
        #region Overrides of MacLotPlayModeService

        /// <summary>
        /// 机器投注模式配置信息
        /// </summary>
        /// <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];

            //初始化，每次都需要进入玩法的投注内容输入界面
            keycodeList.AddRange(GetInitKeycodeList(machineModeConfig));

            //投注号码
            List<JcCodeEntity> codeList = DealPrintCode(ticketEntity.L_Code);
            foreach (JcCodeEntity jcCodeEntity in codeList)
            {
                //进入场次选择界面
                //keycodeList.Add(new KeycodeInfo(WeekInitKey, machineModeConfig.C_SendKeyInterval));
                //选择场次
                for (int i = 0; i < jcCodeEntity.ChangCi.Length; i++)
                {
                    keycodeList.Add(new KeycodeInfo(jcCodeEntity.ChangCi.Substring(i, 1), machineModeConfig.C_SendKeyInterval));
                }
                //选择场次的玩法
                switch (jcCodeEntity.PlayId)
                {
                    case 95101:
                        //keycodeList.Add(new KeycodeInfo("6", machineModeConfig.C_SendKeyInterval));
                        keycodeList.Add(new KeycodeInfo("1", machineModeConfig.C_SendKeyInterval));
                        break;
                    case 95102:
                        //keycodeList.Add(new KeycodeInfo("6", machineModeConfig.C_SendKeyInterval));
                        keycodeList.Add(new KeycodeInfo("2", machineModeConfig.C_SendKeyInterval));
                        break;
                    case 95103:
                        //keycodeList.Add(new KeycodeInfo("6", machineModeConfig.C_SendKeyInterval));
                        keycodeList.Add(new KeycodeInfo("3", machineModeConfig.C_SendKeyInterval));
                        break;
                    case 95104:
                        //keycodeList.Add(new KeycodeInfo("6", machineModeConfig.C_SendKeyInterval));
                        keycodeList.Add(new KeycodeInfo("4", machineModeConfig.C_SendKeyInterval));
                        break;
                }

                //选择投注号码
                foreach (string s in jcCodeEntity.OneCodeList)
                {
                    keycodeList.Add(new KeycodeInfo(s, machineModeConfig.C_SendKeyInterval));
                }
                //投注号码确认
                keycodeList.Add(new KeycodeInfo(ResultEnterKey, machineModeConfig.C_SendKeyInterval));
            }

            //倍投
            if (ticketEntity.L_Mutiple > 1)
            {
                keycodeList.AddRange(GetMultipleKeycodeList(ticketEntity.L_Mutiple, machineModeConfig));
            }

            //过关方式
            keycodeList.AddRange(GetGuoGuanKeycodeList(ticketEntity.L_CodeType, machineModeConfig));

            //打印确认
            keycodeList.Add(new KeycodeInfo(machineModeConfig.C_PrintConfirmKey, machineModeConfig.C_PrintConfirmKeyInterval));

            //是否输入密码
            keycodeList.AddRange(GetPasswordKeycodeList(ticketEntity, machineEntity, machineModeConfig));

            return keycodeList;
        }
        /// <summary>
        /// 拆分投注号码
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        protected List<JcCodeEntity> DealPrintCode(string code)
        {
            List<JcCodeEntity> codeList = new List<JcCodeEntity>();
            string[] changCiCodeArr = code.Split(CodeSplitStr.ToCharArray()); //表示有多少场
            foreach (string changCiCode in changCiCodeArr)
            {
                JcCodeEntity jcCodeEntity = new JcCodeEntity();

                string[] arr = changCiCode.Split(MatchCodeSplitStr.ToCharArray());

                jcCodeEntity.ChangCi = arr[0];
                string[] arrPlayAndCode = arr[1].Split('[');
                jcCodeEntity.PlayId = int.Parse(arrPlayAndCode[0]);
                string s = arrPlayAndCode[1].Replace("]", "");
                string[] oneMatchCodeArr;
                switch (jcCodeEntity.PlayId)
                {
                    case 95101:
                        oneMatchCodeArr = s.Split(SplitStr.ToCharArray());
                        jcCodeEntity.OneCodeList.AddRange(oneMatchCodeArr);
                        break;
                    case 95102:
                        oneMatchCodeArr = s.Split(SplitStr.ToCharArray());
                        jcCodeEntity.OneCodeList.AddRange(oneMatchCodeArr);
                        break;
                    case 95103:
                        oneMatchCodeArr = s.Split(SplitStr.ToCharArray());
                        for (int i = 0; i < oneMatchCodeArr.Length; i++)
                        {
                            for (int j = 0; j < oneMatchCodeArr[i].Length; j++)
                            {
                                jcCodeEntity.OneCodeList.Add(oneMatchCodeArr[i].Substring(j, 1));
                            }
                        }
                        break;
                    case 95104:
                        oneMatchCodeArr = s.Split(SplitStr.ToCharArray());
                        jcCodeEntity.OneCodeList.AddRange(oneMatchCodeArr);
                        break;
                }
                
                codeList.Add(jcCodeEntity);
            }
            return codeList;

        }

        /// <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 = DecodeHeadJc(ticketEntity, machineEntity, decodePrintData);
            if (!suc)
            {
                decodePrintData.ErrorMessage = string.Format("头部解析错误：{0}", decodePrintData.ErrorMessage);
                decodePrintData.DecodeSuccess = false;
                return;
            }

            Regex regex;
            Match match;

            #region 投注号码及赔率
            List<string> dCodeList = new List<string>();
            List<string> dRateList = new List<string>();
            List<string> codeReferenceList = new List<string>(); //参考赔率（水位）  1301→[单场让分, 过关让分]  1301→[主+8.5,主+9.5]]/1302→[主+2.5,主+3.5];
            //金额
            int startposition = input.IndexOf(decodePrintData.L_PrintTicketEntity.P_TicketCode) + 60;
            int endposition = input.IndexOf("本票最高可能固定奖金", startposition);
            strTemp = input.Substring(startposition, endposition - startposition);//包含投注内容的字符串

            //2020.1.7 梧州篮球解析字符串有变 兼容的做法，把有变的替换成之前的
            strTemp = strTemp.Replace("主队让", "固定奖让分:主-");
            strTemp = strTemp.Replace("主队受让", "固定奖让分:主+");
            strTemp = strTemp.Replace("固定奖预设总分:", "预设总分:");

            string[] tmpArr = strTemp.Split('\n');//投注内容临时数组

            regex = new Regex(@"周(一|二|三|四|五|六|日)\d{3}\s{1,}(让分胜负\s{1,}固定奖让分:主[\+-]\d{1,}\.\d{1,}|胜负|胜分差|大小分\s{1,}预设总分:\d{1,}\.\d{1,})");
            //regex = new Regex(@"周(一|二|三|四|五|六|日)\d{3}\s{1,}(让分胜负\s{1,}固定奖让分:主[\+-]\d{1,}\.\d{1,}|胜负|胜分差|大小分\s{1,}固定奖预设总分:\d{1,}\.\d{1,})");
            for (int i = 0; i < tmpArr.Length; i++)
            {
                strTemp = tmpArr[i].Trim();
                match = regex.Match(strTemp);
                if (match.Success)
                {
                    strTemp = match.Value;
                    strTemp=Regex.Replace(strTemp, @"\s{1,}", " ");
                    string[] arrChangCi = strTemp.Split(' ');
                    if(arrChangCi.Length<2)
                    {
                        decodePrintData.ErrorMessage += string.Concat("解析赔率场次失败：", match.Value);
                        decodePrintData.DecodeSuccess = false;
                        return;
                    }
                    string strChangCi = DealChangChi(arrChangCi[0]);//场次字符串 如：第1关  周四002
                    int playIdOfRate = 0;
                    string rangScore = "";
                    switch (arrChangCi[1])
                    {
                        case "让分胜负":
                            playIdOfRate = 95101;
                            rangScore = string.Concat(" ,", arrChangCi[2].Replace("固定奖让分:", ""));
                            break;
                        case "胜负":
                            playIdOfRate = 95102;
                            break;
                        case "胜分差":
                            playIdOfRate = 95103;
                            break;
                        case "大小分":
                            playIdOfRate = 95104;
                            rangScore = string.Concat(" ,", arrChangCi[2].Replace("预设总分:", ""));
                            break;
                    }

                    //i++;//场次的下一行为让分数据 如：浮动奖让分:主-8.5 固定奖让分:主-8.5
                    //strTemp = new Regex(@"浮动奖让分:主[\+-]\d{1,}\.\d{1,}\s{1,}固定奖让分:主[\+-]\d{1,}\.\d{1,}").Match(tmpArr[i]).Value;
                    //strTemp = Regex.Replace(strTemp, @"\s{1,}", ",");
                    //string[] TmpArr_LF = strTemp.Split(',');
                    //if (TmpArr_LF.Length != 2)
                    //{
                    //    decodePrintData.ErrorMessage += string.Concat("解析让分有错误，获取到的字符：", strTemp);
                    //    decodePrintData.DecodeSuccess = false;
                    //    return;
                    //}

                    //codeReferenceList.Add(string.Format("{0}{1}{2}[{3},{4}]", strChangCi, MatchCodeSplitStr, playIdOfRate, TmpArr_LF[0].Trim().Replace("浮动奖让分:", ""), TmpArr_LF[1].Trim().Replace("固定奖让分:", "")));
                    if (playIdOfRate==95101||playIdOfRate==95104)
                    {
                        codeReferenceList.Add(string.Format("{0}{1}{2}[{3}]", strChangCi, MatchCodeSplitStr, playIdOfRate, rangScore));
                    }


                    i++;//场次的下一行为球队名称 如：主队:莫斯科火车头 Vs 客队:毕尔巴鄂竞技    
                    i++;//球队名称的下一行为投注内容与赔率 如：胜@2.540元
                    string tmpCodeStr = "";
                    //while (!new Regex(@"M\0!\0a\0").IsMatch(tmpArr[i]) && !new Regex(@"选项固定奖金额").IsMatch(tmpArr[i]))
                    //while (!new Regex(@"第\d{1,}关").IsMatch(tmpArr[i]) && !new Regex(@"选项固定奖金额").IsMatch(tmpArr[i]))   //2017-05-27 关改成场了
                    while (!new Regex(@"第\d{1,}(关|场)").IsMatch(tmpArr[i]) && !new Regex(@"选项固定奖金额").IsMatch(tmpArr[i]))
                    {
                        //投注内容可能有多行
                        if (tmpArr[i].IndexOf("@") > 0 || new Regex(@"\d{0,}.\d{1,}元").IsMatch(tmpArr[i]))     //有单独行   3.650元
                        {
                            tmpCodeStr += tmpArr[i].Trim();
                        }
                        i++;

                        if (i >= tmpArr.Length)
                        {
                            break;
                        }
                    }
                    i--;
                    //if (ticketEntity.L_RateType == (int)JcRateType.Fixed)
                    //{
                        dRateList.Add(string.Format("{0}{1}{2}[{3}]", strChangCi, MatchCodeSplitStr, playIdOfRate, DealRateCode(playIdOfRate,tmpCodeStr.Trim())));
                    //}
                    //else
                    //{
                    //    dCodeList.Add(string.Format("{0}{1}[{2}]", strChangCi, MatchCodeSplitStr, DealResultCode(tmpCodeStr.Trim())));
                    //}
                }
            }
            decodePrintData.L_PrintTicketEntity.L_CodeReference = string.Join(CodeSplitStr, codeReferenceList.ToArray());//让球
            //解析组合过关的赔率
            decodePrintData.L_PrintTicketEntity.L_CodeRate = string.Join(CodeSplitStr, dRateList.ToArray());

            //投注内容
            decodePrintData.L_PrintTicketEntity.P_Code = SplitRateDetailToCode(decodePrintData.L_PrintTicketEntity.L_CodeRate);
            #endregion

            decodePrintData.DecodeSuccess = true;
        }

        /// <summary>
        /// 处理赔率明细
        /// </summary>
        /// <param name="Istr"></param>
        /// <returns></returns>
        private string DealRateCode(int playIdOfRate, string Istr)
        {
            string result = "";
            switch (playIdOfRate)
            {
                case 95101:
                    result = DealRateCodeRfsf(Istr);
                    break;
                case 95102:
                    result = DealRateCodeSf(Istr);
                    break;
                case 95103:
                    result = DealRateCodeSfc(Istr);
                    break;
                case 95104:
                    result = DealRateCodeDxf(Istr);
                    break;
            }
            return result;
        }
        
        /// <summary>
        /// 处理赔率明细
        /// </summary>
        /// <param name="Istr"></param>
        /// <returns></returns>
        private string DealRateCodeRfsf(string Istr)
        {
            Istr = Regex.Replace(Istr, @"[^胜负元@.+\d]{1}", "");

            string tmpstr = "";
            string OneStr = "";
            for (int i = 0; i < Istr.Length; i++)
            {
                OneStr = Istr.Substring(i, 1);
                switch (OneStr)
                {
                    case "+":
                        tmpstr += SplitStr;
                        break;
                    case "@":
                        tmpstr += "#";
                        break;
                    case "胜":
                        tmpstr += "1";
                        break;
                    case "负":
                        tmpstr += "2";
                        break;
                    case "元":
                        break;
                    default:
                        tmpstr += OneStr;
                        break;
                }
            }
            //电子票上的赔率明细字符串 如：2#4.700,1#1.080 排序输出为 1#1.080,2#4.700  使其与用户投注号码的排序相同
            tmpstr = SortRateText(CODE_SORT_DIECTIONRY_RFSF, tmpstr);
            return tmpstr;
        }
        /// <summary>
        /// 处理赔率明细
        /// </summary>
        /// <param name="Istr"></param>
        /// <returns></returns>
        private string DealRateCodeSf(string Istr)
        {
            Istr = Regex.Replace(Istr, @"[^胜负元@.+\d]{1}", "");

            string tmpstr = "";
            string OneStr = "";
            for (int i = 0; i < Istr.Length; i++)
            {
                OneStr = Istr.Substring(i, 1);
                switch (OneStr)
                {
                    case "+":
                        tmpstr += SplitStr;
                        break;
                    case "@":
                        tmpstr += "#";
                        break;
                    case "胜":
                        tmpstr += "1";
                        break;
                    case "负":
                        tmpstr += "2";
                        break;
                    case "元":
                        break;
                    default:
                        tmpstr += OneStr;
                        break;
                }
            }

            //电子票上的赔率明细字符串 如：2#4.700,1#1.080 排序输出为 1#1.080,2#4.700  使其与用户投注号码的排序相同
            tmpstr = SortRateText(CODE_SORT_DIECTIONRY_SF, tmpstr);

            return tmpstr;
        }

        /// <summary>
        /// 处理赔率明细
        /// </summary>
        /// <param name="Istr"></param>
        /// <returns></returns>
        private string DealRateCodeSfc(string Istr)
        {
            Istr = Regex.Replace(Istr, @"[^()主客\-元@.+\d]{1}", "");

            Istr = Istr.Replace("26+", "26");
            Istr = Istr.Replace("元", "");
            string[] TmpArr = Istr.Split('+');
            string OneStr = "";
            string TmpStr = "";
            List<string> TmpList = new List<string>();
            for (int i = 0; i < TmpArr.Length; i++)
            {
                OneStr = TmpArr[i];
                string[] tmpOneArr = OneStr.Split('@');
                #region)
                switch (tmpOneArr[0])
                {
                    case "(主1-5)":
                        TmpStr = "01";
                        break;
                    case "(主6-10)":
                        TmpStr = "02";
                        break;
                    case "(主11-15)":
                        TmpStr = "03";
                        break;
                    case "(主16-20)":
                        TmpStr = "04";
                        break;
                    case "(主21-25)":
                        TmpStr = "05";
                        break;
                    case "(主26)":
                        TmpStr = "06";
                        break;
                    case "(客1-5)":
                        TmpStr = "11";
                        break;
                    case "(客6-10)":
                        TmpStr = "12";
                        break;
                    case "(客11-15)":
                        TmpStr = "13";
                        break;
                    case "(客16-20)":
                        TmpStr = "14";
                        break;
                    case "(客21-25)":
                        TmpStr = "15";
                        break;
                    case "(客26)":
                        TmpStr = "16";
                        break;
                    default:
                        break;
                }
                #endregion
                TmpList.Add(TmpStr + "#" + tmpOneArr[1]);
            }
            string tmpstr = string.Join(SplitStr, TmpList.ToArray());

            //电子票上的赔率明细字符串 如：2#4.700,1#1.080 排序输出为 1#1.080,2#4.700  使其与用户投注号码的排序相同
            tmpstr = SortRateText(CODE_SORT_DIECTIONRY_SFC, tmpstr);
            return tmpstr;
        }

        /// <summary>
        /// 处理赔率明细
        /// </summary>
        /// <param name="Istr"></param>
        /// <returns></returns>
        private string DealRateCodeDxf(string Istr)
        {
            Istr = Regex.Replace(Istr, @"[^大小元@.+\d]{1}", "");

            string tmpstr = "";
            string OneStr = "";
            for (int i = 0; i < Istr.Length; i++)
            {
                OneStr = Istr.Substring(i, 1);
                switch (OneStr)
                {
                    case "+":
                        tmpstr += SplitStr;
                        break;
                    case "@":
                        tmpstr += "#";
                        break;
                    case "大":
                        tmpstr += "1";
                        break;
                    case "小":
                        tmpstr += "2";
                        break;
                    case "元":
                        break;
                    default:
                        tmpstr += OneStr;
                        break;
                }
            }
            //电子票上的赔率明细字符串 如：2#4.700,1#1.080 排序输出为 1#1.080,2#4.700  使其与用户投注号码的排序相同
            tmpstr = SortRateText(CODE_SORT_DIECTIONRY_DXF, tmpstr);
            return tmpstr;
        }

        //号码排序字典 1 表示胜  2 表示负
        private const string CODE_SORT_DIECTIONRY_RFSF = "1,2";
        //号码排序字典 1 表示胜  2 表示负
        private const string CODE_SORT_DIECTIONRY_SF = "1,2";
        //号码排序字典 1 表示胜  2 表示负
        private const string CODE_SORT_DIECTIONRY_SFC = "01,02,03,04,05,06,11,12,13,14,15,16";
        //号码排序字典 1 表示大  2 表示小
        private const string CODE_SORT_DIECTIONRY_DXF = "1,2";
        #endregion
    }
}
