using Hncore.Infrastructure.Common;
using Hncore.Infrastructure.Data;
using Hncore.Infrastructure.DDD;
using Hncore.Infrastructure.Extension;
using Hncore.Infrastructure.Service;
using Hncore.Infrastructure.WebApi;
using Hncore.Pass.PaymentCenter.Domain;
using Hncore.Payment.Request;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using System;
using System.Threading.Tasks;

namespace Hncore.Pass.PaymentCenter.Service
{
    public class PaymentRecordService : ServiceBase<PaymentRecord>, IFindService
    {
        public PaymentRecordService(PaymentContext dbContext, IHttpContextAccessor httpContextAccessor) : base(dbContext, httpContextAccessor)
        {

        }

        public async Task<PaymentRecord> CreatePaymentRecord(PaymentRecord record)
        {
            bool anySuccessed = await this.Query(false)
                .AnyAsync(t => t.OrderId == record.OrderId && t.PaymentStatus == PaymentStatus.OkPay);

            if (anySuccessed)
            {
                BusinessException.Throw(ResultCode.RepeatPay, "该订单已支付完成，不能再次支付");
            }

            await this.Add(record);
            return record;
        }

        /// <summary>
        /// 创建支付记录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<PaymentRecord> CreatePaymentRecord(CreateOrderRequestBase request)
        {
            //todo
           // var property = await _propertyQuery.GetOneAsync(t => t.Id == request.OwnerId);

           // CheckHelper.NotNull(property, "物业不存在");

            PaymentRecord paymentRecord = request.MapTo<PaymentRecord>();

            paymentRecord.PaymentChannel = PaymentChannel.QuanFuTong;

            if (!paymentRecord.OrderId.Has())
            {
                paymentRecord.OrderId = Guid.NewGuid().ToString().Replace("-", "");
            }


            await CreatePaymentRecord(paymentRecord);

            return paymentRecord;
        }

        public async Task<PaymentRecord> GetOne(int Id)
        {
            return await this.GetById(Id);
        }

        public async Task<PaymentRecord> GetOneByOrderId(string orderId)
        {
            return await this.Query(false).FirstOrDefaultAsync(x => x.OrderId == orderId);
        }
    }
}