
using Dapper;
using System.Threading.Tasks;
using XYY.Core.Standard.Data.Infrastructure;
using XYY.Model.Standard.Finance;

namespace XYY.Data.Standard.Finance
{
    public interface IFinance_RateRepository : IBaseRepository<Finance_Rate>
    {
        new Task Insert(Finance_Rate Finance_Rate);

        new Task Update(Finance_Rate finance_Rate);
    }
    public class Finance_RateRepository : BaseRepository<Finance_Rate>, IFinance_RateRepository
    {
        public Finance_RateRepository(IUnitOfWork unitOfWork) : base(unitOfWork)
        {
        }

        async Task IFinance_RateRepository.Insert(Finance_Rate Finance_Rate)
        {
            string sql = $@"SELECT count(0)
                              FROM Finance_Rate
                             WHERE  Currency='{Finance_Rate.Currency}' and  (StartDate BETWEEN '{Finance_Rate.StartDate}' AND '{Finance_Rate.EndDate}' OR
                                   endDate BETWEEN '{Finance_Rate.StartDate}' AND '{Finance_Rate.EndDate}' OR
                                   '{Finance_Rate.StartDate}' BETWEEN startdate AND endDate OR
                                   '{Finance_Rate.EndDate}' BETWEEN startdate AND endDate)";

            int qty = _unitOfWork.Connection.QuerySingle<int>(sql, null, _unitOfWork.Transaction);
            if (qty > 0)
                throw new System.Exception("指定时间范围重叠");
            else
                await _unitOfWork.InsertAsync(Finance_Rate);
        }

        async Task IFinance_RateRepository.Update(Finance_Rate finance_Rate)
        {
            string sql = $@"SELECT count(0)
                              FROM Finance_Rate
                             WHERE  Currency='{finance_Rate.Currency}' and  Id<>{finance_Rate.Id} and(StartDate BETWEEN '{finance_Rate.StartDate}' AND '{finance_Rate.EndDate}' OR
                                   endDate BETWEEN '{finance_Rate.StartDate}' AND '{finance_Rate.EndDate}' OR
                                   '{finance_Rate.StartDate}' BETWEEN startdate AND endDate OR
                                   '{finance_Rate.EndDate}' BETWEEN startdate AND endDate)
                    ";

            int qty = await _unitOfWork.Connection.QuerySingleAsync<int>(sql, null, _unitOfWork.Transaction);
            if (qty > 0)
                throw new System.Exception("指定时间范围重叠");
            else
                await _unitOfWork.UpdateAsync(finance_Rate);

        }
    }
}
