using Furion;
using Furion.DataEncryption;
using Furion.DependencyInjection;
using Nirvana.Common;
using Nirvana.Common.ApiBase;
using Senparc.Weixin.WxOpen.Containers;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YBDevice.Entity;

namespace YBDevice.NApi.Application.BusinessClient.AccountInfo
{
    /// <summary>
    /// 商户管理
    /// </summary>
    public class BusinessService : BaseApiInfoService, IBusinessService, ITransient
    {
        private readonly ISqlSugarRepository<YB_Business> repository;
        private readonly SqlSugarClient dbClient;
        public BusinessService(ISqlSugarRepository<YB_Business> sqlSugarRepository)
        {
            repository = sqlSugarRepository;
            dbClient = repository.Context;
        }
        /// <summary>
        /// 修改昵称
        /// </summary>
        /// <returns></returns>
        public async Task<ResultInfo> ChangeNickName(string name)
        {
            await dbClient.Updateable<YB_Business>().SetColumns(x => new YB_Business
            {
                Name = name
            }).Where(x => x.Id == CurrentBusinessId).ExecuteCommandAsync();

            await dbClient.Updateable<YB_Account>().SetColumns(x => new YB_Account
            {
                RealName = name
            }).Where(x => x.Id == CurrentUserId).ExecuteCommandAsync();

            return new ResultInfo(ResultState.SUCCESS, "昵称修改成功");
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="businessChangePwdDto"></param>
        /// <returns></returns>
        public async Task<ResultInfo> ChangePwd(BusinessChangePwdDto businessChangePwdDto)
        {
            if (businessChangePwdDto.isvrcode)
            {
                if (string.IsNullOrEmpty(businessChangePwdDto.code))
                {
                    return new ResultInfo(ResultState.FAIL, "验证码不可为空");
                }
                //检查验证码
                var yzm = RedisHelpers.stringGet<string>($"ybdeviceclient_yam_{businessChangePwdDto.Phone}");
                if (businessChangePwdDto.code != yzm)
                {
                    return new ResultInfo() { code = ResultState.FAIL, message = "验证码错误" };
                }
            }
            //检查两次密码是否一致
            if (businessChangePwdDto.Password != businessChangePwdDto.RePassword)
            {
                return new ResultInfo(ResultState.FAIL, "两次密码不一致");
            }
            var user = await dbClient.Queryable<YB_Account>().FirstAsync(x => x.Phone == businessChangePwdDto.Phone);
            if(user == null)
            {
                return new ResultInfo(ResultState.FAIL, "此手机号还未注册");
            }
            string pwd = Md5.md5(DESEncrypt.Encrypt(Md5.md5(businessChangePwdDto.Password, 32).ToLower(), user.Secret).ToLower(), 32).ToLower();
            await dbClient.Updateable<YB_Account>().SetColumns(x => new YB_Account
            {
                Password = pwd
            }).Where(x => x.Id == user.Id).ExecuteCommandAsync();
            return new ResultInfo(ResultState.SUCCESS, "密码修改成功");
        }
        /// <summary>
        /// 检查用户
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public async Task<bool> CheckUserAsync(int userid)
        {
            var account = await dbClient.Queryable<YB_Account>().FirstAsync(x => x.Id == userid);
            if(account == null || account.Status == (int)StatusType.Disabled)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 获取用户资料
        /// </summary>
        /// <returns></returns>
        public async Task<ResultInfo> GetUserInfoAsync()
        {
            var account = await dbClient.Queryable<YB_Account>().FirstAsync(x => x.Id == CurrentUserId);
            var businessdata = await dbClient.Queryable<YB_BusinessRealData>().FirstAsync(x => x.BusinessId == CurrentBusinessId);
            return new ResultInfo(ResultState.SUCCESS, "success", new BusinessInfoDto
            {
                HeadImgUrl = account.HeadImg.ToStr(),
                NickName = account.RealName,
                Phone = account.Phone,
                DevCnt = businessdata !=null?businessdata.DevCount:0,
                TodayCnt = businessdata !=null?businessdata.TodayResultCnt:0,
                UserCnt = 0
            });
        }
        /// <summary>
        /// 退出登录
        /// </summary>
        /// <param name="sessionId"></param>
        /// <returns></returns>
        public async Task<ResultInfo> OutLogin(string sessionId)
        {
            var sessionBag = await SessionContainer.GetSessionAsync(sessionId);
            if (sessionBag == null)
            {
                return new ResultInfo(ResultState.FAIL, "sessionId未找到");
            }
            //清除登录信息
           // var token = App.HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer","").Trim();

            await SessionContainer.RemoveFromCacheAsync(sessionBag.OpenId);
            await dbClient.Deleteable<YB_BusinessWX>().Where(x => x.OpenId == sessionBag.OpenId).ExecuteCommandAsync();
            return new ResultInfo(ResultState.SUCCESS, "退出登录成功");
        }
        /// <summary>
        /// 上传头像
        /// </summary>
        /// <returns></returns>
        public async Task<ResultInfo> UploadImgAsync(string headimg)
        {
            await dbClient.Updateable<YB_Account>().SetColumns(x => new YB_Account
            {
                HeadImg = headimg
            }).Where(x => x.Id == CurrentUserId).ExecuteCommandAsync();
            return new ResultInfo(ResultState.SUCCESS, "头像更新成功");
        }
    }
}
