using System.Data;
using System.Threading.Tasks;
using Znyc.Cloudcar.Admin.Commons;
using Znyc.Cloudcar.Admin.Commons.Dtos;
using Znyc.Cloudcar.Admin.Commons.Entitys;
using Znyc.Cloudcar.Admin.Commons.Enums;
using Znyc.Cloudcar.Admin.Commons.Mapping;
using Znyc.Cloudcar.Admin.Commons.Pages;
using Znyc.Cloudcar.Admin.Commons.Services;
using Znyc.Cloudcar.Admin.Security.Dtos;
using Znyc.Cloudcar.Admin.Security.Entitys;
using Znyc.Cloudcar.Admin.Security.IRepositories;
using Znyc.Cloudcar.Admin.Security.IServices;

namespace Znyc.Cloudcar.Admin.Security.Services
{
    /// <summary>
    /// </summary>
    public class UserService : BaseService<UserEntity, UserOutputDto, long>, IUserService
    {
        private readonly ICertificationRepository _certificationRepository;
        private readonly ILoginLogsRepository _loginLogsRepository;
        private readonly IUserRepository _userRepository;

        public UserService(IUserRepository repository,
            ILoginLogsRepository loginLogsRepository,
            ICertificationRepository certificationRepository) : base(repository)
        {
            _userRepository = repository;
            _certificationRepository = certificationRepository;
            _loginLogsRepository = loginLogsRepository;
        }

        /// <summary>
        ///     �첽����ʵ�塣
        /// </summary>
        /// <param name="entity">ʵ��</param>
        /// <param name="id">����ID</param>
        /// <param name="trans">�������</param>
        /// <returns></returns>
        public override async Task<bool> UpdateAsync(UserEntity entity, long id, IDbTransaction trans = null)
        {
            bool result = await repository.UpdateAsync(entity, id, trans);
            return result;
        }

        /// <summary>
        ///     ����������ѯ���ݿ�,�����ض��󼯺�(���ڷ�ҳ������ʾ)
        /// </summary>
        /// <param name="search">��ѯ������</param>
        /// <returns>ָ������ļ���</returns>
        public override async Task<PageResult<UserOutputDto>> FindWithPagerAsync(SearchInputDto<UserEntity> search)
        {
            bool order = search.Order == "asc" ? false : true;
            string where = GetDataPrivilege(false);
            if (!string.IsNullOrEmpty(search.Keywords))
            {
                @where += string.Format(" and (UserName like '%{0}%')", search.Keywords);
            };
            PagerInfo pagerInfo = new PagerInfo
            {
                CurrenetPageIndex = search.CurrenetPageIndex,
                PageSize = search.PageSize
            };
            System.Collections.Generic.List<UserEntity> list = await repository.FindWithPagerAsync(where, pagerInfo, search.Sort, order);
            PageResult<UserOutputDto> pageResult = new PageResult<UserOutputDto>
            {
                CurrentPage = pagerInfo.CurrenetPageIndex,
                Items = list.MapTo<UserOutputDto>(),
                ItemsPerPage = pagerInfo.PageSize,
                TotalItems = pagerInfo.RecordCount
            };
            return pageResult;
        }

        /// <summary>
        ///     �첽��ҳ��ѯ������ʱ��״̬�ؼ��֣�
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        public async Task<PageResult<UserOutputDto>> FindWithPagerSearchAsync(SearchUserModel search)
        {
            PagerInfo pagerInfo = new PagerInfo
            {
                CurrenetPageIndex = search.CurrenetPageIndex,
                PageSize = search.PageSize
            };

            System.Collections.Generic.List<UserOutputDto> list = (await _userRepository.FindUserWithPagerAsync(search, pagerInfo)).MapTo<UserOutputDto>();
            System.Collections.Generic.List<LoginLogsEntity> LastLoginLogsList = await _loginLogsRepository.GetLastLoginLogAsync();

            foreach (UserOutputDto item in list)
            {
                item.PositivePhoto = "";
                item.ReversePhoto = "";
                item.IdCard = "";
                item.IssuedAddress = "";
                item.Gender = "";
                item.CertificationState = (int)UserCertificationEnum.None;
                CertificationEntity certification = await _certificationRepository.GetWhereAsync($"UserId={item.Id}");
                if (certification != null)
                {
                    item.CertificationId = certification.Id;
                    item.PositivePhoto = string.Format(CommonConst.Default_Identity_Prefix, item.Id) + certification.PositivePhoto;
                    item.ReversePhoto = string.Format(CommonConst.Default_Identity_Prefix, item.Id) + certification.ReversePhoto;
                    item.IdCard = certification.IdCard;
                    item.IssuedAddress = certification.IssuedAddress;
                    item.Gender = certification.Gender;
                    item.CertificationState = certification.State;
                }
                item.AvatarUrl =  item.AvatarUrl;
                item.LastLoginTime = LastLoginLogsList.Find(x => x.CreatedUserId == item.Id)?.LoginTime;
                item.Contact = item.Contact;
            }

            PageResult<UserOutputDto> pageResult = new PageResult<UserOutputDto>
            {
                CurrentPage = pagerInfo.CurrenetPageIndex,
                Items = list,
                ItemsPerPage = pagerInfo.PageSize,
                TotalItems = pagerInfo.RecordCount
            };
            return pageResult;
        }

        /// <summary>
        ///     �첽����/�����û�
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status">1-����/99-����</param>
        /// <returns></returns>
        public async Task<CommonResult> UpdateStatusAsync(long id, int status)
        {
            CommonResult result = new CommonResult();
            UserEntity user = await repository.GetAsync(id);
            if (!(user?.Id > 0))
            {
                result.Success = false;
                result.ErrMsg = "�û�������";
                return result;
            }

            user.State = status;
            await repository.UpdateAsync(user, id);
            result.Success = true;
            return result;
        }


        /// <summary>
        ///     �첽����/�����û�
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<CommonResult> UpdateIsPromoteAsync(long id)
        {
            CommonResult result = new CommonResult();
            UserEntity user = await repository.GetAsync(id);
            if (!(user?.Id > 0))
            {
                result.Success = false;
                result.ErrMsg = "�û�������";
                return result;
            }

            user.IsPromote = !user.IsPromote;
            await repository.UpdateAsync(user, id);
            result.Success = true;
            return result;
        }

    }
}