using Furion.DependencyInjection;
using Nirvana.Common;
using Nirvana.Common.ApiBase;
using Senparc.Weixin;
using Senparc.Weixin.Open.Containers;
using Senparc.Weixin.Open.WxaAPIs.Sns;
using Senparc.Weixin.WxOpen.Containers;
using Senparc.Weixin.WxOpen.Entities;
using Senparc.Weixin.WxOpen.Helpers;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YBDevice.Core;
using YBDevice.Entity;

namespace YBDevice.NApi.Application.UserInfo
{
    /// <summary>
    /// 小程序管理
    /// </summary>
    public class WxOpenService : BaseService, IWxOpenService, ITransient
    {
        public static readonly string Component_Token = Senparc.Weixin.Config.SenparcWeixinSetting.Component_Token;
        public static readonly string Component_EncodingAESKey = Senparc.Weixin.Config.SenparcWeixinSetting.Component_EncodingAESKey;
        public static readonly string Component_Appid = Senparc.Weixin.Config.SenparcWeixinSetting.Component_Appid;
        public static readonly string Component_Secret = Senparc.Weixin.Config.SenparcWeixinSetting.Component_Secret;
        private readonly ISqlSugarRepository<YB_OfficlaAccount> repository;
        private readonly SqlSugarClient dbClient;
        public WxOpenService(ISqlSugarRepository<YB_OfficlaAccount> sqlSugarRepository)

        {
            repository = sqlSugarRepository;
            dbClient = repository.Context;
        }
        /// <summary>
        /// 检查登录状态
        /// </summary>
        /// <param name="sessionId"></param>
        /// <returns></returns>
        public async Task<ResultInfo> CheckLoginAsync(string sessionId)
        {
            var sessionBag = await SessionContainer.GetSessionAsync(sessionId);
            if (sessionBag == null)
            {
                return new ResultInfo(ResultState.FAIL, "sessionId已失效");
            }
            var user = await dbClient.Queryable<YB_UserWX>().Where(x => x.openid == sessionBag.OpenId).FirstAsync();
            if (user == null)
            {
                return new ResultInfo(ResultState.FAIL, "此微信还未绑定");
            }
            if (!await dbClient.Queryable<YB_RegUser>().AnyAsync(x => x.Id == user.UserId))
            {
                return new ResultInfo(ResultState.FAIL, "用户未找到");
            }
            var token = Token(new WebApiOperaModel
            {
                UserId = user.UserId
            });
            return new ResultInfo(ResultState.SUCCESS, "登录成功", token);
        }
        /// <summary>
        /// 检查登录状态是否已失效
        /// </summary>
        /// <param name="sessionId"></param>
        /// <returns></returns>
        public async Task<ResultInfo> CheckStatusAsync(string sessionId)
        {
            var sessionBag = await SessionContainer.GetSessionAsync(sessionId);
            if (sessionBag == null)
            {
                return new ResultInfo(ResultState.FAIL, "登录已失效");
            }
            return new ResultInfo(ResultState.SUCCESS, "success");
        }
        /// <summary>
        /// 解密用户资料,如果未注册则自动进行注册,否则更新资料
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ResultInfo> DecryptDataAsync(WxOpenDecryptSubmitModel model)
        {
            var sessionbage = await SessionContainer.GetSessionAsync(model.sessionId);
            if (sessionbage == null)
            {
                return new ResultInfo(ResultState.FAIL, "登录信息已过期");
            }
            DecodeEntityBase decodedEntity = null;
            DecodedUserInfo userinfo = null;
            userinfo = EncryptHelper.DecodeUserInfoBySessionId(
                       model.sessionId,
                       model.encryptedData, model.iv);
            //记录日志
            //_loggerService.AddLogger($"解密后的用户资料:{userinfo.ToJson()}");
            decodedEntity = userinfo;
            //检验水印
            var checkWartmark = false;
            if (decodedEntity != null)
            {
                checkWartmark = decodedEntity.CheckWatermark(model.appid);
            }
            if (!checkWartmark)
            {
                return new ResultInfo(ResultState.FAIL, "水印验证不通过");
            }
            //检查此openid是否已绑定用户
            if (!await dbClient.Queryable<YB_UserWX>().AnyAsync(x => x.openid == sessionbage.OpenId))
            {
                //未注册自动注册
                var userid = await dbClient.Insertable(new YB_RegUser
                {
                    Secret = "",
                    Status = 1,
                    CreateTime = DateTime.Now,
                    Headimg = userinfo.avatarUrl.ToStr(),
                    LastVisitIP = Net.Ip,
                    LastVisitTime = DateTime.Now,
                    Name = userinfo.nickName.ToStr(),
                    Password = "",
                    Phone = "",
                    City = userinfo.city.ToStr(),
                    Country = userinfo.country.ToStr(),
                    Gender = userinfo.gender,
                    Province = userinfo.province.ToStr(),
                    UnionId = userinfo.unionId.ToStr()
                }).ExecuteReturnIdentityAsync();
                //增加一条用户数据记录
                await dbClient.Insertable(new YB_UserRealData
                {
                    UserId = userid,
                    TopStep = 0,
                    TopStepTime = 0
                }).ExecuteCommandAsync();

                //增加微信绑定记录
                await dbClient.Insertable(new YB_UserWX
                {
                    createtime = DateTime.Now,
                    openid = sessionbage.OpenId.ToStr(),
                    unionid = sessionbage.UnionId.ToStr(),
                    UserId = userid
                }).ExecuteCommandAsync();
                //增加一条为自己的家庭成员
                var birthday = DateTime.Now.AddYears(-18).Date;
                var family = new YB_Family
                {
                    Type = (int)FamilyType.Adult,
                    Age = 18,
                    Birthday = birthday,
                    Sex = userinfo.gender,
                    IsSelf = 1,
                    Status = 1,
                    Createtime = DateTime.Now,
                    Height = 175,
                    Name = userinfo.nickName,
                    UserId = userid,
                    Weight = 0,
                    HeadImg = userinfo.avatarUrl.ToStr()
                };
                int familyid = await dbClient.Insertable(family).ExecuteReturnIdentityAsync();
                //增加一条家庭成员数据记录
                await dbClient.Insertable(new YB_FamilyData
                {
                    FamilyId = familyid,
                    AdultHeight = 0,
                    CreateTime = DateTime.Now,
                    DadHeight = 0,
                    HalfYearHeight = 0,
                    MomHeight = 0,
                    YearHeight = 0
                }).ExecuteCommandAsync();
                //更新或者新增统计数据
                if (await dbClient.Queryable<YB_Combined>().AnyAsync(x => x.Id == 1))
                {
                    await dbClient.Updateable<YB_Combined>().SetColumns(x => new YB_Combined
                    {
                        TodayRegCnt = x.TodayRegCnt + 1,
                        TotalRegCnt = x.TotalRegCnt + 1
                    }).Where(x => x.Id == 1).ExecuteCommandAsync();
                }
                else
                {
                    await dbClient.Insertable(new YB_Combined
                    {
                        Id = 1,
                        TodayDevCnt = 0,
                        TotalDevCnt = 0,
                        TodayIncome = 0,
                        TodayRegCnt = 1,
                        TodayResultCnt = 0,
                        TotalIncome = 0,
                        TotalRegCnt = 1,
                        TotalResultCnt = 0
                    }).ExecuteCommandAsync();
                }
                var token = Token(new WebApiOperaModel
                {
                    UserId = userid
                });
                return new ResultInfo(ResultState.SUCCESS, "注册成功", new
                {
                    token = token,
                    sessionid = model.sessionId
                });
            }
            else
            {
                var userwx = await dbClient.Queryable<YB_UserWX>().Where(x => x.openid == sessionbage.OpenId).OrderBy(x => x.createtime, OrderByType.Desc).FirstAsync();
                if (!await dbClient.Queryable<YB_RegUser>().Where(x => x.Id == userwx.UserId).AnyAsync())
                {
                    return new ResultInfo(ResultState.FAIL, "用户未找到");
                }
                //更新登录时间,以及最新的资料
                await dbClient.Updateable<YB_RegUser>().SetColumns(x => new YB_RegUser
                {
                    LastVisitIP = Net.Ip,
                    LastVisitTime = DateTime.Now,
                    Country = userinfo.country.ToStr(),
                    Gender = userinfo.gender,
                    Province = userinfo.province.ToStr(),
                    City = userinfo.city.ToStr(),
                    Headimg = userinfo.avatarUrl.ToStr(),
                    UnionId = userinfo.unionId.ToStr(),
                    Name = userinfo.nickName
                })
                    .Where(x => x.Id == userwx.UserId)
                    .ExecuteCommandAsync();
                //更新关联的家庭成员资料
                await dbClient.Updateable<YB_Family>().SetColumns(x => new YB_Family
                {
                    HeadImg = userinfo.avatarUrl.ToStr(),
                    Name = userinfo.nickName.ToStr()
                }).Where(x => x.IsSelf == 1 && x.UserId == userwx.UserId).ExecuteCommandAsync();
                var token = Token(new WebApiOperaModel
                {
                    UserId = userwx.UserId
                });
                return new ResultInfo(ResultState.SUCCESS, "登录成功", new
                {
                    token = token,
                    sessionid = model.sessionId
                });
            }
        }
        /// <summary>
        /// 手机号授权,如果未注册会自动进行注册
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ResultInfo> DecryptPhoneAsync(WxOpenDecryptSubmitModel model)
        {
            //_loggerService.AddLogger($"手机号授权登录数据:{model.ToJson()}");
            var sessionBag = await SessionContainer.GetSessionAsync(model.sessionId);
            if (sessionBag == null)
            {
                return new ResultInfo(ResultState.FAIL, "sessionId未找到");
            }
            var phone = EncryptHelper.DecryptPhoneNumber(model.sessionId, model.encryptedData, model.iv);
            var user = await dbClient.Queryable<YB_RegUser>().Where(x => x.Phone == phone.purePhoneNumber).FirstAsync();
            //检查此手机号是否已注册
            if (user != null)
            {
                if (!await dbClient.Queryable<YB_UserWX>().AnyAsync(x => x.openid == sessionBag.OpenId && x.UserId == user.Id))
                {
                    await dbClient.Insertable(new YB_UserWX
                    {
                        openid = sessionBag.OpenId,
                        createtime = DateTime.Now,
                        unionid = sessionBag.UnionId.ToStr(),
                        UserId = user.Id
                    }).ExecuteCommandAsync();
                }
                //更新登录时间,以及最新的资料
                await dbClient.Updateable<YB_RegUser>().SetColumns(x => new YB_RegUser
                {
                    LastVisitIP = Net.Ip,
                    LastVisitTime = DateTime.Now
                })
                   .Where(x => x.Id == user.Id)
                   .ExecuteCommandAsync();
                //检测是否绑定了fansid
                Guid? fansid = user.FansId;
                if ((!fansid.HasValue || fansid.Value == Guid.Empty)
                    && model.fansid.HasValue && model.fansid.Value != Guid.Empty)
                {
                    YB_WXFans fansdata = await dbClient.Queryable<YB_WXFans>().FirstAsync(x => x.Id == model.fansid);
                    user.Headimg = fansdata.HeadImgUrl;
                    user.Name = fansdata.NickName;
                    user.Gender = fansdata.Sex;
                    //更新用户资料和绑定的fansid
                    await dbClient.Updateable<YB_RegUser>().SetColumns(x => new YB_RegUser
                    {
                        FansId = model.fansid,
                        Headimg = fansdata.HeadImgUrl,
                        Name = fansdata.NickName,
                        Gender = fansdata.Sex
                    }).Where(x => x.Id == user.Id).ExecuteCommandAsync();
                }
                var token = Token(new WebApiOperaModel
                {
                    UserId = user.Id
                });
                return new ResultInfo(ResultState.SUCCESS, "登录成功", new
                {
                    token = token,
                    sessionid = model.sessionId,
                    info = new
                    {
                        headimg = user.Headimg,
                        nickname = user.Name
                    }
                });
            }
            else
            {
                //自动进行注册
                user = new YB_RegUser
                {
                    Secret = "",
                    Status = 1,
                    CreateTime = DateTime.Now,
                    Headimg = "",
                    LastVisitIP = Net.Ip,
                    LastVisitTime = DateTime.Now,
                    Name = phone.purePhoneNumber,
                    Password = "",
                    Phone = phone.purePhoneNumber,
                    City = "",
                    Country = "",
                    Gender = 0,
                    Province = "",
                    UnionId = sessionBag.UnionId.ToStr(),
                    FansId = model.fansid
                };
                //检测是否绑定了fansid
                if (model.fansid.HasValue && model.fansid.Value != Guid.Empty)
                {
                    YB_WXFans fansdata = await dbClient.Queryable<YB_WXFans>().FirstAsync(x => x.Id == model.fansid);
                    user.Headimg = fansdata.HeadImgUrl;
                    user.Name = fansdata.NickName;
                    user.Gender = fansdata.Sex;
                }
                var userid = await dbClient.Insertable(user).ExecuteReturnIdentityAsync();
                //增加微信绑定记录
                await dbClient.Insertable(new YB_UserWX
                {
                    createtime = DateTime.Now,
                    openid = sessionBag.OpenId.ToStr(),
                    unionid = sessionBag.UnionId.ToStr(),
                    UserId = userid
                }).ExecuteCommandAsync();
                //增加一条用户数据记录
                await dbClient.Insertable(new YB_UserRealData
                {
                    UserId = userid,
                    TopStep = 0,
                    TopStepTime = 0
                }).ExecuteCommandAsync();
                //增加一条为自己的家庭成员
                var birthday = DateTime.Now.AddYears(-18).Date;
                var family = new YB_Family
                {
                    Type = (int)FamilyType.Adult,
                    Age = 18,
                    Birthday = birthday,
                    Sex = user.Gender,
                    IsSelf = 1,
                    Status = 1,
                    Createtime = DateTime.Now,
                    Height = 0,
                    Name = user.Name,
                    UserId = userid,
                    Weight = 0,
                    HeadImg = user.Headimg,
                    LastHeartTime = null
                };
                int familyid = await dbClient.Insertable(family).ExecuteReturnIdentityAsync();
                //增加一条家庭成员数据记录
                await dbClient.Insertable(new YB_FamilyData
                {
                    FamilyId = familyid,
                    AdultHeight = 0,
                    CreateTime = DateTime.Now,
                    DadHeight = 0,
                    HalfYearHeight = 0,
                    MomHeight = 0,
                    YearHeight = 0
                }).ExecuteCommandAsync();
                //更新或者新增统计数据
                if (await dbClient.Queryable<YB_Combined>().AnyAsync(x => x.Id == 1))
                {
                    await dbClient.Updateable<YB_Combined>().SetColumns(x => new YB_Combined
                    {
                        TodayRegCnt = x.TodayRegCnt + 1,
                        TotalRegCnt = x.TotalRegCnt + 1
                    }).Where(x => x.Id == 1).ExecuteCommandAsync();
                }
                else
                {
                    await dbClient.Insertable(new YB_Combined
                    {
                        Id = 1,
                        TodayDevCnt = 0,
                        TotalDevCnt = 0,
                        TodayIncome = 0,
                        TodayRegCnt = 1,
                        TodayResultCnt = 0,
                        TotalIncome = 0,
                        TotalRegCnt = 1,
                        TotalResultCnt = 0
                    }).ExecuteCommandAsync();
                }
                var token = Token(new WebApiOperaModel
                {
                    UserId = userid
                });
                return new ResultInfo(ResultState.SUCCESS, "注册成功", new
                {
                    token = token,
                    sessionid = model.sessionId,
                    info = new
                    {
                        headimg = user.Headimg,
                        nickname = user.Name
                    }
                });
            }
        }
        /// <summary>
        /// 解密用户资料
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ResultInfo> DecryptUserInfoAsync(WxOpenDecryptSubmitModel model)
        {
            var sessionbage = await SessionContainer.GetSessionAsync(model.sessionId);
            if (sessionbage == null)
            {
                return new ResultInfo(ResultState.FAIL, "登录信息已过期");
            }
            DecodeEntityBase decodedEntity = null;
            DecodedUserInfo userinfo = null;
            userinfo = EncryptHelper.DecodeUserInfoBySessionId(
                       model.sessionId,
                       model.encryptedData, model.iv);
            decodedEntity = userinfo;
            //检验水印
            var checkWartmark = false;
            if (decodedEntity != null)
            {
                checkWartmark = decodedEntity.CheckWatermark(model.appid);
            }
            if (!checkWartmark)
            {
                return new ResultInfo(ResultState.FAIL, "水印验证不通过");
            }
            //更新登录时间,以及最新的资料
            await dbClient.Updateable<YB_RegUser>().SetColumns(x => new YB_RegUser
            {
                Country = userinfo.country.ToStr(),
                Gender = userinfo.gender,
                Province = userinfo.province.ToStr(),
                City = userinfo.city.ToStr(),
                Headimg = userinfo.avatarUrl.ToStr(),
                UnionId = userinfo.unionId.ToStr(),
                Name = userinfo.nickName
            })
                .Where(x => x.Id == authInfo.UserId)
                .ExecuteCommandAsync();
            //更新关联的家庭成员资料
            await dbClient.Updateable<YB_Family>().SetColumns(x => new YB_Family
            {
                HeadImg = userinfo.avatarUrl.ToStr(),
                Name = userinfo.nickName.ToStr()
            }).Where(x => x.IsSelf == 1 && x.UserId == authInfo.UserId).ExecuteCommandAsync();
            var token = Token(new WebApiOperaModel
            {
                UserId = authInfo.UserId
            });
            return new ResultInfo(ResultState.SUCCESS, "资料更新成功");
        }

        /// <summary>
        /// 小程序登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ResultInfo> OnLoginAsync(WXOpenLoginSubmitModel model)
        {
            //检查小程序是否已授权
            if (!await dbClient.Queryable<YB_OfficlaAccount>().AnyAsync(x => x.authorizer_appid == model.appid && x.isauthorize == 1))
            {
                return new ResultInfo(ResultState.FAIL, "此小程序还未授权");
            }
            var accesstoken = await ComponentContainer.TryGetComponentAccessTokenAsync(Component_Appid, Component_Secret);
            //这里使用的是componentaccesstoken。不是小程序的token
            var jsonResult = await SnsApi.JsCode2JsonAsync(model.appid, Component_Appid, accesstoken, model.code);
           // _loggerService.AddLogger($"登录授权信息:{jsonResult.ToJson()}");
            if (jsonResult.errcode == ReturnCode.请求成功)
            {
                //得到openid,检查是否绑定有账号,如果有绑定则返回token,否则返回sessionid
                var openid = jsonResult.openid;
                TimeSpan val = new TimeSpan(1, 0, 0);//一个小时
                if (await dbClient.Queryable<YB_UserWX>().AnyAsync(x => x.openid == openid))
                {
                    var userwx = await dbClient.Queryable<YB_UserWX>().Where(x => x.openid == openid).FirstAsync();
                    //生成token
                    var token = Token(new WebApiOperaModel
                    {
                        UserId = userwx.UserId
                    });
                    //检测是否绑定了fansid
                    var user = await dbClient.Queryable<YB_RegUser>().FirstAsync(x => x.Id == userwx.UserId);
                    if(user != null)
                    {
                        Guid? fansid = user.FansId;
                        if ((!fansid.HasValue || fansid.Value == Guid.Empty)
                            && model.fansid.HasValue && model.fansid.Value != Guid.Empty)
                        {
                            YB_WXFans fansdata = await dbClient.Queryable<YB_WXFans>().FirstAsync(x => x.Id == model.fansid);
                            user.Headimg = fansdata.HeadImgUrl;
                            user.Name = fansdata.NickName;
                            await dbClient.Updateable<YB_RegUser>().SetColumns(x => new YB_RegUser
                            {
                                FansId = model.fansid,
                                Headimg = fansdata.HeadImgUrl,
                                Name = fansdata.NickName,
                                Gender = fansdata.Sex
                            }).Where(x => x.Id == userwx.UserId).ExecuteCommandAsync();
                        }
                        //刷新key
                        var sessionbag = await SessionContainer.UpdateSessionAsync(jsonResult.openid, jsonResult.openid, jsonResult.session_key, jsonResult.unionid, val);
                        return new ResultInfo(ResultState.SUCCESS, "登录成功", new
                        {
                            token = token,
                            sessionid = sessionbag.Key,
                            info = new
                            {
                                headimg = user.Headimg,
                                nickname = user.Name
                            }
                        });
                    }
                    else
                    {
                        //清理无效的信息
                        await dbClient.Deleteable<YB_UserWX>().Where(x => x.UserId == userwx.UserId).ExecuteCommandAsync();
                    }
                }
                //记录信息
                var sessionBag = await SessionContainer.UpdateSessionAsync(jsonResult.openid, jsonResult.openid, jsonResult.session_key, jsonResult.unionid, val);
                return new ResultInfo(ResultState.WXUNAUTHORITY, "success", new WxOpenLoginData
                {
                    sessionid = sessionBag.Key
                });
            }
            return new ResultInfo(ResultState.FAIL, jsonResult.errmsg);
        }
        /// <summary>
        /// 根据手机号进行注册
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ResultInfo> RegisterAsync(RegModel model)
        {
            var sessionBag = await SessionContainer.GetSessionAsync(model.sessionId);
            if (sessionBag == null)
            {
                return new ResultInfo(ResultState.FAIL, "sessionId未找到");
            }
            if (string.IsNullOrEmpty(model.phone))
            {
                return new ResultInfo(ResultState.FAIL, "手机号不可为空");
            }
            if (model.isvrcode)
            {
                if (string.IsNullOrEmpty(model.code))
                {
                    return new ResultInfo(ResultState.FAIL, "验证码不可为空");
                }
                //检查验证码
                var yzm = RedisHelpers.stringGet<string>($"ybdevice_yam_{model.phone}");
                if (model.code != yzm)
                {
                    return new ResultInfo() { code = ResultState.FAIL, message = "验证码错误" };
                }
            }
            var user = await dbClient.Queryable<YB_RegUser>().Where(x => x.Phone == model.phone).FirstAsync();
            //检查此手机号是否已注册
            if (user != null)
            {
                if (!await dbClient.Queryable<YB_UserWX>().AnyAsync(x => x.openid == sessionBag.OpenId && x.UserId == user.Id))
                {
                    await dbClient.Insertable<YB_UserWX>(new YB_UserWX
                    {
                        openid = sessionBag.OpenId,
                        createtime = DateTime.Now,
                        unionid = sessionBag.UnionId.ToStr(),
                        UserId = user.Id
                    }).ExecuteCommandAsync();
                }
                //检测是否绑定了fansid
                Guid? fansid = user.FansId;
                if ((!fansid.HasValue || fansid.Value == Guid.Empty)
                    && model.fansid.HasValue && model.fansid.Value != Guid.Empty)
                {
                    YB_WXFans fansdata = await dbClient.Queryable<YB_WXFans>().FirstAsync(x => x.Id == model.fansid);
                    user.Headimg = fansdata.HeadImgUrl;
                    user.Name = fansdata.NickName;
                    await dbClient.Updateable<YB_RegUser>().SetColumns(x => new YB_RegUser
                    {
                        FansId = model.fansid,
                        Headimg = fansdata.HeadImgUrl,
                        Name = fansdata.NickName,
                        Gender = fansdata.Sex
                    }).Where(x => x.Id == user.Id).ExecuteCommandAsync();
                }
                //更新登录时间,以及最新的资料
                await dbClient.Updateable<YB_RegUser>().SetColumns(x => new YB_RegUser
                {
                    LastVisitIP = Net.Ip,
                    LastVisitTime = DateTime.Now
                })
                   .Where(x => x.Id == user.Id)
                   .ExecuteCommandAsync();
                var token = Token(new WebApiOperaModel
                {
                    UserId = user.Id
                });
                return new ResultInfo(ResultState.SUCCESS, "登录成功", new
                {
                    token = token,
                    sessionid = model.sessionId,
                    info = new
                    {
                        headimg = user.Headimg,
                        nickname = user.Name
                    }
                });
            }
            else
            {
                //自动进行注册
                user = new YB_RegUser
                {
                    Secret = "",
                    Status = 1,
                    CreateTime = DateTime.Now,
                    Headimg = "",
                    LastVisitIP = Net.Ip,
                    LastVisitTime = DateTime.Now,
                    Name = model.phone,
                    Password = "",
                    Phone = model.phone,
                    City = "",
                    Country = "",
                    Gender = 0,
                    Province = "",
                    UnionId = sessionBag.UnionId.ToStr(),
                    FansId = model.fansid
                };
                if (model.fansid.HasValue && model.fansid.Value != Guid.Empty)
                {
                    YB_WXFans fansdata = await dbClient.Queryable<YB_WXFans>().FirstAsync(x => x.Id == model.fansid);
                    user.Headimg = fansdata.HeadImgUrl;
                    user.Name = fansdata.NickName;
                    user.Gender = fansdata.Sex;
                    await dbClient.Updateable<YB_RegUser>().SetColumns(x => new YB_RegUser
                    {
                        FansId = model.fansid,
                        Headimg = fansdata.HeadImgUrl,
                        Name = fansdata.NickName,
                        Gender = fansdata.Sex
                    }).Where(x => x.Id == user.Id).ExecuteCommandAsync();
                }
                var userid = await dbClient.Insertable(user).ExecuteReturnIdentityAsync();
                //增加微信绑定记录
                await dbClient.Insertable<YB_UserWX>(new YB_UserWX
                {
                    createtime = DateTime.Now,
                    openid = sessionBag.OpenId.ToStr(),
                    unionid = sessionBag.UnionId.ToStr(),
                    UserId = userid
                }).ExecuteCommandAsync();
                //增加一条用户数据记录
                await dbClient.Insertable<YB_UserRealData>(new YB_UserRealData
                {
                    UserId = userid,
                    TopStep = 0,
                    TopStepTime = 0
                }).ExecuteCommandAsync();
                //增加一条为自己的家庭成员
                var birthday = DateTime.Now.AddYears(-18).Date;
                var family = new YB_Family
                {
                    Type = (int)FamilyType.Adult,
                    Age = 18,
                    Birthday = birthday,
                    Sex = user.Gender,
                    IsSelf = 1,
                    Status = 1,
                    Createtime = DateTime.Now,
                    Height = 0,
                    Name = user.Name,
                    UserId = userid,
                    Weight = 0,
                    HeadImg = user.Headimg,
                    LastHeartTime = null
                };
                int familyid = await dbClient.Insertable(family).ExecuteReturnIdentityAsync();
                //增加一条家庭成员数据记录
                await dbClient.Insertable(new YB_FamilyData
                {
                    FamilyId = familyid,
                    AdultHeight = 0,
                    CreateTime = DateTime.Now,
                    DadHeight = 0,
                    HalfYearHeight = 0,
                    MomHeight = 0,
                    YearHeight = 0
                }).ExecuteCommandAsync();
                //更新或者新增统计数据
                if (await dbClient.Queryable<YB_Combined>().AnyAsync(x => x.Id == 1))
                {
                    await dbClient.Updateable<YB_Combined>().SetColumns(x => new YB_Combined
                    {
                        TodayRegCnt = x.TodayRegCnt + 1,
                        TotalRegCnt = x.TotalRegCnt + 1
                    }).Where(x => x.Id == 1).ExecuteCommandAsync();
                }
                else
                {
                    await dbClient.Insertable<YB_Combined>(new YB_Combined
                    {
                        Id = 1,
                        TodayDevCnt = 0,
                        TotalDevCnt = 0,
                        TodayIncome = 0,
                        TodayRegCnt = 1,
                        TodayResultCnt = 0,
                        TotalIncome = 0,
                        TotalRegCnt = 1,
                        TotalResultCnt = 0
                    }).ExecuteCommandAsync();
                }
                var token = Token(new WebApiOperaModel
                {
                    UserId = userid
                });
                return new ResultInfo(ResultState.SUCCESS, "注册成功", new
                {
                    token = token,
                    sessionid = model.sessionId,
                    info = new
                    {
                        headimg = user.Headimg,
                        nickname = user.Name
                    }
                });
            }
        }
    }
}
