using System.Diagnostics.Eventing.Reader;
using System.Linq.Expressions;

using Furion.DataEncryption;

using PTCMS.API.Domain.Entities;
using PTCMS.API.Domain.Repositories;
using PTCMS.API.Infrastructure.Dtos;
using PTCMS.API.Infrastructure.Utils.Consts;

namespace PTCMS.API.Infrastructure.Repositories
{
    /// <summary>
    /// 证书信息仓储实现
    /// </summary>
    public class CertificateRepository : ICertificateRepository
    {
        private readonly IFreeSql _freeSql;

        /// <summary>
        /// 注入服务
        /// </summary>
        /// <param name="freeSql"></param>
        public CertificateRepository(IFreeSql freeSql)
        {
            _freeSql = freeSql;
        }

        /// <summary>
        /// 根据姓名+身份证号或者姓名+证书编码进行查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<Certificate> GetCertificateAsync(CertificateSearchDto input)
        {
            Expression<Func<Certificate, bool>> expression = null;

            if (!string.IsNullOrWhiteSpace(input.Name) && !string.IsNullOrWhiteSpace(input.IdNumber) && !string.IsNullOrWhiteSpace(input.CertificateNumber))
            {
                expression = expression.And(x => x.Name == input.Name && x.IdNumber == input.IdNumber && x.CertificateNumber == input.CertificateNumber);
            }
            else if (!string.IsNullOrWhiteSpace(input.Name) && !string.IsNullOrWhiteSpace(input.IdNumber))
            {
                expression = expression.And(x => x.Name == input.Name && x.IdNumber == input.IdNumber);
            }
            else if (!string.IsNullOrWhiteSpace(input.Name) && !string.IsNullOrWhiteSpace(input.CertificateNumber))
            {
                expression = expression.And(x => x.Name == input.Name && x.CertificateNumber == input.CertificateNumber);
            }
            else
            {
                throw new Exception("请输入姓名、身份证号、证书编号中的两项进行查询");
            }

            if (expression == null)
            {
                return null;
            }

            var data = await _freeSql.Select<Certificate>().Where(expression).FirstAsync();

            return data;
        }
    }
}