using DotNetCore.CAP;
using Furion.DependencyInjection;
using Furion.DistributedIDGenerator;
using Mapster;
using Nirvana.Common;
using Nirvana.Common.ApiBase;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using YBDevice.Body.BodyFatHelper;
using YBDevice.CommonService;
using YBDevice.CommonService.DevTypeInfo;
using YBDevice.Entity;
using YBDevice.NApi.Application.UserInfo;

namespace YBDevice.NApi.Application.MeasureInfo
{
    /// <summary>
    /// 用户测量处理
    /// </summary>
    public class ResultService : BaseService, IResultService, ITransient
    {
        private readonly ISqlSugarRepository<YB_nMeasureResult> repository;
        private readonly SqlSugarClient dbClient;
        private readonly IBodyFatHelperService _bodyFatHelperService;
        private readonly IDeviceTypeService _deviceTypeService;
        private readonly ICapPublisher _capBus;
        private readonly IUserService _userService;

        public ResultService(ISqlSugarRepository<YB_nMeasureResult> sqlSugarRepository, IBodyFatHelperService bodyFatHelperService, ICapPublisher capPublisher, IDeviceTypeService deviceTypeService, IUserService userService)

        {
            repository = sqlSugarRepository;
            dbClient = repository.Context;
            _bodyFatHelperService = bodyFatHelperService;
            _capBus = capPublisher;
            _deviceTypeService = deviceTypeService;
            _userService = userService;
        }

        /// <summary>
        /// 增加测量记录,用于蓝牙传输,适用于F01PRO
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ResultInfo> MeasureDataAsync(MeasureDataSubmitModel model)
        {
            //检查家庭成员是否存在
            if (!await dbClient.Queryable<YB_Family>().AnyAsync(x => x.Id == model.familyid))
            {
                return new ResultInfo(ResultState.FAIL, "家庭成员未找到");
            }
            //检查设备是否存在
            var device = await dbClient.Queryable<YB_Device>().FirstAsync(x => x.Ecode == model.ecode);
            if (device == null)
            {
                return new ResultInfo(ResultState.DEVNOTFOUND, "设备未找到,请到管理端进行激活");
            }
            if (device.Status != DeviceStatus.Run)
            {
                return new ResultInfo(ResultState.DEVNOTFOUND, "设备还未激活,请先激活");
            }
            decimal weight = AnalyWeight(model.weight);
            var family = await dbClient.Queryable<YB_Family>().FirstAsync(x => x.Id == model.familyid);
            //增加yb_nresult
            var result = new YB_nResult
            {
                Id = IDGen.NextID(),
                SourceType = 1,
                BusinessId = device.BusinessId,
                CreateTime = DateTime.Now,
                DevType = device.Type,
                EquId = device.Id,
                Height = model.height,
                Weight = weight,
                Imp = model.imp,
                LeftArmImp = 0,
                RightArmImp = 0,
                LeftLegImp = 0,
                RightLegImp = 0
            };
            await dbClient.Insertable(result).ExecuteCommandAsync();

            //用户认领,加入认领表并进行结果计算
            var month = family.Birthday.ToMonth();
            var fansid = await dbClient.Queryable<YB_RegUser>().Where(x => x.Id == authInfo.UserId).Select(x => x.FansId).FirstAsync();
            //增加yb_nuserresult
            var userresult = new YB_nUserResult
            {
                CreateTime = result.CreateTime,
                FamilyId = model.familyid,
                Id = result.Id,
                UserId = authInfo.UserId,
                DevType = result.DevType,
                FansId = fansid,
                Status = 1
            };
            await dbClient.Insertable(userresult).ExecuteCommandAsync();
            //计算结果
            MeasureCalcDto calcdata = new MeasureCalcDto
            {
                weight = weight.ToString(),
                imp = model.imp,
                height = model.height,
                ecode = model.ecode,
                familyid = model.familyid,
                bodyage = model.bodyage,
                fat_r = model.fat_r,
                muscle = model.muscle,
                water = model.water,
                bone = model.bone,
                kcal = model.kcal,
                visceral = model.visceral,
                protein = model.protein,
                bmi = model.bmi,
                sfr = model.sfr,
                fatlevlval = model.fatlevlval,
                StandardWeight = model.StandardWeight,
                fat_w = model.fat_w,
                lbm = model.lbm,
                muscleval = model.muscleval,
                proteinval = model.proteinval,
                age = family.Age,
                sex = family.Sex
            };
            var calcresult = _bodyFatHelperService.CalcBodyFat(calcdata);
            //增加计算结果
            var measureresult = new YB_nMeasureResult
            {
                Id = result.Id,
                sfr = calcresult.sfr,
                Sex = family.Sex,
                SfrVal = 0,
                SkeletalMuscle = 0,
                Age = family.Age,
                DevType = device.Type,
                bmi = calcresult.bmi,
                body = calcresult.bodylevel,
                bodyage = calcresult.bodyage,
                BodyFat = 0,
                BodyFatVal = 0,
                BodyMuscle = 0,
                BodyMuscleVal = 0,
                bone = calcresult.bone,
                cmi = calcresult.cmi,
                createtime = DateTime.Now,
                fatlevel = calcresult.fatLevel,
                fat_r = calcresult.fat_r,
                fat_w = calcresult.fat_w,
                Height = model.height,
                IdealWeight = calcresult.standardWeight.ToDecimal(),
                kcal = calcresult.kcal,
                lbm = calcresult.lbm,
                LeftFootFat = 0,
                LeftFootFatVal = 0,
                LeftFootMuscle = 0,
                LeftFootMuscleVal = 0,
                LeftHandFat = 0,
                LeftHandFatVal = 0,
                LeftHandMuscle = 0,
                LeftHandMuscleVal = 0,
                Month = month,
                muscle = calcresult.muscle,
                muscleval = calcresult.muscleval,
                protein = calcresult.protein,
                proteinval = calcresult.proteinval,
                RightFootFat = 0,
                RightFootFatVal = 0,
                RightFootMuscle = 0,
                RightFootMuscleVal = 0,
                RightHandFat = 0,
                RightHandFatVal = 0,
                RightHandMuscle = 0,
                RightHandMuscleVal = 0,
                visceral = calcresult.visceral,
                water = calcresult.water,
                Weight = calcresult.weight
            };
            await dbClient.Insertable(measureresult).ExecuteCommandAsync();

            //更新家庭成员的最新体重
            await dbClient.Updateable<YB_Family>().SetColumns(x => new YB_Family
            {
                Weight = weight,
                Height = model.height,
                LastHeartTime = result.CreateTime
            }).Where(x => x.Id == family.Id).ExecuteCommandAsync();
            //更新家庭成员统计数据
            if (family.LastHeartTime.HasValue)
            {
                await dbClient.Updateable<YB_FamilyData>().SetColumns(x => new YB_FamilyData
                {
                    LastHeight = model.height,
                    LastWeight = weight,
                    LastResultTime = result.CreateTime,
                    TotalCount = x.TotalCount + 1,
                    TodayCount = x.TodayCount + 1,
                    LastTimeWeight = x.LastWeight - weight,
                    LastTimeHeight = x.LastHeight - model.height,
                    LastResultHeightTime = result.CreateTime
                }).Where(x => x.FamilyId == family.Id).ExecuteCommandAsync();
            }
            else
            {
                await dbClient.Updateable<YB_FamilyData>().SetColumns(x => new YB_FamilyData
                {
                    LastHeight = model.height,
                    LastWeight = weight,
                    LastResultTime = result.CreateTime,
                    TotalCount = x.TotalCount + 1,
                    TodayCount = x.TodayCount + 1,
                    LastTimeWeight = 0,
                    LastTimeHeight = 0,
                    FirstResultTime = result.CreateTime,
                    FirstHeight = model.height,
                    FirstWeight = weight,
                    LastResultHeightTime = result.CreateTime
                }).Where(x => x.FamilyId == family.Id).ExecuteCommandAsync();
            }
            //更新家庭成员数据
            List<int> devtypes = await _deviceTypeService.GetDevTypesAsync(device.Type);
            var familyrealdata = await dbClient.Queryable<YB_FamilyRealData>().FirstAsync(x => x.FamilyId == family.Id && x.DevType == device.Type);
            if (familyrealdata != null)
            {
                decimal monthheight = familyrealdata.MonthHeight;
                decimal monthweight = familyrealdata.MonthWeight;
                //是否为同一个月
                var nowtime = DateTime.Now;
                if (result.CreateTime.Year == nowtime.Year && result.CreateTime.Month == nowtime.Month)
                {
                    monthheight = familyrealdata.MonthHeight > model.height ? familyrealdata.MonthHeight : model.height;
                    monthweight = familyrealdata.LastResultTime < result.CreateTime ? weight : familyrealdata.MonthWeight;
                }
                await dbClient.Updateable<YB_FamilyRealData>().SetColumns(x => new YB_FamilyRealData
                {
                    LastHeight = model.height,
                    LastWeight = weight,
                    LastResultTime = result.CreateTime,
                    TotalCount = x.TotalCount + 1,
                    TodayCount = x.TodayCount + 1,
                    LastTimeHeight = x.LastHeight - model.height,
                    LastTimeWeight = x.LastWeight - weight,
                    MonthHeight = monthheight,
                    MonthWeight = monthweight,
                    LastResultId = result.Id,
                    LastResultHeightTime = result.CreateTime
                }).Where(x => x.FamilyId == family.Id && devtypes.Contains(x.DevType)).ExecuteCommandAsync();
            }
            //更新合计数据并添加用户设备类型
            await _capBus.PublishAsync("result.service.updaterealdata", new UpdateRealDataS2SDtO
            {
                CreateTime = result.CreateTime,
                DevId = device.Id,
                familyid = family.Id,
                height = model.height,
                IsUserTake = true,
                UserId = userresult.UserId,
                weight = weight
            });
            return new ResultInfo(ResultState.SUCCESS, "测量成功");
        }

        /// <summary>
        /// 添加测量记录
        /// </summary>
        /// <param name="data"></param>
        /// <param name="device"></param>
        /// <param name="family"></param>
        /// <returns></returns>
        private async Task InsertResultAsync(InsertResultC2SDto data, YB_Device device, YB_Family family)
        {
            if (!data.CreateTime.HasValue)
            {
                data.CreateTime = DateTime.Now;
            }
            var familyrealdata = await dbClient.Queryable<YB_FamilyRealData>().FirstAsync(x => x.FamilyId == data.familyid && x.DevType == device.Type);
            if (familyrealdata == null)
            {
                familyrealdata = new YB_FamilyRealData
                {
                    FamilyId = data.familyid,
                    FirstHeight = data.height,
                    FirstResultTime = data.CreateTime,
                    DevType = device.Type,
                    CreateTime = DateTime.Now,
                    FirstWeight = data.weight,
                    Id = IDGen.NextID(),
                    LastHeight = data.height,
                    LastResultTime = data.CreateTime,
                    LastTimeHeight = 0,
                    LastTimeWeight = 0,
                    LastWeight = data.weight,
                    TodayCount = 0,
                    TotalCount = 0,
                    UserId = family.UserId,
                    MonthHeight = data.height,
                    MonthWeight = data.weight,
                    LastResultHeightTime = data.CreateTime,
                    LastHead = data.Head,
                    MonthHead = data.Head
                };
                await dbClient.Insertable(familyrealdata).ExecuteCommandAsync();
            }
            if (data.SourceType != 2 || (data.SourceType == 2 && (!familyrealdata.LastResultTime.HasValue || familyrealdata.LastResultTime.Value <= data.CreateTime)))
            {
                //更新家庭成员的最新体重
                await dbClient.Updateable<YB_Family>().SetColumns(x => new YB_Family
                {
                    Weight = data.weight,
                    Height = data.height,
                    LastHeartTime = data.CreateTime,
                    Head = data.Head
                }).Where(x => x.Id == data.familyid).ExecuteCommandAsync();
                //更新家庭成员统计数据
                if (family.LastHeartTime.HasValue)
                {
                    await dbClient.Updateable<YB_FamilyData>().SetColumns(x => new YB_FamilyData
                    {
                        LastHeight = data.height,
                        LastWeight = data.weight,
                        LastHead = data.Head,
                        LastResultTime = data.CreateTime,
                        TotalCount = x.TotalCount + 1,
                        TodayCount = x.TodayCount + 1,
                        LastTimeWeight = x.LastWeight - data.weight,
                        LastTimeHeight = x.LastHeight - data.height,
                        LastResultHeightTime = data.CreateTime
                    }).Where(x => x.FamilyId == data.familyid).ExecuteCommandAsync();
                }
                else
                {
                    await dbClient.Updateable<YB_FamilyData>().SetColumns(x => new YB_FamilyData
                    {
                        LastHeight = data.height,
                        LastWeight = data.weight,
                        LastHead = data.Head,
                        LastResultTime = data.CreateTime,
                        TotalCount = x.TotalCount + 1,
                        TodayCount = x.TodayCount + 1,
                        LastTimeWeight = 0,
                        LastTimeHeight = 0,
                        FirstResultTime = data.CreateTime,
                        FirstHeight = data.height,
                        FirstWeight = data.weight,
                        LastResultHeightTime = data.CreateTime
                    }).Where(x => x.FamilyId == data.familyid).ExecuteCommandAsync();
                }
                //更新家庭成员数据
                List<int> devtypes = await _deviceTypeService.GetDevTypesAsync(device.Type);
                if (familyrealdata != null)
                {
                    decimal monthheight = familyrealdata.MonthHeight;
                    decimal monthweight = familyrealdata.MonthWeight;
                    decimal monthhead = familyrealdata.MonthHead;
                    //是否为同一个月
                    var nowtime = DateTime.Now;
                    if (data.CreateTime.Value.Year == nowtime.Year && data.CreateTime.Value.Month == nowtime.Month)
                    {
                        monthheight = familyrealdata.MonthHeight > data.height ? familyrealdata.MonthHeight : data.height;
                        monthweight = familyrealdata.LastResultTime < data.CreateTime ? data.weight : familyrealdata.MonthWeight;
                        monthhead = familyrealdata.LastResultTime < data.CreateTime ? data.Head : familyrealdata.MonthHead;
                    }
                    await dbClient.Updateable<YB_FamilyRealData>().SetColumns(x => new YB_FamilyRealData
                    {
                        LastHeight = data.height,
                        LastWeight = data.weight,
                        LastHead = data.Head,
                        LastResultTime = data.CreateTime,
                        TotalCount = x.TotalCount + 1,
                        TodayCount = x.TodayCount + 1,
                        LastTimeHeight = x.LastHeight - data.height,
                        LastTimeWeight = x.LastWeight - data.weight,
                        MonthHeight = monthheight,
                        MonthWeight = monthweight,
                        LastResultId = data.ResultId,
                        LastResultHeightTime = data.CreateTime,
                        MonthHead = monthhead
                    }).Where(x => x.FamilyId == data.familyid && devtypes.Contains(x.DevType)).ExecuteCommandAsync();
                }
            }
            await _capBus.PublishAsync("result.service.insertuserresult", new InsertResultDataS2SDto
            {
                CreateTime = data.CreateTime,
                SourceType = data.SourceType,
                BusinessId = device.BusinessId,
                DeviceLastHeartTime = device.LastHeartTime,
                DevId = device.Id,
                DevType = device.Type,
                ecode = device.Ecode,
                familyid = data.familyid,
                fansid = data.fansid,
                height = data.height,
                Head = data.Head,
                imp = data.imp,
                IsUserTake = data.IsUserTake,
                LeftArmImp = data.LeftArmImp,
                LeftLegImp = data.LeftLegImp,
                orderid = data.orderid,
                publicid = data.publicid,
                ResultId = data.ResultId,
                RightArmImp = data.RightArmImp,
                RightLegImp = data.RightLegImp,
                UserId = data.UserId,
                weight = data.weight
            });
        }

        /// <summary>
        /// 解析身高
        /// </summary>
        /// <param name="height">身高值,带有单位</param>
        /// <returns></returns>
        private decimal AnalyHeight(string height)
        {
            decimal dheight = 0;
            height = height.ToLower();
            if (height.Contains("cm"))
            {
                dheight = height.Substring(0, height.Length - 2).ToDecimal();
            }
            else if (height.Contains("ft"))
            {
                dheight = (height.Substring(0, height.Length - 2).ToDecimal()) * 0.3048m * 100;
            }
            else
            {
                dheight = height.ToDecimal();
            }
            dheight = dheight.ToDecimal(1);
            return dheight;
        }

        /// <summary>
        /// 体重解析
        /// </summary>
        /// <param name="weight">重量值,带有单位</param>
        /// <returns></returns>
        private decimal AnalyWeight(string weight)
        {
            var wg = 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 if (wg.Contains("G") && !wg.Contains("KG")) //克
            {
                wg = (wg.Replace("G", "").ToDouble() / 1000.0).ToString();
            }
            else
            {
                wg = wg.Replace("KG", "");
            }
            return wg.ToDecimal(2);
        }

        /// <summary>
        /// 增加测量记录,用于蓝牙传输,身高带有单位(cm/ft)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ResultInfo> MeasureOfUnitAsync(MeasureOfUnitSubmitModel model)
        {
            //解析身高
            decimal height = AnalyHeight(model.height);
            return await MeasureAsync(new MeasureSubmitModel
            {
                ecode = model.ecode,
                familyid = model.familyid,
                height = height,
                imp = model.imp,
                weight = model.weight,
                Head = model.Head
            });
        }

        /// <summary>
        /// 增加测量记录,用于蓝牙传输
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ResultInfo> MeasureAsync(MeasureSubmitModel model)
        {
            //检查家庭成员是否存在
            var family = await dbClient.Queryable<YB_Family>().FirstAsync(x => x.Id == model.familyid);
            if (family == null)
            {
                return new ResultInfo(ResultState.FAIL, "家庭成员未找到");
            }
            //检查设备是否存在
            var device = await dbClient.Queryable<YB_Device>().FirstAsync(x => x.Ecode == model.ecode);
            if (device == null)
            {
                return new ResultInfo(ResultState.DEVNOTFOUND, "设备未找到,请到管理端进行激活");
            }
            if (device.Status != DeviceStatus.Run)
            {
                return new ResultInfo(ResultState.DEVNOTFOUND, "设备还未激活,请先激活");
            }
            decimal weight = AnalyWeight(model.weight);
            await InsertResultAsync(new InsertResultC2SDto
            {
                DevId = device.Id,
                SourceType = 1,
                ecode = device.Ecode,
                familyid = family.Id,
                height = model.height,
                imp = model.imp,
                IsUserTake = true,
                UserId = authInfo.UserId,
                weight = weight,
                ResultId = IDGen.NextID(),
                CreateTime = DateTime.Now,
                fansid = null,
                LeftArmImp = 0,
                LeftLegImp = 0,
                orderid = null,
                publicid = "",
                Head = model.Head,
                RightArmImp = 0,
                RightLegImp = 0
            }, device, family);
            return new ResultInfo(ResultState.SUCCESS, "测量成功");
        }

        /// <summary>
        /// 手动增加测量记录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ResultInfo> InsertMeasureAsync(UserMeasureSubmitModel model)
        {
            var family = await dbClient.Queryable<YB_Family>().FirstAsync(x => x.Id == model.familyid);
            //检查家庭成员是否存在
            if (family == null)
            {
                return new ResultInfo(ResultState.FAIL, "家庭成员未找到");
            }
            //查找最近使用的设备
            var familydata = await dbClient.Queryable<YB_FamilyRealData>().FirstAsync(x => x.DevType == model.DevType && x.FamilyId == model.familyid);
            YB_Device device = null;
            if (familydata != null && familydata.LastResultId.HasValue && familydata.LastResultId.Value != Guid.Empty)
            {
                var lastresult = await dbClient.Queryable<YB_nResult>().FirstAsync(x => x.Id == familydata.LastResultId);
                if (lastresult != null)
                {
                    device = await dbClient.Queryable<YB_Device>().FirstAsync(x => x.Id == lastresult.EquId);
                }
            }
            if (device == null)
            {
                device = await dbClient.Queryable<YB_Device>().FirstAsync(x => x.Id == 1);
            }
            var ctime = model.time.ToDate();
            string time = $"{ctime.Year}-{ctime.Month}-{ctime.Day} {DateTime.Now.Hour}:{DateTime.Now.Minute}:{DateTime.Now.Second}";
            DateTime createtime = time.ToDate();
            device.Type = model.DevType;
            await InsertResultAsync(new InsertResultC2SDto
            {
                DevId = device.Id,
                SourceType = 2,
                ecode = device.Ecode,
                familyid = family.Id,
                height = model.Height <= 0 ? family.Height : model.Height,
                imp = 0,
                IsUserTake = true,
                UserId = authInfo.UserId,
                weight = model.weight,
                CreateTime = createtime,
                fansid = null,
                LeftArmImp = 0,
                LeftLegImp = 0,
                orderid = null,
                publicid = "",
                ResultId = IDGen.NextID(),
                RightArmImp = 0,
                RightLegImp = 0,
                Head = model.Head
            }, device, family);
            return new ResultInfo(ResultState.SUCCESS, "记录成功");
        }

        /// <summary>
        /// 获取历史记录
        /// </summary>
        /// <param name="param">查询参数</param>
        /// <returns></returns>
        public async Task<PageParms<MeasureHisList>> GetHistoryListAsync(ParamQuery param)
        {
            int familyid = param.keyword.ToInt();
            List<int> devtypes = new List<int>();
            var tempquery = dbClient.Queryable<YB_nUserResult, YB_nMeasureResult>((u, x) => new JoinQueryInfos(
                   JoinType.Left, u.Id == x.Id
               )).Where((u, x) => u.FamilyId == familyid && u.Status == 1);
            if (param.devtype > 0)
            {
                devtypes = await _deviceTypeService.GetDevTypesAsync(param.devtype);
                tempquery = tempquery.Where((u, x) => SqlFunc.ContainsArray(devtypes, u.DevType));
            }
            RefAsync<int> totalnum = 0;
            var query = await tempquery.OrderBy((u, x) => x.createtime, OrderByType.Desc)
                .Select((u, 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,
                    Id = x.Id
                })
                .Mapper((it, cache) =>
                {
                    it.bmi = it.bmi.ToDecimal(1);
                    it.createtime = it.createtime.ToYearDateTime();
                    it.Age = it.Month.TomAge();
                    it.bone = it.bone.ToDecimal(1);
                    it.cmi = it.cmi.ToDecimal(1);
                    it.fat_r = it.fat_r.ToDecimal(1);
                    it.fat_w = it.fat_w.ToDecimal(1);
                    it.kcal = it.kcal.ToDecimal(1);
                    it.lbm = it.lbm.ToDecimal(1);
                    it.muscle = it.muscle.ToDecimal(1);
                    it.muscleval = it.muscleval.ToDecimal(1);
                    it.protein = it.protein.ToDecimal(1);
                    it.proteinval = it.proteinval.ToDecimal(1);
                    it.sfr = it.sfr.ToDecimal(1);
                    it.visceral = it.visceral.ToDecimal(1);
                    it.water = it.water.ToDecimal(1);
                    it.weight = it.weight.ToDecimal(1);
                })
                .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)
        {
            var tempquery = dbClient.Queryable<YB_nResultAdd>();
            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(Guid id)
        {
            var data = await dbClient.Queryable<YB_nResultAdd>().FirstAsync(x => x.Id == id);
            if (data == null)
            {
                return new ResultInfo(ResultState.FAIL, "记录未找到");
            }

            await dbClient.Deleteable<YB_nResultAdd>().Where(x => x.Id == id).ExecuteCommandAsync();
            //删除关联的记录
            await DeleteAsync(new DeleteResultC2SDto
            {
                Id = id
            });
            return new ResultInfo(ResultState.SUCCESS, "删除成功");
        }

        /// <summary>
        /// 检测设备状态
        /// </summary>
        /// <param name="sn">设备机器码</param>
        /// <param name="type">类型,0-检测设备是否存在,1-不检测</param>
        /// <returns></returns>
        public async Task<ResultInfo> CheckDevStatus(string sn, int type = 0)
        {
            if (string.IsNullOrEmpty(sn))
            {
                return new ResultInfo(ResultState.FAIL, "设备编码不可为空");
            }
            var equ = await dbClient.Queryable<YB_Device>().FirstAsync(x => x.Ecode == sn);
            if (equ == null)
            {
                if (type == 1)
                {
                    return new ResultInfo(ResultState.DEVNOTFOUND, "此设备还未激活,请先激活", new
                    {
                        type = 4
                    });
                }
                return new ResultInfo(ResultState.DEVNOTFOUND, "此设备还未激活,请先激活");
            }
            if (equ.Status == DeviceStatus.UnActive)
            {
                //检查设备类型,
                var devicetype = await dbClient.Queryable<YB_DeviceType>().FirstAsync(x => x.Code == equ.Type);
                return new ResultInfo(ResultState.DEVNOTFOUND, "此设备还未激活,请先激活", new
                {
                    type = devicetype.ProType
                });
            }
            if (equ.Status == (int)DeviceStatus.Stop)
            {
                return new ResultInfo(ResultState.FAIL, "此设备暂不可使用");
            }
            return new ResultInfo(ResultState.SUCCESS, "success");
        }

        /// <summary>
        /// 获取八电极历史记录
        /// </summary>
        /// <param name="param">查询参数</param>
        /// <returns></returns>
        public async Task<PageParms<BodyMeasureHisListDto>> GetBodyHistoryListAsync(ParamQuery param)
        {
            int familyid = param.keyword.ToInt();
            if (familyid <= 0)
            {
                familyid = (await dbClient.Queryable<YB_Family>().FirstAsync(x => x.UserId == authInfo.UserId && x.IsSelf == 1)).Id;
            }
            var devtypes = await _deviceTypeService.GetDevTypesAsync(param.devtype);
            var tempquery = dbClient.Queryable<YB_nMeasureResult, YB_nUserResult>((x, b) => new JoinQueryInfos(
                      JoinType.Left, b.Id == x.Id
                  )).Where((x, b) => b.FamilyId == familyid && b.Status == 1 && devtypes.Contains(b.DevType));
            RefAsync<int> totalnum = 0;
            var query = await tempquery.OrderBy((x, b) => b.CreateTime, OrderByType.Desc)
                .Select((x, b) => new BodyMeasureHisList
                {
                    bmi = x.bmi,
                    body = x.body,
                    fatLevel = x.fatlevel,
                    bodyage = x.bodyage,
                    bone = x.bone,
                    cmi = x.cmi,
                    time = b.CreateTime,
                    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 = x.Age,
                    sfrval = x.SfrVal,
                    SkeletalMuscle = x.SkeletalMuscle,
                    muscleratetrunk = x.BodyMuscle,
                    musclerateleftleg = x.LeftFootMuscle,
                    muscleraterightleg = x.RightFootMuscle,
                    musclerateleftarm = x.LeftHandMuscle,
                    muscleraterightarm = x.RightHandMuscle,
                    musclekgtrunk = x.BodyMuscleVal,
                    musclekgleftleg = x.LeftFootMuscleVal,
                    musclekgrightleg = x.RightFootMuscleVal,
                    musclekgleftarm = x.LeftHandMuscleVal,
                    musclekgrightarm = x.RightHandMuscleVal,
                    bodyfatraterunk = x.BodyFat,
                    bodyfatrateleftleg = x.LeftFootFat,
                    bodyfatraterightleg = x.RightFootFat,
                    bodyfatrateleftarm = x.LeftHandFat,
                    bodyfatraterightarm = x.RightHandFat,
                    bodyfatkgtrunk = x.BodyFatVal,
                    bodyfatkgleftleg = x.LeftFootFatVal,
                    bodyfatkgrightleg = x.RightFootFatVal,
                    bodyfatkgleftarm = x.LeftHandFatVal,
                    bodyfatkgrightarm = x.RightHandFatVal,
                    idealweight = x.IdealWeight,
                    Id = x.Id
                })
                .Mapper((it, cache) =>
                {
                    if (!string.IsNullOrEmpty(it.leveljson))
                    {
                        var data = it.leveljson.ToObject<MeasureLevelDto>();
                        if (data != null)
                        {
                            it.SkeletalMuscleLevel = data.SkeletalMuscleLevel;
                            it.fatLevel = data.fatLevel;
                            it.fat_rLevel = data.fat_rLevel;
                            it.muscleLevel = data.muscleLevel;
                            it.waterLevel = data.waterLevel;
                            it.boneLevel = data.boneLevel;
                            it.kcalLevel = data.kcalLevel;
                            it.fat_wLevel = data.fat_wLevel;
                            it.visceralLevel = data.visceralLevel;
                            it.proteinLevel = data.proteinLevel;
                            it.bodyageLevel = data.bodyageLevel;
                            it.bmiLevel = data.bmiLevel;
                            it.musulevalLevel = data.musulevalLevel;
                            it.proteinvalLevel = data.proteinvalLevel;
                            it.sfrLevel = data.sfrLevel;
                            it.bodylevel = data.bodylevel;
                        }
                    }
                })
                .ToPageListAsync(param.page, param.pagesize, totalnum);
            var list = query.Adapt<List<BodyMeasureHisListDto>>();
            return new PageParms<BodyMeasureHisListDto>
            {
                page = param.page,
                Items = list,
                totalnum = totalnum,
                limit = param.pagesize
            };
        }

        /// <summary>
        /// 两次测量记录对比
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<ResultInfo> ResultDiff(ResultDiffC2SDto data)
        {
            var firstresult = await dbClient.Queryable<YB_nResult>()
                .Select(x => new YB_nResult
                {
                    Imp = x.Imp,
                    LeftArmImp = x.LeftArmImp,
                    LeftLegImp = x.LeftLegImp,
                    RightArmImp = x.RightArmImp,
                    RightLegImp = x.RightLegImp,
                    Weight = x.Weight
                })
                .FirstAsync(x => x.Id == data.FirstId);
            if (firstresult == null)
            {
                return new ResultInfo(ResultState.FAIL, "第一条测量记录未找到");
            }
            var secondresult = await dbClient.Queryable<YB_nResult>()
                 .Select(x => new YB_nResult
                 {
                     Imp = x.Imp,
                     LeftArmImp = x.LeftArmImp,
                     LeftLegImp = x.LeftLegImp,
                     RightArmImp = x.RightArmImp,
                     RightLegImp = x.RightLegImp,
                     Weight = x.Weight
                 })
                .FirstAsync(x => x.Id == data.SecondId);
            if (secondresult == null)
            {
                return new ResultInfo(ResultState.FAIL, "第二条测量记录未找到");
            }
            var firstres = await dbClient.Queryable<YB_nMeasureResult>()
                .Select(x => new YB_nMeasureResult
                {
                    Height = x.Height,
                    Sex = x.Sex,
                    Age = x.Age,
                    createtime = x.createtime,
                    DevType = x.DevType,
                    fat_r = x.fat_r,
                    sfr = x.sfr,
                    SfrVal = x.SfrVal,
                    SkeletalMuscle = x.SkeletalMuscle,
                    bmi = x.bmi,
                    body = x.body,
                    bodyage = x.bodyage,
                    bone = x.bone,
                    cmi = x.cmi,
                    fatlevel = x.fatlevel,
                    fat_w = x.fat_w,
                    kcal = x.kcal,
                    lbm = x.lbm,
                    visceral = x.visceral,
                    water = x.water,
                    muscle = x.muscle,
                    protein = x.protein
                })
                .FirstAsync(x => x.Id == data.FirstId);
            var secondres = await dbClient.Queryable<YB_nMeasureResult>()
               .Select(x => new YB_nMeasureResult
               {
                   Height = x.Height,
                   Sex = x.Sex,
                   Age = x.Age,
                   createtime = x.createtime,
                   DevType = x.DevType,
                   fat_r = x.fat_r,
                   sfr = x.sfr,
                   SfrVal = x.SfrVal,
                   SkeletalMuscle = x.SkeletalMuscle,
                   bmi = x.bmi,
                   body = x.body,
                   bodyage = x.bodyage,
                   bone = x.bone,
                   cmi = x.cmi,
                   fatlevel = x.fatlevel,
                   fat_w = x.fat_w,
                   kcal = x.kcal,
                   lbm = x.lbm,
                   visceral = x.visceral,
                   water = x.water,
                   muscle = x.muscle,
                   protein = x.protein
               })
               .FirstAsync(x => x.Id == data.SecondId);
            var family = await dbClient.Queryable<YB_Family>().FirstAsync(x => x.Id == data.FamilyId);
            string headimg = family.HeadImg;
            if (!string.IsNullOrEmpty(headimg))
            {
                headimg = headimg.ToLower().StartsWith("http") ? headimg : $"{APICDNURL}{headimg}";
            }
            else
            {
                headimg = DefaultService.HeadImg(family.Sex, family.Type);
            }
            UserMeasureModel firstdata = null;
            //如果是八电极协议
            if (await dbClient.Queryable<YB_DeviceType>().AnyAsync(x => x.ProType == DeviceProType.WT8 && firstres.DevType == x.Code))
            {
                var bodydata = await _bodyFatHelperService.CalcBody120FatAsync(firstresult.Weight, firstres.Height, firstres.Age, firstres.Sex, firstresult.LeftArmImp, firstresult.RightArmImp, firstresult.LeftLegImp, firstresult.RightLegImp, firstresult.Imp);
                firstdata = new UserMeasureModel
                {
                    bmi = firstres.bmi,
                    bmiLevel = bodydata.bmiLevel,
                    sfr = firstres.sfr,
                    sfrLevel = bodydata.sfrLevel,
                    muscleLevel = bodydata.muscleLevel,
                    muscle = firstres.muscle,
                    muscleval = bodydata.muscleval,
                    body = firstres.body,
                    fatLevel = bodydata.fatLevel,
                    fat_r = firstres.fat_r,
                    fat_rLevel = bodydata.fat_rLevel,
                    fat_w = firstres.fat_w,
                    bodyage = firstres.bodyage,
                    bone = firstres.bone,
                    cmi = firstres.cmi,
                    height = bodydata.height,
                    kcal = firstres.kcal,
                    lbm = firstres.lbm,
                    protein = firstres.protein,
                    visceral = firstres.visceral,
                    standardWeight = firstres.IdealWeight.ToString(),
                    bodylevel = firstres.body,
                    bodyageLevel = bodydata.bodyageLevel,
                    boneLevel = bodydata.boneLevel,
                    fat_wLevel = bodydata.fat_wLevel,
                    kcalLevel = bodydata.kcalLevel,
                    musulevalLevel = bodydata.musulevalLevel,
                    proteinLevel = bodydata.proteinLevel,
                    proteinval = firstres.proteinval,
                    proteinvalLevel = bodydata.proteinvalLevel,
                    visceralLevel = bodydata.visceralLevel,
                    water = firstres.water,
                    waterLevel = bodydata.waterLevel,
                    weight = bodydata.weight,
                    sfrval = firstres.SfrVal,
                    skeletalmuscle = firstres.SkeletalMuscle,
                    skeletalmuscleLevel = bodydata.SkeletalMuscleLevel
                };
            }
            else
            {
                firstdata = _bodyFatHelperService.CalcBodyFat(firstresult.Weight.ToDouble(), firstres.Height.ToDouble(), firstres.Age, firstresult.Imp.ToInt(), firstres.Sex);
            }
            UserMeasureModel seconddata = null;
            //如果是八电极协议
            if (await dbClient.Queryable<YB_DeviceType>().AnyAsync(x => x.ProType == DeviceProType.WT8 && secondres.DevType == x.Code))
            {
                var bodydata = await _bodyFatHelperService.CalcBody120FatAsync(secondresult.Weight, secondres.Height, secondres.Age, secondres.Sex, secondresult.LeftArmImp, secondresult.RightArmImp, secondresult.LeftLegImp, secondresult.RightLegImp, secondresult.Imp);
                seconddata = new UserMeasureModel
                {
                    bmi = secondres.bmi,
                    bmiLevel = bodydata.bmiLevel,
                    sfr = secondres.sfr,
                    sfrLevel = bodydata.sfrLevel,
                    muscleLevel = bodydata.muscleLevel,
                    muscle = secondres.muscle,
                    muscleval = bodydata.muscleval,
                    body = secondres.body,
                    fatLevel = bodydata.fatLevel,
                    fat_r = secondres.fat_r,
                    fat_rLevel = bodydata.fat_rLevel,
                    fat_w = secondres.fat_w,
                    bodyage = secondres.bodyage,
                    bone = secondres.bone,
                    cmi = secondres.cmi,
                    height = bodydata.height,
                    kcal = secondres.kcal,
                    lbm = secondres.lbm,
                    protein = secondres.protein,
                    visceral = secondres.visceral,
                    standardWeight = secondres.IdealWeight.ToString(),
                    bodylevel = secondres.body,
                    bodyageLevel = bodydata.bodyageLevel,
                    boneLevel = bodydata.boneLevel,
                    fat_wLevel = bodydata.fat_wLevel,
                    kcalLevel = bodydata.kcalLevel,
                    musulevalLevel = bodydata.musulevalLevel,
                    proteinLevel = bodydata.proteinLevel,
                    proteinval = secondres.proteinval,
                    proteinvalLevel = bodydata.proteinvalLevel,
                    visceralLevel = bodydata.visceralLevel,
                    water = secondres.water,
                    waterLevel = bodydata.waterLevel,
                    weight = bodydata.weight,
                    sfrval = secondres.SfrVal,
                    skeletalmuscle = secondres.SkeletalMuscle,
                    skeletalmuscleLevel = bodydata.SkeletalMuscleLevel
                };
            }
            else
            {
                seconddata = _bodyFatHelperService.CalcBodyFat(secondresult.Weight.ToDouble(), secondres.Height.ToDouble(), secondres.Age, secondresult.Imp.ToInt(), (GenderType)secondres.Sex);
            }
            int day = (secondres.createtime.Date - firstres.createtime.Date).TotalDays.ToInt();
            var fdata = firstdata.Adapt<ResultDiffItemS2SDto>();
            var sdata = seconddata.Adapt<ResultDiffItemS2SDto>();
            ResultDiffS2CDto returndata = null;
            if (firstres.createtime > secondres.createtime)
            {
                returndata = new ResultDiffS2CDto
                {
                    Day = Math.Abs(day),
                    WeightDiff = fdata.weight - sdata.weight,
                    Fat_WDiff = fdata.fat_w - sdata.fat_w,
                    FirstResult = sdata,
                    SecondResult = fdata,
                    HeadImg = headimg,
                    NickName = family.Name,
                    Sex = family.Sex,
                    Time = $"{secondres.createtime.ToString("yyyy/MM/dd")}-{firstres.createtime.ToString("yyyy/MM/dd")}"
                };
            }
            else
            {
                returndata = new ResultDiffS2CDto
                {
                    Day = Math.Abs(day),
                    WeightDiff = sdata.weight - fdata.weight,
                    Fat_WDiff = sdata.fat_w - fdata.fat_w,
                    FirstResult = fdata,
                    SecondResult = sdata,
                    HeadImg = headimg,
                    NickName = family.Name,
                    Sex = family.Sex,
                    Time = $"{firstres.createtime.ToString("yyyy/MM/dd")}-{secondres.createtime.ToString("yyyy/MM/dd")}"
                };
            }
            return new ResultInfo(ResultState.SUCCESS, "success", returndata);
        }

        /// <summary>
        /// 添加测量记录,针对八电极
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<ResultInfo> InsertBodyMeasureAsync(MeasureBodySubmitC2SDto data)
        {
            //检查家庭成员是否存在
            var family = await dbClient.Queryable<YB_Family>().FirstAsync(x => x.Id == data.familyid);
            if (family == null)
            {
                return new ResultInfo(ResultState.FAIL, "家庭成员未找到");
            }
            //检查设备是否存在
            var device = await dbClient.Queryable<YB_Device>().FirstAsync(x => x.Ecode == data.ecode);
            if (device == null)
            {
                return new ResultInfo(ResultState.DEVNOTFOUND, "设备未找到,请到管理端进行激活");
            }
            if (device.Status != DeviceStatus.Run)
            {
                return new ResultInfo(ResultState.DEVNOTFOUND, "设备还未激活,请先激活");
            }
            decimal weight = AnalyWeight(data.weight);
            decimal height = AnalyHeight(data.height);
            await InsertResultAsync(new InsertResultC2SDto
            {
                DevId = device.Id,
                SourceType = 1,
                ecode = device.Ecode,
                familyid = family.Id,
                height = height,
                imp = data.imp,
                IsUserTake = true,
                UserId = authInfo.UserId,
                weight = weight,
                LeftArmImp = data.LeftHandImp,
                LeftLegImp = data.LeftFootImp,
                RightArmImp = data.RightHandImp,
                RightLegImp = data.RightFootImp,
                CreateTime = DateTime.Now,
                fansid = null,
                orderid = null,
                publicid = "",
                ResultId = Guid.Empty
            }, device, family);
            return new ResultInfo(ResultState.SUCCESS, "测量成功");
        }

        /// <summary>
        /// 添加测量记录,针对八电极,不激活
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<ResultInfo> InsertBodyMeasureNoActiveAsync(MeasureBodySubmitC2SDto data)
        {
            //检查家庭成员是否存在
            var family = await dbClient.Queryable<YB_Family>().FirstAsync(x => x.Id == data.familyid);
            if (family == null)
            {
                return new ResultInfo(ResultState.FAIL, "家庭成员未找到");
            }
            //检查设备是否存在,固定ID为29107,不激活
            var did = data.Type == 2? 29108 : 29107;
            var device = await dbClient.Queryable<YB_Device>().FirstAsync(x => x.Id == did);
            if (device == null)
            {
                return new ResultInfo(ResultState.DEVNOTFOUND, "设备未找到,请到管理端进行激活");
            }
            if (device.Status != DeviceStatus.Run)
            {
                return new ResultInfo(ResultState.DEVNOTFOUND, "设备还未激活,请先激活");
            }
            decimal weight = AnalyWeight(data.weight);
            decimal height = AnalyHeight(data.height);
            await InsertResultAsync(new InsertResultC2SDto
            {
                DevId = device.Id,
                SourceType = 1,
                ecode = device.Ecode,
                familyid = family.Id,
                height = height,
                imp = data.imp,
                IsUserTake = true,
                UserId = authInfo.UserId,
                weight = weight,
                LeftArmImp = data.LeftHandImp,
                LeftLegImp = data.LeftFootImp,
                RightArmImp = data.RightHandImp,
                RightLegImp = data.RightFootImp,
                CreateTime = DateTime.Now,
                fansid = null,
                orderid = null,
                publicid = "",
                ResultId = Guid.Empty
            }, device, family);
            return new ResultInfo(ResultState.SUCCESS, "测量成功");
        }

        /// <summary>
        /// 删除测量记录
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<ResultInfo> DeleteAsync(DeleteResultC2SDto data)
        {
            var result = await dbClient.Queryable<YB_nUserResult>().FirstAsync(x => x.Id == data.Id);
            if (result == null)
            {
                return new ResultInfo(ResultState.FAIL, "记录未找到");
            }
            if (await dbClient.Queryable<YB_nUserResult>().CountAsync(x => x.FamilyId == result.FamilyId && x.Status == 1) == 1)
            {
                return new ResultInfo(ResultState.FAIL, "记录就剩一条了,无法继续删除");
            }
            //删除记录队列
            await _capBus.PublishAsync("system.service.deleteuserresult", new DeleteUserDataS2SDto
            {
                UserId = result.UserId,
                FamilyId = result.FamilyId,
                ResultId = result.Id,
                DevType = result.DevType,
                time = result.CreateTime
            });
            return new ResultInfo(ResultState.SUCCESS, "记录删除成功");
        }

        /// <summary>
        /// 测量记录详情
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultInfo> DetailAsync(ResultDetailC2SDto input)
        {
            var measureresult = await dbClient.Queryable<YB_nMeasureResult>().Where(x => x.Id == input.Id).Select(x => new YB_nMeasureResult
            {
                Month = x.Month,
                Age = x.Age,
                Weight = x.Weight,
                Height = x.Height,
                Sex = x.Sex,
                fat_r = x.fat_r,
                sfr = x.sfr,
                SfrVal = x.SfrVal,
                SkeletalMuscle = x.SkeletalMuscle,
                bmi = x.bmi,
                body = x.body,
                bodyage = x.bodyage,
                bone = x.bone,
                cmi = x.cmi,
                fatlevel = x.fatlevel,
                fat_w = x.fat_w,
                kcal = x.kcal,
                lbm = x.lbm,
                visceral = x.visceral,
                water = x.water,
                muscle = x.muscle,
                protein = x.protein
            }).FirstAsync();
            if (measureresult == null)
            {
                return new ResultInfo(ResultState.FAIL, "测量记录未找到");
            }
            var result = await dbClient.Queryable<YB_nResult>().Where(x => x.Id == input.Id).Select(x => new YB_nResult
            {
                Imp = x.Imp,
                LeftArmImp = x.LeftArmImp,
                RightArmImp = x.RightArmImp,
                LeftLegImp = x.LeftLegImp,
                RightLegImp = x.RightLegImp
            }).FirstAsync();
            var sex = measureresult.Sex;
            var age = measureresult.Age;
            var weight = measureresult.Weight;
            var height = measureresult.Height;
            var data = await _bodyFatHelperService.CalcBody120FatAsync(weight, height, age, sex, result.LeftArmImp, result.RightArmImp, result.LeftLegImp, result.RightLegImp, result.Imp);
            if (data == null)
            {
                return new ResultInfo(ResultState.NORESULT, "测量结果计算失败");
            }
            data.fat_r = measureresult.fat_r;
            data.sfr = measureresult.sfr;
            data.sfrval = measureresult.SfrVal;
            data.SkeletalMuscle = measureresult.SkeletalMuscle;
            data.bmi = measureresult.bmi;
            data.body = measureresult.body;
            data.bodyage = measureresult.bodyage;
            data.bone = measureresult.bone;
            data.cmi = measureresult.cmi;
            data.fatLevel = measureresult.fatlevel;
            data.fat_w = measureresult.fat_w;
            data.kcal = measureresult.kcal;
            data.lbm = measureresult.lbm;
            data.visceral = measureresult.visceral;
            data.water = measureresult.water;
            data.muscle = measureresult.muscle;
            data.protein = measureresult.protein;
            var returndata = data.Adapt<Body120MeausreS2CDto>();
            returndata.Age = age;
            returndata.Sex = sex;
            var currentdata = data.Adapt<UserMeasureModel>();
            var list = _userService.HisList(sex, age, weight, currentdata);
            if (list != null)
            {
                list.Add(new MeasureInfoItem
                {
                    name = "skeletalmuscle",
                    slist = _bodyFatHelperService.skeletalmusclekg_val(sex, age, returndata.SkeletalMuscle),
                    Color = _bodyFatHelperService.GetLevelColor(returndata.SkeletalMuscleLevel)
                });
            }
            returndata.list = list;
            return new ResultInfo(ResultState.SUCCESS, "success", returndata);
        }
    }
}