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
{
///
/// 微信运动解析
///
public partial class WxRun : BaseApp
{
///
/// 解密微信运动
///
///
///
///
///
public static async Task 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 step = null;
long topstep = 0;
long topsteptime = 0;
bool ischange = false;
var reldata = await dbClient.Queryable().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().Where(x => SqlFunc.DateIsSame(x.CreateTime, step.CreateTime, DateType.Day) && x.UserId == authInfo.UserId).FirstAsync();
if (olddata != null)
{
await dbClient.Updateable()
.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().AnyAsync(x => x.UserId == authInfo.UserId))
{
await dbClient.Insertable(step).ExecuteCommandAsync();
}
else
{
await dbClient.Insertable(list).ExecuteCommandAsync();
}
}
if (ischange)
{
await dbClient.Updateable().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;
}
}
}
}