using Hncore.Infrastructure.Data;
using Hncore.Infrastructure.DDD;
using Hncore.Infrastructure.Extension;
using Hncore.Infrastructure.WebApi;
using Hncore.Pass.PaymentCenter.Domain;
using Hncore.Pass.PaymentCenter.Model;
using Hncore.Pass.PaymentCenter.Service;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Linq;
using System.Threading.Tasks;

namespace Hncore.Pass.PaymentCenter.Controllers
{
    public class PaymentControllerBase : HncoreControllerBase
    {
        TenantService m_TenantService;
     

        IConfiguration m_Configuration;

        public PaymentControllerBase(TenantService _TenantService, IConfiguration _Configuration)
        {
            m_TenantService = _TenantService;
            m_Configuration = _Configuration;
        }

        [NonAction]
        protected async Task<MchInfo> GetMchInfoAsync(int tenantId, int storeId,
            PaymentChannel paymentChannel)
        {
            if (paymentChannel == PaymentChannel.WxPay)
            {
                MchInfo mchInfo;

                mchInfo = await RedisHelper.GetAsync<MchInfo>(GetWxPayCacheKey(tenantId, storeId));

                if (mchInfo == null)
                {

                    var config = await m_TenantService.GetById(tenantId);

                    if (config == null
                        || !config.MchId.Has()
                        || !config.MchKey.Has())
                    {
                        BusinessException.Throw("支付信息未设置");
                    }

                    mchInfo = new MchInfo()
                    {
                        GroupNo = config?.MchId,
                        Key = config?.MchKey,
                        MchId = config?.MchId
                    };

                    await RedisHelper.SetAsync(GetWxPayCacheKey(tenantId, storeId), mchInfo);

                    return mchInfo;
                }

                return mchInfo;

            }

            BusinessException.Throw("未知的支付渠道");
            return null;
        }

        [NonAction]
        protected string GetWxPayCacheKey(int ownerId, int projectCode)
        {
            return $"PaymentCenter:WxPayMchInfo:{ownerId}:{projectCode}";
        }
        /// <summary>
        /// 微信支付 接收通知url
        /// </summary>
        /// <returns></returns>
        protected string GetNotifyUrl()
        {
            return Request.HttpContext.RequestServices.GetService<IConfiguration>()["NotifyUrl"];
        }

    }
}