using RFrameGenerate.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

namespace RFrameGenerate.BLL
{
    public class LotteryResultManage
    {
        private const string HtmlPattern = @"<table[^>]*class\s*=\s*(?:'|"")awardList(?:'|"")[^>]*>.*?</table>";
        private const string DataPattern = @"<td[^>]*class\s*=\s*(?:'|"")start(?:'|"")[^>]*>\s*(?<period>[^>]*?)\s*</td>\s*<td[^>]*class\s*=\s*(?:'|"")award-winNum(?:'|"")[^>]*>\s*(?<number>[^>]*?)\s*</td>";
        /// <summary>
        /// 采集开奖结果
        /// </summary>
        public static Result CollectLotteryResult(string url = null)
        {
            HttpWebResponse response = null;
            if (string.IsNullOrEmpty(url) == true)
                url = string.Format("http://caipiao.163.com/award/cqssc/{0}.html", DateTime.Now.ToString("yyyyMMdd"));
            try
            {
                int tryCount = 0;
                string html = string.Empty;
                while (tryCount++ < 3)
                {
                    response = RequestHepler.CreateGetHttpResponse(url);


                    if (response.Headers.AllKeys.Contains<string>("Content-Encoding") && (response.Headers.Get("Content-Encoding").ToLower().Trim() == "gzip"))
                    {
                        using (var reader = new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress, true), System.Text.Encoding.UTF8))
                        {
                            html = reader.ReadToEnd();
                        }
                    }
                    else
                    {
                        using (var reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
                        {
                            html = reader.ReadToEnd();
                        }
                    }


                    if (!string.IsNullOrEmpty(html) && Regex.IsMatch(html, HtmlPattern, RegexOptions.Singleline | RegexOptions.IgnoreCase)) break;
                }

                if (string.IsNullOrEmpty(html) || !Regex.IsMatch(html, DataPattern)) return new Result(false, "采集结果为空！");

                string strNumber = string.Empty;
                string strPeriod = string.Empty;
                int maxPeriod = 0;
                int tempPeriod = 0;
                foreach (Match match in Regex.Matches(html, DataPattern, RegexOptions.Singleline | RegexOptions.IgnoreCase))
                {
                    if (!int.TryParse(match.Groups["period"].Value.Trim(), out tempPeriod)) continue;

                    if (tempPeriod <= maxPeriod) continue;

                    maxPeriod = tempPeriod;
                    strNumber = match.Groups["number"].Value.Trim();
                    strPeriod = match.Groups["period"].Value.Trim();
                }

                int number = 0;

                var period = strPeriod;
                if (!int.TryParse(strNumber.Replace(" ", "").Replace("　", ""), out number)) return new Result(false, "返回结果不正确 : number");

                if (string.IsNullOrEmpty(period) || period.Length != 3) return new Result(false, "返回结果不正确 : period");
                if (number <= 0) return new Result(false, "返回结果不正确 : number");

                period = DateTime.Now.ToString("yyyyMMdd") + period;
                using (var query = Factory.CreateT_CR_LotteryResult())
                {
                    if (query.IsExist(m => m.AwardsPeriod == period)) return new Result(true);

                    T_CR_LotteryResult model = new T_CR_LotteryResult();

                    model.LotteryResultGuid = Guid.NewGuid();
                    model.AwardsPeriod = period;
                    model.AwardsNumber = number;
                    model.AwardsTime = DateTime.Now;
                    model.CollectUrl = url;

                    query.Add(model);
                }
            }
            catch (Exception ex)
            {
                RFramework.Log.Write("采集开奖结果Url : " + url);
                RFramework.Log.Write("采集开奖结果异常：" + ex.Message);
                return new Result(false, ex.Message);
            }
            finally
            {
                if (response != null) response.Close();
            }
            return new Result(true);
        }

        /// <summary>
        /// 获取最近开奖结果
        /// </summary>        
        public static T_CR_LotteryResult GetLastNumber()
        {
            using (var query = Factory.CreateT_CR_LotteryResult())
            {
                return query.GetFirstData(null, false, v => v.AwardsPeriod, DAL.Enums.OrderMethods.DESC);
            }
        }

        public static T_CR_LotteryResult GetEntity(Guid lotteryResultGuid)
        {
            using (var query = Factory.CreateT_CR_LotteryResult())
            {
                return query.GetFirstData(m => m.LotteryResultGuid == lotteryResultGuid);
            }
        }

    }
}
