using Furion;
using Furion.DependencyInjection;
using Furion.DistributedIDGenerator;
using Mapster;
using Nirvana.Common;
using Nirvana.Common.ApiBase;
using SqlSugar;
using System;
using System.Linq;
using System.Threading.Tasks;
using YBDevice.Entity;
using YBDevice.Entity.DataModel.ThirdOpen;

namespace YBDevice.NApi.Application.ThirdClient.Family
{
    /// <summary>
    /// 家庭成员管理
    /// </summary>
    public class FamilyService : IOpenFamilyService, ITransient
    {
        private readonly ISqlSugarRepository<T_Family> repository;
        private readonly SqlSugarClient dbClient;
        private static string APICDNURL = App.Configuration["APICDNURL"];//API图片CDN地址
        public FamilyService(ISqlSugarRepository<T_Family> sqlSugarRepository)
        {
            repository = sqlSugarRepository;
            dbClient = repository.Context;
        }
        /// <summary>
        /// 家庭成员列表
        /// </summary>
        /// <returns></returns>
        public async Task<ResultInfo> GetListAsync()
        {
            var CurrentUser = AuthUserInfoService.GetUserInfo();
            var list = await dbClient.Queryable<T_Family>().Where(x => x.UserId == CurrentUser.UserId)
                .OrderBy(x => x.CreateTime, OrderByType.Desc)
                .Select(x => new FamilyInfoS2CDto
                {
                    Id = x.Id,
                    Name = x.Name,
                    HeadImg = x.HeadImg
                })
                .Mapper((it, cache) =>
                {
                    var alldata = cache.Get(list =>
                    {
                        var ids = list.Select(x => x.Id).ToList();
                        return dbClient.Queryable<T_FamilyData>().Where(x => ids.Contains(x.Id)).ToList();
                    });
                    var data = alldata.FirstOrDefault(x => x.Id == it.Id);
                    it.Sex = data != null ? data.Sex : 0;
                    it.Birthday = data != null ? data.Brithday : null;
                    it.Age = data != null && data.Brithday.HasValue ? data.Brithday.Value.ToAAge() : "";
                    it.HeadImg = string.IsNullOrEmpty(it.HeadImg) ? HeadImg((GenderType)it.Sex, 1) : it.HeadImg;
                })
                .ToListAsync();
            return new ResultInfo(ResultState.SUCCESS, "success", list);
        }
        /// <summary>
        /// 修改家庭成员资料
        /// </summary>
        /// <returns></returns>
        public async Task<ResultInfo> SubmitAsync(FamilySubmitC2SDto data)
        {
            var CurrentUser = AuthUserInfoService.GetUserInfo();
            if (data.Id.HasValue && data.Id.Value != Guid.Empty)
            {
                await dbClient.Updateable<T_Family>().SetColumns(x => new T_Family
                {
                    Name = data.Name
                }).Where(x => x.Id == data.Id.Value).ExecuteCommandAsync();
                if (await dbClient.Queryable<T_FamilyData>().AnyAsync(x => x.Id == data.Id.Value))
                {
                    await dbClient.Updateable<T_FamilyData>().SetColumns(x => new T_FamilyData
                    {
                        Sex = data.Sex,
                        Brithday = data.Birthday,
                        Height = data.Height,
                        Weight = data.Weight
                    }).Where(x => x.Id == data.Id.Value).ExecuteCommandAsync();
                }
                else
                {
                    await dbClient.Insertable(new T_FamilyData
                    {
                        Brithday = data.Birthday,
                        Sex = data.Sex,
                        Id = data.Id.Value,
                        Height = data.Height,
                        LastResultId = null,
                        LastResultTime = null,
                        Weight = data.Weight
                    }).ExecuteCommandAsync();
                }
                return new ResultInfo(ResultState.SUCCESS, "资料修改成功");
            }
            else
            {
                var family = data.Adapt<T_Family>();
                family.Id = IDGen.NextID();
                family.HeadImg = "";
                family.UserId = CurrentUser.UserId;
                family.CreateTime = DateTime.Now;
                await dbClient.Insertable(family).ExecuteCommandAsync();

                await dbClient.Insertable(new T_FamilyData
                {
                    Brithday = data.Birthday,
                    Sex = data.Sex,
                    Id = family.Id,
                    Height = data.Height,
                    LastResultId = null,
                    LastResultTime = null,
                    Weight = data.Weight
                }).ExecuteCommandAsync();
                return new ResultInfo(ResultState.SUCCESS, "添加成功");
            }
        }

        /// <summary>
        /// 加载默认头像
        /// </summary>
        /// <param name="sex">性别,1-男,2-女</param>
        /// <param name="type">类型,1-成人,2-儿童</param>
        /// <returns></returns>
        public string HeadImg(GenderType sex, int type)
            => (sex, type) switch
            {
                _ when sex == GenderType.Male && type == 1 => $"{APICDNURL}/img/adult_male.png",
                _ when sex == GenderType.FeMale && type == 1 => $"{APICDNURL}/img/adult_female.png",
                _ when sex == GenderType.Male && type == 2 => $"{APICDNURL}/img/child_male.png",
                _ => $"{APICDNURL}/img/child_female.png"
            };
    }
}
