using Mall.CacheManager.AppletWeChat;
using Mall.CacheManager.DataStatistic;
using Mall.Common;
using Mall.Common.Plugin;
using Mall.Model.Entity.TradePavilion;
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>
        private static RB_Visit_LogRepository _VisitLogRepository = new RB_Visit_LogRepository();
        /// <summary>
        /// 【商载通】 品牌、企业服务仓储层
        /// </summary>
        private static RB_Brand_EnterpriseRepository brand_EnterpriseRepository = new RB_Brand_EnterpriseRepository();

        /// <summary>
        /// 【商载通】【商载通】楼宇、载体服务仓储层
        /// </summary>
        private static RB_Building_CarrierRepository building_CarrierRepository = new RB_Building_CarrierRepository();
        /// <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)
                            {
                                DateTime dateTime = DateTime.Now.AddDays(-1);
                                RB_Wechat_Statistics model = new RB_Wechat_Statistics();
                                model.TenantId = miniProgramModel.TenantId ?? 0;
                                model.MallBaseId = miniProgramModel.MallBaseId;
                                model.Status = 0;
                                model.CreateTime = dateTime;
                                string refDate = model.CreateTime.ToString("yyyyMMdd");
                                string selectDateStr = dateTime.ToString("yyyy-MM-dd");
                                var oldList = wechatStatisticsRepository.GetList(new RB_Wechat_Statistics_Extend { TenantId = model.TenantId, MallBaseId = model.MallBaseId, ref_date = selectDateStr, Status = 0 });//判断是否已添加信息
                                if (oldList?.Count() > 0)//已同步则不继续
                                {
                                    return false;
                                }

                                #region 微信小程序同步
                                var postdata = new
                                {
                                    begin_date = refDate,
                                    end_date = refDate,
                                };
                                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));

                                }
                                #endregion

                                #region 系统数据统计

                                #region 访问统计
                                var visitLogoList = _VisitLogRepository.GetList(new Model.Entity.TradePavilion.RB_Visit_Log { MallBaseId = miniProgramModel.MallBaseId, TenantId = miniProgramModel.TenantId ?? 0 }, startTime: selectDateStr, endTime: selectDateStr);
                                if (visitLogoList != null && visitLogoList.Any())
                                {
                                    model.CarrierVisitNum = visitLogoList?.Where(x => x.ProductType == 1)?.Count() ?? 0;
                                    model.BuildingCarrierVisitNum = visitLogoList?.Where(x => x.ProductType == 2)?.Count() ?? 0;
                                    model.BrandVisitNum = visitLogoList?.Where(x => x.ProductType == 3)?.Count() ?? 0;
                                    model.EnterpriseVisitNum = visitLogoList?.Where(x => x.ProductType == 4)?.Count() ?? 0;
                                }
                                #endregion 

                                #region 新增/总数统计
                                //品牌 Or 企业
                                var brandEnterpriseList = brand_EnterpriseRepository.GetBrandEnterpriseBriefRepository(new RB_Brand_Enterprise_Extend { MallBaseId = miniProgramModel.MallBaseId, TenantId = miniProgramModel.TenantId ?? 0 });
                                if (brandEnterpriseList != null && brandEnterpriseList.Any())
                                {
                                    model.BrandNum = brandEnterpriseList?.Where(x => x.CreateDate.ToString("yyyy-MM-dd") == dateTime.ToString("yyyy-MM-dd") && x.BrandEnterpriseType == 1)?.Count() ?? 0;
                                    model.BrandTotalNum = brandEnterpriseList?.Where(x => x.BrandEnterpriseType == 1)?.Count() ?? 0;

                                    model.EnterpriseNum = brandEnterpriseList?.Where(x => x.CreateDate.ToString("yyyy-MM-dd") == dateTime.ToString("yyyy-MM-dd") && x.BrandEnterpriseType == 2)?.Count() ?? 0;
                                    model.EnterpriseTotalNum = brandEnterpriseList?.Where(x => x.BrandEnterpriseType == 2)?.Count() ?? 0;
                                }

                                //楼宇 Or 载体信息
                                var buildingCarrierList = building_CarrierRepository.GetBuildingCarrierBriefListRepository(new RB_Building_Carrier_Extend { MallBaseId = miniProgramModel.MallBaseId, TenantId = miniProgramModel.TenantId ?? 0 });
                                if (buildingCarrierList != null && buildingCarrierList.Any())
                                {
                                    model.CarrierNum = buildingCarrierList?.Where(x => x.CreateDate.ToString("yyyy-MM-dd") == dateTime.ToString("yyyy-MM-dd") && x.BuildingCarrierType == 1)?.Count() ?? 0;
                                    model.CarrierTotalNum = buildingCarrierList?.Where(x => x.BuildingCarrierType == 1)?.Count() ?? 0;
                                    model.BuildingCarrierNum = buildingCarrierList?.Where(x => x.CreateDate.ToString("yyyy-MM-dd") == dateTime.ToString("yyyy-MM-dd") && x.BuildingCarrierType == 2)?.Count() ?? 0;
                                    model.BuildingCarrierTotalNum = buildingCarrierList?.Where(x => x.BuildingCarrierType == 2)?.Count() ?? 0;
                                }
                                #endregion

                                #endregion
                                flag = wechatStatisticsRepository.Insert(model) > 0;
                            }
                        }
                        catch (Exception ex)
                        {


                        }

                    }
                }
            }
            return flag;
        }
    }
}
