using BBWY.Common.Models;
using BBWY.Server.Model.Db;
using BBWY.Server.Model.Dto;
using System.Collections.Generic;
using System.Linq;
using Yitter.IdGenerator;

namespace BBWY.Server.Business
{
    public class FinancialTerminalBusiness : BaseBusiness, IDenpendency
    {
        public FinancialTerminalBusiness(IFreeSql fsql, NLog.ILogger logger, IIdGenerator idGenerator) : base(fsql, logger, idGenerator)
        {

        }

        public IList<AuditPayBillResponse> GetAuditPayBillList(QueryAuditPayBillRequest request)
        {
            request.EndDate = request.EndDate.Date.AddDays(1).AddSeconds(-1);
            return fsql.Select<AuditPayBill>().Where(apb => apb.ImportShopIds == request.ImportShopIds &&
                                                            apb.PayTime >= request.StartDate &&
                                                            apb.PayTime <= request.EndDate).OrderByDescending(b => b.PayTime).ToList<AuditPayBillResponse>();
        }

        public bool IsExistAuditPayBill(QueryAuditPayBillRequest request)
        {
            request.EndDate = request.EndDate.Date.AddDays(1).AddSeconds(-1);
            return fsql.Select<AuditPayBill>().Where(apb => apb.ImportShopIds == request.ImportShopIds &&
                                                            apb.PayTime >= request.StartDate &&
                                                            apb.PayTime <= request.EndDate).Any();
        }

        public void BatchInsertAuditPayBill(List<AuditPayBill> insertList)
        {
            if (insertList == null || insertList.Count == 0)
                throw new BusinessException("数据不全");
            //var importShopIds = insertList[0].ImportShopIds;
            //var startTime = insertList.Min(abp => abp.PayTime).Value;
            //var endTime = insertList.Max(abp => abp.PayTime).Value;

            var deleteIds = insertList.Select(p => p.PayBillNo).ToArray();

            fsql.Transaction(() =>
            {
                fsql.Delete<AuditPayBill>(deleteIds).ExecuteAffrows();
                //fsql.Delete<AuditPayBill>().Where(apb => apb.ImportShopIds == importShopIds &&
                //                                         apb.PayTime >= startTime &&
                //                                         apb.PayTime <= endTime).ExecuteAffrows();
                fsql.Insert(insertList).ExecuteAffrows();
            });
        }
    }
}