using Nirvana.Common;
using Nirvana.Common.ApiBase;
using Nirvana.Data;
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 ResultApp : BaseApp
    {
        /// <summary>
        /// 增加测量记录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ResultInfo> MeasureAsync(MeasureSubmitModel model)
        {
            if (model.height <= 0)
            {
                return new ResultInfo(ResultState.FAIL, "身高不可小于0");
            }
            if (model.weight <= 0)
            {
                return new ResultInfo(ResultState.FAIL, "体重不可小于0");
            }
            if (string.IsNullOrEmpty(model.ecode))
            {
                return new ResultInfo(ResultState.FAIL, "设备码不可为空");
            }
            using (var dbClient = ReadDbContext.GetInstance())
            {
                //检查设备是否存在
                var equ = await dbClient.Queryable<YB_Device>().AnyAsync(x => x.Ecode == model.ecode);
                if (!equ)
                {
                    return new ResultInfo(ResultState.FAIL, "设备未找到");
                }
                //增加记录
                await dbClient.Ado.UseStoredProcedure().ExecuteCommandAsync("proc_insertresult", new { });
                //计算出本次测量结果的值并返回

                return new ResultInfo(ResultState.SUCCESS, "success");
            }
        }

        /// <summary>
        /// 获取历史记录
        /// </summary>
        /// <param name="param">查询参数</param>
        /// <returns></returns>
        public async Task<PageParms<YB_Measure>> GetHistoryListAsync(ParamQuery param)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                int familyid = param.keyword.ToInt();
                var tempquery = dbClient.Queryable<YB_Measure>().Where(x => x.FamilyId == familyid);
                RefAsync<int> totalnum = 0;
                var query = await tempquery.OrderBy(x => x.createtime, OrderByType.Desc).ToPageListAsync(param.page, param.pagesize, totalnum);
                return new PageParms<YB_Measure>
                {
                    page = param.page,
                    Items = query,
                    totalnum = totalnum,
                    limit = param.pagesize
                };
            }
        }
    }
}
