using Nirvana.Common;
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.NApi.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<WXRunListModel> DecodeWxRunBySessionIdAsync(string sessionId, string encryptedData, string iv)
        {
            var sessionBag = await SessionContainer.GetSessionAsync(sessionId);
            if (sessionBag == null)
            {
                return null;
            }
            var rundata = Senparc.Weixin.WxOpen.Helpers.EncryptHelper.DecryptRunData(sessionId, encryptedData, iv);
            using (var dbClient = ReadDbContext.GetInstance())
            {
                if (rundata != null && rundata.stepInfoList.Count > 0)
                {
                    //第一次保存30天的,第二次就更新当天的。
                    var list = new List<YB_WXRun>();
                    YB_WXRun step = null;
                    long topstep = 0;
                    long topsteptime = 0;
                    bool ischange = false;
                    var reldata = await dbClient.Queryable<YB_UserRealData>().Where(x => x.UserId == authInfo.UserId).FirstAsync();
                    if (reldata != null)
                    {
                        topstep = reldata.TopStep;
                        topsteptime = reldata.TopStepTime;
                    }
                    rundata.stepInfoList.ForEach(x =>
                    {
                        var data = new YB_WXRun
                        {
                            Step = x.step,
                            CreateTime = x.timestamp.ToDatetimeFromTimeStamp(),
                            TimeStamp = x.timestamp,
                            UserId = authInfo.UserId
                        };
                        list.Add(data);
                        if (data.CreateTime.Date.Equals(DateTime.Now.Date))
                        {
                            step = data;
                        }
                        if (data.Step > topstep)
                        {
                            topstep = data.Step;
                            topsteptime = data.TimeStamp;
                            ischange = true;
                        }
                    });
                    var olddata = await dbClient.Queryable<YB_WXRun>().Where(x => SqlFunc.DateIsSame(x.CreateTime, step.CreateTime, DateType.Day) && x.UserId == authInfo.UserId).FirstAsync();
                    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
                    {
                        if (await dbClient.Queryable<YB_WXRun>().AnyAsync(x => x.UserId == authInfo.UserId))
                        {
                            await dbClient.Insertable<YB_WXRun>(step).ExecuteCommandAsync();
                        }
                        else
                        {
                            await dbClient.Insertable<YB_WXRun>(list).ExecuteCommandAsync();
                        }
                    }
                    if (ischange)
                    {
                        await dbClient.Updateable<YB_UserRealData>().SetColumns(x => new YB_UserRealData
                        {
                            TopStep = topstep,
                            TopStepTime = topsteptime
                        }).Where(x => x.UserId == authInfo.UserId).ExecuteCommandAsync();
                    }
                    var returndata = new WXRunListModel
                    {
                        stepInfoList = list.OrderByDescending(x => x.TimeStamp)
                        .Take(7)
                        .Select(x => new WXRunItemModel
                        {
                            createtime = x.CreateTime.ToYearDate(),
                            Step = x.Step
                        })
                        .ToList(),
                        TodayStep = step.Step,
                        TopStep = topstep,
                        TopStepTime = topsteptime,
                        TopStepDateTime = topsteptime.ToDatetimeFromTimeStamp().ToYearDate()
                    };
                    returndata.TotalStep = returndata.stepInfoList.Sum(x => x.Step);
                    return returndata;
                }
                return null;
            }
        }
    }
}
