using JiaZhiQuan.Common.Config;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Dynamic;
using Wicture.DbRESTFul;
using Wicture.DbRESTFul.Infrastructure;
using Wicture.DbRESTFul.Infrastructure.Repository;

namespace JiaZhiQuan.Common
{
    public static partial class RepositoryExtension
    {

        private static bool IsPropertyExist(dynamic data, string propertyName)
        {
            if (data is ExpandoObject)
                return ((IDictionary<string, object>)data).ContainsKey(propertyName);
            return data.GetType().GetProperty(propertyName) != null;
        }

        /// <summary>
        /// 判断是否使用审核数据
        /// </summary>
        /// <param name="repository"></param>
        /// <returns></returns>
        public static bool IsUsingPreviewData(this DbRESTFulRepository repository)
        {
            var httpContext = repository.Context as HttpApiExecutionContext;
            var headers = httpContext.HttpContext.Request.Headers;
            var deviceInfo = httpContext.CustomFields["deviceInfo"];
            var channel = httpContext.CustomFields["channel"];
            try
            {
                if (string.IsNullOrEmpty(deviceInfo)) return false;
                var json = JsonConvert.DeserializeObject<JObject>(deviceInfo);
                var appVersion = channel + "," + json.Value<string>("soft_version");
                return ConfigFromDb.AppPreviewTypeList.Contains(appVersion);
            }
            catch (Exception ex)
            {
                LoggerManager.Logger.Error(ex, "读取os_version进出错");
                return false;
            }
        }

        /// <summary>
        /// 获取当前时间应该获取统计数据的起止日期，startDate <= DATE >= endDate
        /// </summary>
        public static DateRange GetQueryDateRange(this DbRESTFulRepository repository, int days)
        {
            // 如果是早上10点后才展示昨日的数据
            var now = DateTime.Now;
            string endDate;
            string startDate;
            if (days == 0) days = 1;
            if (now.Hour < 10)
            {
                endDate = now.AddDays(-2).ToString("yyyy-MM-dd");
                startDate = now.AddDays(-2 - days + 1).ToString("yyyy-MM-dd");
            }
            else
            {
                endDate = now.AddDays(-1).ToString("yyyy-MM-dd");
                startDate = now.AddDays(-1 - days + 1).ToString("yyyy-MM-dd");
            }

            return new DateRange
            {
                startDate = startDate,
                endDate = endDate,
            };
        }
    }

}
