using Nirvana.Data;
using Senparc.Weixin.WxOpen.Containers;
using Senparc.Weixin.WxOpen.Entities;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YBDevice.Entity;

namespace YBDevice.Api.DBServices
{
    /// <summary>
    /// 微信运动解析
    /// </summary>
    public partial class WxRun : BaseApp
    {
        /// <summary>
        /// 解密微信运动
        /// </summary>
        /// <param name="sessionId"></param>
        /// <param name="encryptedData"></param>
        /// <param name="iv"></param>
        /// <returns></returns>
        public static async Task<DecodedRunData> DecodeWxRunBySessionIdAsync(string sessionId, string encryptedData, string iv)
        {
            var rundata = Senparc.Weixin.WxOpen.Helpers.EncryptHelper.DecryptRunData(sessionId, encryptedData, iv);
            using (var dbClient = ReadDbContext.GetInstance())
            {
                if (rundata != null && rundata.stepInfoList.Count > 0)
                {
                    var list = new List<YB_WXRun>();

                    long currentValue = 0;
                    YB_WXRun step = new YB_WXRun()
                    {
                        UserId=authInfo.UserId
                    };
                    rundata.stepInfoList.ForEach(x =>
                    {
                        long lTime = long.Parse(x.timestamp + "0000000");
                        if (lTime > currentValue)
                        {
                            currentValue = lTime;
                            //DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
                            DateTime dtStart = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1), TimeZoneInfo.Local);
                            TimeSpan toNow = new TimeSpan(currentValue);
                            DateTime targetDt = dtStart.Add(toNow);
                            step.Step = x.step;
                            step.CreateTime = dtStart.Add(toNow);
                            step.TimeStamp = x.timestamp;
                        }
                    });

                    var olddata = await dbClient.Queryable<YB_WXRun>().FirstAsync(x => SqlFunc.DateIsSame(x.CreateTime, step.CreateTime, DateType.Day) && x.UserId == authInfo.UserId);
                    if (olddata != null)
                    {
                        await dbClient.Updateable<YB_WXRun>()
                             .SetColumns(x => new YB_WXRun
                             {
                                 Step = step.Step,
                                 CreateTime = step.CreateTime,
                                 TimeStamp = step.TimeStamp
                             })
                             .Where(x => x.Id == olddata.Id)
                             .ExecuteCommandAsync();
                    }
                    else
                    {
                        await dbClient.Insertable<YB_WXRun>(step)
                             .ExecuteCommandAsync();
                    }
                }
                return rundata;
            }
        }
    }
}
