using log4net;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VIZ.TVP.WMCUP.Module
{
    public static class JsonModel
    {

        /// <summary>
        /// 添加日志
        /// </summary>
        private static readonly ILog Log = LogManager.GetLogger(typeof(JsonModel));

        //读取url
        private static AppSetup_InitLiteDB appSetup_InitLiteDB = AppSetup_InitLiteDB.CreateInstance;


        //新的URL
        public static string strUrl = AppSetup_InitLiteDB.HttpUrlConfigEntity.Url;

        /// <summary>
        /// 读取艾果的数据平台的配置项
        /// </summary>
        public static string appID = AppSetup_InitLiteDB.HttpUrlConfigEntity.AppId;
        //sd.Settings["AppID"].Value.ToString();
        public static string appKey = AppSetup_InitLiteDB.HttpUrlConfigEntity.AppKey;

        //public  string type = AppSetup_InitLiteDB.HttpUrlConfigEntity.SelectFootballType;

        //public  string seasonId = AppSetup_InitLiteDB.HttpUrlConfigEntity.SeasonId;

        /// <summary>
        /// true 是主数据来源，false 是备份数据库来源
        /// </summary>
        public static bool dataFromSource = true;


        /// <summary>
        /// 获取URl地址
        /// </summary>
        public static void GethttpUrl()
        {
            if (dataFromSource)
            {
                strUrl = AppSetup_InitLiteDB.HttpUrlConfigEntity.Url;
                appID = AppSetup_InitLiteDB.HttpUrlConfigEntity.AppId;
                appKey = AppSetup_InitLiteDB.HttpUrlConfigEntity.AppKey;

            }
            else
            {
                JsonModel.strUrl = AppSetup_InitLiteDB.HttpUrlConfigEntity.BUrl;
                JsonModel.appKey = AppSetup_InitLiteDB.HttpUrlConfigEntity.BAppKey;
                JsonModel.appID = AppSetup_InitLiteDB.HttpUrlConfigEntity.BAppId;
            }

        }



        /// <summary>
        /// 艾果平台的明日赛程数据服务器接口
        /// </summary>
        /// <returns></returns>
        public async static Task<Dayschedules> PostTomorrowMatch_Path(string date)
        {
           
            //Dictionary<string, string> dict = new Dictionary<string, string>();
            //dict.Add("leagueid", "401");
            //dict.Add("date", "2022-12-17");
            //dict.Add("customer", "migu");
            //dict.Add("key", "migu");
            //dict.Add("random", "4");
            //dict.Add("encrypted", "6587d013da014c99032f7d17b096ad73");
            //string newKey = Utils.GetKey(appID,appKey);
            //var str = JsonHelper.Post(strUrl, dict, newKey);

            Dayschedules dayschedules = new Dayschedules();
            try

            {

                GethttpUrl();

                await Task.Run(() =>
                {
                    string TomorrowMatchPath = strUrl + "women/getDaySchedule";
                    //"matchSeason";
                    //"women/getDaySchedule";
                    //+ leagueid + "&date=" + date + "&customer=" + customer + "&key=" + key + "&encrypted="
                    //+ Utils.GetMD5(key + encrypted + random) + "&random=" + random;
                    //                    //MessageBox.Show(TomorrowMatchPath);
                    //                    Console.WriteLine("明日赛程数据接口新新:=======>:" + TomorrowMatchPath);

                    //                    string result = JsonHelper.GetResult(TomorrowMatchPath);

                    //                    Log.Info("明日赛程数据接口新:=======>:" + result);
                    //                    JsonSerializerSettings settings = new JsonSerializerSettings();
                    //                    settings.NullValueHandling = NullValueHandling.Ignore;
                    //                    dayschedules = JsonConvert.DeserializeObject<Dayschedules>(result, settings);

                    // Dayschedules aguodayschedules = JsonConvert.DeserializeObject<Dayschedules>(str,settings);

                    Dictionary<string, string> dict = new Dictionary<string, string>();
                    // dict.Add("leagueid", "401");
                    dict.Add("date", date);

                    //dict.Add("competitionId", "德甲");

                    string newKey = Utils.GetKey(appID, appKey);
                    var str = JsonHelper.Post(TomorrowMatchPath, dict, newKey);

                    if (dataFromSource)
                    {
                        Log.Info($"女足世界杯明日赛程数据接口新:主数据来源:{TomorrowMatchPath}=======>:" + str);
                    }
                    else
                    {
                        Log.Info($"女足世界杯明日赛程数据接口新:备份数据来源:{TomorrowMatchPath}=======>:" + str);
                    }
                    JsonSerializerSettings settings = new JsonSerializerSettings();
                    settings.NullValueHandling = NullValueHandling.Ignore;
                    dayschedules = JsonConvert.DeserializeObject<Dayschedules>(str, settings);

                    if (dayschedules == null)
                    {
                        Log.Error("明日赛程数据接口新:=======>dayschedules数据错误:为null:");
                    }
                    else
                    {
                        if (dayschedules.dayschedule != null)
                        {
                            dayschedules.dayschedule = dayschedules.dayschedule.OrderBy(a => a.time).ToList();
                        }
                        else
                        {
                            Log.Error("明日赛程数据接口新:=======>dayschedules.dayschedule数据错误:为null:");
                        }
                    }

                });

                return dayschedules;

            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
                return null;
            }

        }


        

        /// <summary>
        ///球队积分数据服务器地址
        /// </summary>
        /// <returns></returns>
        public async static Task<TeamRanks> PostTeamScoreData_Path(string group)
        {
            try
            {
                GethttpUrl();

                TeamRanks teamRanks = new TeamRanks();

                await Task.Run(() =>
                {
                    string TeamScoreDataPath = strUrl + "women/teamScoreStat";


                    Dictionary<string, string> dict = new Dictionary<string, string>();

                    dict.Add("groupName", group);
                   // dict.Add("seasonId", seasonId);//"110000005454"

                    string newKey = Utils.GetKey(appID, appKey);

                    string result = JsonHelper.Post(TeamScoreDataPath, dict, newKey);

                    if (dataFromSource)
                    {
                        Log.Info($"球队积分排行数据:主数据来源:{TeamScoreDataPath}==>:" + result);
                    }
                    else
                    {
                        Log.Info($"球队积分排行数据:备份数据来源:{TeamScoreDataPath}==>:" + result);
                    }

                    JsonSerializerSettings settings = new JsonSerializerSettings();
                    settings.NullValueHandling = NullValueHandling.Ignore;

                    teamRanks = JsonConvert.DeserializeObject<TeamRanks>(result, settings);
                    if (teamRanks != null)
                    {
                        var sortRanks = teamRanks.teamstats.OrderBy(a => Convert.ToInt32(a.rank)).ToList();
                        teamRanks.teamstats = sortRanks;
                    }
                    Console.WriteLine("球队积分排行数据============>:" + TeamScoreDataPath);

                });

                return teamRanks;
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
                return null;
            }
        }



        /// <summary>
        /// 获取赛季数据接口
        /// </summary>
        /// <returns></returns>
        public async static Task<Seasons> Post_MatchSeasonData_Path(string selectFootballType)
        {
            try
            {
                GethttpUrl();
                Seasons seasons = new Seasons();
                await Task.Run(() =>
                {
                    string MatchDataPath = strUrl + "matchSeason";
                    Dictionary<string, string> dict = new Dictionary<string, string>();

                    dict.Add("competitionId", selectFootballType);

                    string newKey = Utils.GetKey(appID, appKey);
                    string result = JsonHelper.Post(MatchDataPath, dict, newKey);

                    if (dataFromSource)
                    {
                        Log.Info($"{DateHeaderViewModel.FoolballType} 足球赛季数据:主数据来源:{MatchDataPath}==>" + result);
                    }
                    else
                    {
                        Log.Info($"{DateHeaderViewModel.FoolballType} 足球赛季数据:备份数据来源:{MatchDataPath}==>" + result);
                    }

                    JsonSerializerSettings settings = new JsonSerializerSettings();
                    settings.NullValueHandling = NullValueHandling.Ignore;

                    seasons = JsonConvert.DeserializeObject<Seasons>(result, settings);

                    if (seasons != null)
                    {
                        var sortSeason = seasons.matchseason.OrderByDescending(a => a.seasonName).ToList();
                        seasons.matchseason = sortSeason;
                    }
                    Console.WriteLine("足球赛季数据=========>" + MatchDataPath);

                });
                return seasons;
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
                return null;
            }

        }


        /// <summary>
        /// 获取球队射手榜数据
        /// </summary>
        /// <param name="footballType"></param>
        /// <param name="seasonId"></param>
        /// <returns></returns>
        public async static Task<ShootPlayerRanks> Post_ShootPlayerRankData(string seasonId, string startOffset, string endOffset)
        {
            try
            {
                GethttpUrl();
                ShootPlayerRanks shootPlayerRanks = new ShootPlayerRanks();
                await Task.Run(() =>
                {
                    string shootPath = strUrl + "women/getPlayStatRankBySeason";

                    Dictionary<string, string> dict = new Dictionary<string, string>();

                    //dict.Add("competitionId", footballType);
                    //dict.Add("seasonId", seasonId);//"110000005454"
                    dict.Add("startOffset", startOffset);
                    dict.Add("endOffset", endOffset);

                    string newKey = Utils.GetKey(appID, appKey);

                    string result = JsonHelper.Post(shootPath, dict, newKey);

                    if (dataFromSource)
                    {
                        Log.Info($"{DateHeaderViewModel.FoolballType} 足球球员射手排行:主数据来源:{shootPath}==>" + result);
                    }
                    else
                    {
                        Log.Info($"{DateHeaderViewModel.FoolballType} 足球球员射手排行:备份数据来源:{shootPath}==>" + result);
                    }

                    JsonSerializerSettings settings = new JsonSerializerSettings();

                    settings.NullValueHandling = NullValueHandling.Ignore;

                    shootPlayerRanks = JsonConvert.DeserializeObject<ShootPlayerRanks>(result, settings);

                    if (shootPlayerRanks.playstatrank == null) return;

                    //var sortPlayerShoot = shootPlayerRanks.aystatrank.Take(4).ToList();

                    //shootPlayerRanks.aystatrank = sortPlayerShoot;
                });
                return shootPlayerRanks;
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
                return null;
            }

        }






        /// <summary>
        ///女足球队队员全部信息
        /// </summary>
        /// <returns></returns>
        public async static Task<SingleTeamPlayers> PostTeamPlayerData_Path(string teamId,string matchId,string role)
        {


            try
            {
                Log.Info("开始获取球员信息");
                GethttpUrl();

                SingleTeamPlayers singleTeamPlayers = new SingleTeamPlayers();

                if (string.IsNullOrEmpty(teamId))
                {
                    return null;
                }

                await Task.Run(() =>
                {
                    string TeamScoreDataPath = strUrl + "women/getPlaysByTeam";


                    Dictionary<string, string> dict = new Dictionary<string, string>();

                    if (!string.IsNullOrEmpty(matchId))
                    {
                        dict.Add("matchId", matchId);
                    }
                    dict.Add("teamId", teamId);
                  

                    if (!string.IsNullOrEmpty(role))
                    {
                        dict.Add("role", role);
                    }

                    string newKey = Utils.GetKey(appID, appKey);
                    Log.Info("getPlaysByTeam：开始发送请求数据:"+matchId);
                    string result = JsonHelper.Post(TeamScoreDataPath, dict, newKey);

                    Log.Info("getPlaysByTeam：开发发送结束数据");

                    if (dataFromSource)
                    {
                        Log.Info($"球队队伍球员:主数据来源:{TeamScoreDataPath}==>:" + result);
                    }
                    else
                    {
                        Log.Info($"球队队伍球员:备份数据来源:{TeamScoreDataPath}==>:" + result);
                    }

                    JsonSerializerSettings settings = new JsonSerializerSettings();
                    settings.NullValueHandling = NullValueHandling.Ignore;

                    singleTeamPlayers = JsonConvert.DeserializeObject<SingleTeamPlayers>(result, settings);

                    Console.WriteLine("球队队伍球员============>:" + TeamScoreDataPath);
                    Log.Info("结束获取球员信息");
                });

                return singleTeamPlayers;

           
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
                return null;
            }
        }



        /// <summary>
        ///女足单数据统计
        /// </summary>
        /// <returns></returns>
        public async static Task<SinglePlayers> PostSinglePlayerData_Path(string playerId)
        {
            Log.Info("女足数据统计开始时间");
            try
            {
                GethttpUrl();

                SinglePlayers singlePlayers = new SinglePlayers();

                await Task.Run(() =>
                {
                    string TeamScoreDataPath = strUrl + "women/getPlayStatBySeason";


                    Dictionary<string, string> dict = new Dictionary<string, string>();

                    dict.Add("playerId", playerId);

                    string newKey = Utils.GetKey(appID, appKey);

                    Log.Info("getPlayStatBySeason:开始获取数据");
                    string result = JsonHelper.Post(TeamScoreDataPath, dict, newKey);

                    Log.Info("getPlayStatBySeason:结束获取时间");

                    if (dataFromSource)
                    {
                        Log.Info($"单球员数据统计:主数据来源:{TeamScoreDataPath}==>:" + result);
                    }
                    else
                    {
                        Log.Info($"单球员数据统计:备份数据来源:{TeamScoreDataPath}==>:" + result);
                    }

                    JsonSerializerSettings settings = new JsonSerializerSettings();
                    settings.NullValueHandling = NullValueHandling.Ignore;

                    singlePlayers = JsonConvert.DeserializeObject<SinglePlayers>(result, settings);

                    Console.WriteLine("单球员球员数据统计============>:" + TeamScoreDataPath);

                });

                Log.Info("女足数据统计结束时间");
                return singlePlayers;
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
                return null;
            }
        }





        /// <summary>
        ///女足球队历史数据统计
        /// </summary>
        /// <returns></returns>
        public async static Task<TeamStats> PostTeamHistoryData_Path(string teamId)
        {
            try
            {
                GethttpUrl();

                TeamStats teamStats = new TeamStats();

                if(string.IsNullOrEmpty(teamId))
                {
                    return null;
                }
                    
                await Task.Run(() =>
                {
                    string TeamScoreDataPath = strUrl + "women/historyStat";


                    Dictionary<string, string> dict = new Dictionary<string, string>();

                    dict.Add("teamId", teamId);

                    string newKey = Utils.GetKey(appID, appKey);

                    string result = JsonHelper.Post(TeamScoreDataPath, dict, newKey);

                    if (dataFromSource)
                    {
                        Log.Info($"球队球员数据:主数据来源:{TeamScoreDataPath}==>:" + result);
                    }
                    else
                    {
                        Log.Info($"球队球员数据:备份数据来源:{TeamScoreDataPath}==>:" + result);
                    }

                    JsonSerializerSettings settings = new JsonSerializerSettings();
                    settings.NullValueHandling = NullValueHandling.Ignore;

                    teamStats = JsonConvert.DeserializeObject<TeamStats>(result, settings);
            
                    Console.WriteLine("球队积分排行数据============>:" + TeamScoreDataPath);

                });

                return teamStats;
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
                return null;
            }
        }



    }
}
