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 FamilyApp : BaseApp
    {
        /// <summary>
        /// 家庭成员列表
        /// </summary>
        /// <returns></returns>
        public async Task<ResultInfo> GetListAsync()
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var tempquery = dbClient.Queryable<YB_Family>()
                    .Where(x => x.UserId == authInfo.UserId && x.Status != -1);
                var result = await tempquery
                    .OrderBy(x => x.Createtime, OrderByType.Desc)
                    .Select(x => new FamilyListModel
                    {
                        Id = x.Id,
                        Birthday = x.Birthday,
                        HeadImg = x.HeadImg,
                        Height = x.Height,
                        IsSelf = x.IsSelf,
                        LastHeartTime = SqlFunc.ToString(x.LastHeartTime),
                        Name = x.Name,
                        Sex = x.Sex,
                        Type = x.Type,
                        Weight = x.Weight,
                        Age = x.Age
                    })
                    .Mapper((it, cache) =>
                    {
                        it.mAge = it.Birthday.TomAge();
                        if (!string.IsNullOrEmpty(it.HeadImg))
                        {
                           it.HeadImg=it.HeadImg.ToLower().StartsWith("http") ?it.HeadImg:$"{APICDNURL}{it.HeadImg}";
                        }
                        else
                        {
                            it.HeadImg = HeadImg(it.Sex, it.Type);
                        }
                        if (!string.IsNullOrEmpty(it.LastHeartTime))
                        {
                            it.LastHeartTime = it.LastHeartTime.ToYearDateTime();
                        }
                        else
                        {
                            it.LastHeartTime = "-";
                        }
                    })
                    .ToListAsync();
                return new ResultInfo(ResultState.SUCCESS, "success", result);
            }
        }
        /// <summary>
        /// 加载默认头像
        /// </summary>
        /// <param name="sex">性别,1-男,2-女</param>
        /// <param name="type">类型,1-成人,2-儿童</param>
        /// <returns></returns>
        public string HeadImg(int sex, int type)
            => (sex, type) switch
            {
                _ when sex == 1 && type == 1=>$"{APICDNURL}/img/adult_male.png",
                _ when sex == 2 && type == 1=> $"{APICDNURL}/img/adult_female.png",
                _ when sex == 1 && type == 2 => $"{APICDNURL}/img/child_male.png",
                _=> $"{APICDNURL}/img/child_female.png"
            };

        /// <summary>
        /// 家庭成员信息修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ResultInfo> SubmitAsync(FamilySubmitModel model)
        {
            if (string.IsNullOrEmpty(model.name))
            {
                return new ResultInfo(ResultState.FAIL, "名称不可为空");
            }
            if (model.height <= 50)
            {
                return new ResultInfo(ResultState.FAIL, "身高不可小于50厘米");
            }
            if (model.birthday >= DateTime.Now.Date)
            {
                return new ResultInfo(ResultState.FAIL, "出生年月不可大于当前日期");
            }
            int age = model.birthday.ToAge();
            //年龄不可超过100岁
            if (age >= 100)
            {
                return new ResultInfo(ResultState.FAIL, "出生年月过大");
            }
            //儿童模式只支持14岁及以下的
            if(model.type == 2 && age > 14)
            {
                return new ResultInfo(ResultState.FAIL, "儿童年龄只限14岁以下");
            }
            model.headimg = model.headimg.ToStr();
            using (var dbClient = ReadDbContext.GetInstance())
            {
                if (model.id > 0)
                {
                    if (!string.IsNullOrEmpty(model.headimg))
                    {
                        await dbClient.Updateable<YB_Family>().SetColumns(x => new YB_Family
                        {
                            Age = age,
                            Sex = model.sex,
                            Birthday = model.birthday,
                            Height = model.height,
                            Name = model.name,
                            Type = model.type,
                            HeadImg = model.headimg
                        }).Where(x => x.Id == model.id).ExecuteCommandAsync();
                    }
                    else
                    {
                        await dbClient.Updateable<YB_Family>().SetColumns(x => new YB_Family
                        {
                            Age = age,
                            Sex = model.sex,
                            Birthday = model.birthday,
                            Height = model.height,
                            Name = model.name,
                            Type = model.type
                        }).Where(x => x.Id == model.id).ExecuteCommandAsync();
                    }
                    return new ResultInfo(ResultState.SUCCESS, "资料更新成功");
                }
                else
                {
                   int familyid= await dbClient.Insertable<YB_Family>(new YB_Family
                    {
                        Age = age,
                        Sex = model.sex,
                        Birthday = model.birthday,
                        Height = model.height,
                        Name = model.name,
                        Type = model.type,
                        Status = 1,
                        IsSelf = 0,
                        Createtime = DateTime.Now,
                        UserId = authInfo.UserId,
                        Weight = 0,
                        LastHeartTime = null,
                        HeadImg = model.headimg
                    }).ExecuteReturnIdentityAsync();
                    //增加一条家庭成员数据记录
                    if(!await dbClient.Queryable<YB_FamilyData>().AnyAsync(x=>x.FamilyId == familyid))
                    {
                        await dbClient.Insertable<YB_FamilyData>(new YB_FamilyData
                        {
                            FamilyId = familyid,
                            AdultHeight = 0,
                            CreateTime = DateTime.Now,
                            DadHeight = 0,
                            HalfYearHeight = 0,
                            MomHeight = 0,
                            YearHeight = 0
                        }).ExecuteCommandAsync();
                    }
                    return new ResultInfo(ResultState.SUCCESS, "成员添加成功");
                }
            }
        }
        /// <summary>
        /// 家庭成员删除
        /// </summary>
        /// <param name="id">家庭成员ID</param>
        /// <returns></returns>
        public async Task<ResultInfo> DeleteAsync(int id)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                if (!await dbClient.Queryable<YB_Family>().AnyAsync(x => x.Id == id))
                {
                    return new ResultInfo(ResultState.FAIL, "家庭成员未找到");
                }
                if (await dbClient.Queryable<YB_Family>().AnyAsync(x => x.Id == id && x.IsSelf == 1))
                {
                    return new ResultInfo(ResultState.FAIL, "不能够删除自己");
                }
                await dbClient.Updateable<YB_Family>().SetColumns(x => new YB_Family
                {
                    Status = -1
                }).Where(x => x.Id == id).ExecuteCommandAsync();
                return new ResultInfo(ResultState.SUCCESS, "删除成功");
            }
        }

        /// <summary>
        /// 家庭成员详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultInfo> DetailAsync(int id)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var data = await dbClient.Queryable<YB_Family>().FirstAsync(x => x.Id == id);
                if(data != null)
                {
                    if (string.IsNullOrEmpty(data.HeadImg))
                    {
                        data.HeadImg = HeadImg(data.Sex, data.Type);
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(data.HeadImg) && !data.HeadImg.ToLower().StartsWith("http"))
                        {
                            data.HeadImg = $"{APICDNURL}{data.HeadImg}";
                        }
                    }
                }
                return new ResultInfo(ResultState.SUCCESS, "success", new { 
                    Id=data.Id,
                    Age=data.Age,
                    Birthday=data.Birthday.ToString("yyyy-MM-dd"),
                    HeadImg= data.HeadImg,
                    Height = data.Height,
                    IsSelf = data.IsSelf,
                    Name = data.Name,
                    Sex = data.Sex,
                    Type = data.Type
                });
            }
        }
        /// <summary>
        /// 设置目标体重
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ResultInfo> SetTargetAsync(YB_FamilyTarget model)
        {
            if (model.time.Date < DateTime.Now.Date)
            {
                return new ResultInfo(ResultState.SUCCESS, "目标日期设置错误");
            }
            using (var dbClient = ReadDbContext.GetInstance())
            {
                if (await dbClient.Queryable<YB_FamilyTarget>().AnyAsync(x => x.familyid == model.familyid))
                {
                    await dbClient.Updateable<YB_FamilyTarget>().SetColumns(x => new YB_FamilyTarget
                    {
                        time = model.time,
                        weight = model.weight
                    }).Where(x => x.familyid == model.familyid).ExecuteCommandAsync();
                }
                else
                {
                    await dbClient.Insertable<YB_FamilyTarget>(model).ExecuteCommandAsync();
                }
                return new ResultInfo(ResultState.SUCCESS, "设置成功");
            }
        }
    }
}
