using Mall.CacheManager.AppletWeChat;
using Mall.CacheManager.DataStatistic;
using Mall.Common;
using Mall.Common.Plugin;
using Mall.Model.Entity.WeChatStatistics;
using Mall.Model.Extend.TradePavilion;
using Mall.Repository.BaseSetUp;
using Mall.Repository.Coffee;
using Mall.Repository.TradePavilion;
using Mall.Repository.User;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Mall.WindowsService.Module
{
    /// <summary>
    /// 宜宾翠屏商务局小程序统计同步
    /// </summary>
    public class CuiPingModule
    {

        /// <summary>
        /// 小程序统计
        /// </summary>
        private static readonly RB_Wechat_StatisticsRepository wechatStatisticsRepository = new RB_Wechat_StatisticsRepository();

        /// <summary>
        /// 基础配置
        /// </summary>
        private static RB_MallBaseRepository mallBaseRepository = new RB_MallBaseRepository();
        /// <summary>
        /// 基础配置
        /// </summary>
        private static RB_MiniProgramRepository miniProgramRepository = new RB_MiniProgramRepository();

        /// <summary>
        /// 同步小程序统计信息
        /// </summary>
        /// <returns></returns>
        public static bool AddWechatStatistics()
        {
            bool flag = false;
            string mallBaseIds = Config.WechatStatisticsMallBaseId;
            if (!string.IsNullOrWhiteSpace(mallBaseIds))
            {
                var mallBaseIdList = mallBaseIds.Split(",");
                foreach (var item in mallBaseIdList)
                {
                    if (!string.IsNullOrWhiteSpace(item))
                    {
                        try
                        {
                            var miniProgramModel = miniProgramRepository.GetEntity(Convert.ToInt32(item));
                            if ((miniProgramModel?.MallBaseId ?? 0) > 0)
                            {
                                RB_Wechat_Statistics model = new RB_Wechat_Statistics();
                                model.TenantId = miniProgramModel.TenantId ?? 0;
                                model.MallBaseId = miniProgramModel.MallBaseId;
                                model.Status = 0;
                                model.Ref_Date = DateTime.Now.AddDays(-1).ToString("yyyyMMdd");
                                var oldList = wechatStatisticsRepository.GetList(new RB_Wechat_Statistics_Extend { TenantId = model.TenantId, MallBaseId = model.MallBaseId, Ref_Date = model.Ref_Date, Status = 0 });//判断是否已添加信息
                                if (oldList?.Count() > 0)//已同步则不继续
                                {
                                    return false;
                                }
                                var postdata = new
                                {
                                    begin_date = model.Ref_Date,
                                    end_date = model.Ref_Date,
                                };
                                string token = WeiXinReidsCache.Get(miniProgramModel.MiniAppId);
                                if (string.IsNullOrEmpty(token))
                                {
                                    token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, miniProgramModel.MiniAppId, miniProgramModel.MiniAppSecret);
                                    System.Threading.Tasks.Task.Run(() => WeiXinReidsCache.Set(DataConstant.DATA_WeiXinToken + miniProgramModel.MiniAppId, token));
                                }
                                if (string.IsNullOrEmpty(token))
                                {
                                    return false;
                                }
                                if (!string.IsNullOrEmpty(token))
                                {
                                    string wenXinResult = string.Empty;
                                    string Url = "https://api.weixin.qq.com/datacube/getweanalysisappiddailyretaininfo?access_token=" + token;

                                    #region 获取用户访问小程序日留存  https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/data-analysis/visit-retain/getDailyRetain.html
                                    try
                                    {
                                       
                                        wenXinResult = HttpHelper.HttpPost(Url, JsonHelper.Serialize(postdata), "");
                                        JObject jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);
                                        LogHelper.WriteInfo(wenXinResult);
                                        RB_Wechat_Statistics_Extend tempModel = new RB_Wechat_Statistics_Extend();
                                        tempModel = JsonConvert.DeserializeObject<RB_Wechat_Statistics_Extend>(wenXinResult);
                                        if (tempModel.visit_uv_new != null && tempModel.visit_uv_new.Any())
                                        {
                                            model.NewVisitUV = tempModel?.visit_uv_new?.FirstOrDefault()?.value ?? 0;
                                        }
                                        if (tempModel.visit_uv != null && tempModel.visit_uv.Any())
                                        {
                                            model.VisitUV = tempModel?.visit_uv?.FirstOrDefault()?.value ?? 0;
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        LogHelper.Write(ex, "获取用户访问小程序日留存");
                                    }
                                    #endregion

                                    #region 获取用户访问小程序数据日趋势  https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/data-analysis/visit-trend/getDailyVisitTrend.html
                                    try
                                    {
                                       
                                        Url = "https://api.weixin.qq.com/datacube/getweanalysisappiddailyvisittrend?access_token=" + token;
                                        wenXinResult = HttpHelper.HttpPost(Url, JsonHelper.Serialize(postdata), "");
                                        JObject jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);
                                        LogHelper.WriteInfo(wenXinResult);
                                        DailyVisitTrend tempDailyVisitTrendList = new DailyVisitTrend();
                                        tempDailyVisitTrendList = JsonConvert.DeserializeObject<DailyVisitTrend>(wenXinResult);
                                        if (tempDailyVisitTrendList.list != null && tempDailyVisitTrendList.list.Any())
                                        {
                                            DailyVisitTrendItem dailyVisitTrendItem = tempDailyVisitTrendList?.list?.FirstOrDefault();
                                            model.Session_CNT = dailyVisitTrendItem.session_cnt;
                                            model.Visit_PV = dailyVisitTrendItem.visit_pv;
                                            model.Visit_UV = dailyVisitTrendItem.visit_uv;
                                            model.Visit_UV_New = dailyVisitTrendItem.visit_uv_new;
                                            model.Stay_Time_UV = dailyVisitTrendItem.stay_time_uv;
                                            model.Stay_Time_Session = dailyVisitTrendItem.stay_time_session;
                                            model.Visit_Depth = dailyVisitTrendItem.visit_depth;
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        LogHelper.Write(ex, "获取用户访问小程序数据日趋势");
                                    }
                                    #endregion


                                    #region 获取用户访问小程序数据概况  https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/data-analysis/others/getDailySummary.html
                                    try
                                    {
                                       
                                        Url = "https://api.weixin.qq.com/datacube/getweanalysisappiddailysummarytrend?access_token=" + token;
                                        wenXinResult = HttpHelper.HttpPost(Url, JsonHelper.Serialize(postdata), "");
                                        JObject jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);
                                        LogHelper.WriteInfo(wenXinResult);

                                        DailyVisitTrend tempList = new DailyVisitTrend();
                                        tempList = JsonConvert.DeserializeObject<DailyVisitTrend>(wenXinResult);
                                        if (tempList.list != null && tempList.list.Any())
                                        {
                                            DailyVisitTrendItem dailyVisitTrendItem = tempList?.list?.FirstOrDefault();
                                            model.Visit_Total = dailyVisitTrendItem.visit_total;
                                            model.Share_PV = dailyVisitTrendItem.share_pv;
                                            model.Share_UV = dailyVisitTrendItem.share_uv;
                                        }
                                       
                                    }
                                    catch (Exception ex)
                                    {
                                        LogHelper.Write(ex, "获取用户访问小程序数据概况");
                                    }
                                    #endregion

                                    LogHelper.WriteInfo(JsonConvert.SerializeObject(model));
                                    flag = wechatStatisticsRepository.Insert(model) > 0;
                                }
                            }
                        }
                        catch (Exception ex)
                        {


                        }

                    }
                }
            }
            return flag;
        }
    }
}
