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.NApi.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 (string.IsNullOrEmpty(model.weight))
            {
                return new ResultInfo(ResultState.FAIL, "体重不可小于0");
            }
            if (string.IsNullOrEmpty(model.ecode))
            {
                return new ResultInfo(ResultState.FAIL, "设备码不可为空");
            }
            if (model.familyid <= 0)
            {
                return new ResultInfo(ResultState.FAIL, "请先选择家庭成员");
            }
            using (var dbClient = ReadDbContext.GetInstance())
            {
                //检查家庭成员是否存在
                if (!await dbClient.Queryable<YB_Family>().AnyAsync(x => x.Id == model.familyid))
                {
                    return new ResultInfo(ResultState.FAIL, "家庭成员未找到");
                }
                //检查设备是否存在
                if (!await dbClient.Queryable<YB_Device>().AnyAsync(x => x.Ecode == model.ecode))
                {
                    return new ResultInfo(ResultState.FAIL, "设备未找到");
                }
                var wg = model.weight.ToUpper();
                if (wg.Contains("LB"))
                {
                    wg = (wg.Replace("LB", "").ToDouble() * 0.4536).ToString();
                }
                else if (wg.Contains("JIN"))
                {
                    wg = (wg.Replace("JIN", "").ToDouble() / 2.0).ToString();
                }
                else if (wg.Contains("ST")) //英石
                {
                    wg = (wg.Replace("ST", "").ToDouble() *6.35).ToString();
                }
                else
                {
                    wg = wg.Replace("KG", "");
                }
                decimal weight = wg.ToDecimal();
                var family = await dbClient.Queryable<YB_Family>().FirstAsync(x => x.Id == model.familyid);
                //计算结果
                var result = BodyFatHelper.CalcBodyFat(weight.ToDouble(), model.height, family.Age, model.imp.ToInt(), family.Sex);
                //年龄月份
                var month = family.Birthday.ToMonth();
                //增加记录
                await dbClient.Ado.UseStoredProcedure().ExecuteCommandAsync("proc_insertresult", new
                {
                    sex = family.Sex,
                    age = family.Age,
                    month = month,
                    height = model.height,
                    weight = weight,
                    imp = model.imp,
                    ecode = model.ecode,
                    familyid = model.familyid,
                    userid = authInfo.UserId,
                    fat_r = result.fat_r,
                    muscle = result.muscle,
                    water = result.water,
                    bone = result.bone,
                    kcal = result.kcal,
                    fat_w = result.fat_w,
                    visceral = result.visceral,
                    protein = result.protein,
                    bodyage = result.bodyage,
                    bmi = result.bmi,
                    cmi = result.cmi,
                    sfr = result.sfr,
                    muscleval = result.muscleval,
                    proteinval = result.proteinval,
                    lbm = result.lbm,
                    body = result.bodylevel,
                    fatlevel = result.fatLevel
                });
                return new ResultInfo(ResultState.SUCCESS, "测量成果");
            }
        }

        /// <summary>
        /// 手动增加测量记录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ResultInfo> InsertMeasureAsync(UserMeasureSubmitModel model)
        {
            if (model.weight <= 0)
            {
                return new ResultInfo(ResultState.FAIL, "体重不可小于0");
            }
            if (model.familyid <= 0)
            {
                return new ResultInfo(ResultState.FAIL, "请先选择家庭成员");
            }
            using (var dbClient = ReadDbContext.GetInstance())
            {
                //检查家庭成员是否存在
                if (!await dbClient.Queryable<YB_Family>().AnyAsync(x => x.Id == model.familyid))
                {
                    return new ResultInfo(ResultState.FAIL, "家庭成员未找到");
                }
                var family = await dbClient.Queryable<YB_Family>().FirstAsync(x => x.Id == model.familyid);
                //计算结果
                var result = BodyFatHelper.CalcBodyFat(model.weight.ToDouble(), family.Height.ToDouble(), family.Age, 0, family.Sex);
                //年龄月份
                var month = family.Birthday.ToMonth();
                //增加记录
                await dbClient.Ado.UseStoredProcedure().ExecuteCommandAsync("proc_insertresult", new
                {
                    sex = family.Sex,
                    age = family.Age,
                    month = month,
                    height = model.Height <= 0 ? family.Height : model.Height,
                    weight = model.weight,
                    imp = 0,
                    ecode = "YB0001",//所有手动添加的记录都默认为此设置
                    familyid = model.familyid,
                    userid = authInfo.UserId,
                    fat_r = result.fat_r,
                    muscle = result.muscle,
                    water = result.water,
                    bone = result.bone,
                    kcal = result.kcal,
                    fat_w = result.fat_w,
                    visceral = result.visceral,
                    protein = result.protein,
                    bodyage = result.bodyage,
                    bmi = result.bmi,
                    cmi = result.cmi,
                    sfr = result.sfr,
                    muscleval = result.muscleval,
                    proteinval = result.proteinval,
                    lbm = result.lbm,
                    body = result.bodylevel,
                    fatlevel = result.fatLevel,
                    createtime = model.time.ToDate(),
                    sourcetype = 2 //1-蓝牙传输,2-手动记录
                });
                return new ResultInfo(ResultState.SUCCESS, "记录成功");
            }
        }

        /// <summary>
        /// 获取历史记录
        /// </summary>
        /// <param name="param">查询参数</param>
        /// <returns></returns>
        public async Task<PageParms<MeasureHisList>> 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)
                    .Select(x=>new MeasureHisList {
                        bmi=x.bmi,
                        body=x.body,
                        bodyage=x.bodyage,
                        bone=x.bone,
                        cmi=x.cmi,
                        createtime=SqlFunc.ToString(x.createtime),
                        fatlevel=x.fatlevel,
                        fat_r=x.fat_r,
                        fat_w=x.fat_w,
                        Height=x.Height,
                        kcal=x.kcal,
                        lbm=x.lbm,
                        muscle=x.muscle,
                        muscleval=x.muscleval,
                        protein=x.protein,
                        proteinval=x.proteinval,
                        sfr=x.sfr,
                        visceral=x.visceral,
                        water=x.water,
                        weight=x.Weight,
                        Age=SqlFunc.ToString(x.Age),
                        Month=x.Month
                    })
                    .Mapper((it, cache) => {
                        it.createtime = it.createtime.ToYearDateTime();
                        it.Age = it.Month.TomAge();
                    })
                    .ToPageListAsync(param.page, param.pagesize, totalnum);
                return new PageParms<MeasureHisList>
                {
                    page = param.page,
                    Items = query,
                    totalnum = totalnum,
                    limit = param.pagesize
                };
            }
        }
        /// <summary>
        /// 手动添加的历史记录
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<PageParms<AddResultList>> GetAddListAsync(ParamQuery param)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var tempquery = dbClient.Queryable<YB_ResultAdd>();
                RefAsync<int> totalnum = 0;
                if (!string.IsNullOrEmpty(param.keyword))
                {
                    var familyid = param.keyword.ToInt();
                    tempquery = tempquery.Where(x => x.FamilyId == familyid);
                }
                else
                {
                    tempquery = tempquery.Where(x => x.UserId == authInfo.UserId);
                }
                var query = await tempquery.OrderBy(x => x.CreateTime, OrderByType.Desc)
                    .Select(x => new AddResultList
                    {
                        CreateTime = SqlFunc.ToString(x.CreateTime),
                        Height = x.Height,
                        Weight = x.Weight,
                        Id = x.Id,
                        ResultTime = SqlFunc.ToString(x.ResultTime)
                    })
                    .Mapper((it, cache) =>
                    {
                        it.CreateTime = it.CreateTime.ToYearDateTime();
                        it.ResultTime = it.ResultTime.ToYearDate();
                    })
                    .ToPageListAsync(param.page, param.pagesize, totalnum);
                return new PageParms<AddResultList>
                {
                    page = param.page,
                    Items = query,
                    totalnum = totalnum,
                    limit = param.pagesize
                };
            }
        }

        /// <summary>
        /// 删除手动添加的记录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultInfo> DeleteAddResultAsync(int id)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var data = await dbClient.Queryable<YB_ResultAdd>().FirstAsync(x => x.Id == id);
                if (data == null)
                {
                    return new ResultInfo(ResultState.FAIL, "记录未找到");
                }

                await dbClient.Deleteable<YB_ResultAdd>().Where(x => x.Id == id).ExecuteCommandAsync();
                //删除关联的记录
                await dbClient.Deleteable<YB_ResultExt>().Where(x => x.ResultId == data.ResultId).ExecuteCommandAsync();

                await dbClient.Deleteable<YB_Measure>().Where(x => x.ResultId == data.ResultId).ExecuteCommandAsync();
                return new ResultInfo(ResultState.SUCCESS, "删除成功");
            }
        }
    }
}
