
using Hncore.Infrastructure.Service;
using Hncore.Pass.BaseInfo.Models;
using Hncore.Pass.Sells.Service;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace Hncore.Pass.BaseInfo.Service
{

    public partial class WxAppUserService : ServiceBase<WxAppUserEntity>, IFindService
    {
        WxAppService m_WxAppService;
        CouponService couponService;
        public WxAppUserService(WxAppService _WxAppService, CouponService _couponService, UserDbContext dbContext, IHttpContextAccessor httpContextAccessor) : base(dbContext, httpContextAccessor)
        {
            m_WxAppService = _WxAppService;
            couponService = _couponService;
        }

        public async Task<WxAppUserEntity> GetWxAppUserInfo(string appId,string openId, int appType=1)
        {
            var wxappInfo = await this.Query(false).FirstOrDefaultAsync(m => m.Appid == appId&&m.AppType==appType&&m.Openid==openId);

            return wxappInfo;
        }

        public async Task<WxAppUserEntity> Bind(WxAppUserEntity userInfo)
        {
            var wxUserInfo = await GetWxUser(userInfo.Appid, userInfo.Openid);
            if (wxUserInfo == null)
            {
                wxUserInfo = await this.Add(userInfo);
            }
            else //if (!string.IsNullOrEmpty(userInfo.Openid))
            {
                if (wxUserInfo.UserId == 0 && wxUserInfo.IsSubscribe == 1)
                {
                    await couponService.Give(5, "", userInfo.UserId, 1, Hncore.Pass.Sells.Domain.Enums.CouponOriginType.MP, "¹Ø×¢¹«ÖÚºÅÔùËÍ");
                }
                wxUserInfo.UserId = userInfo.UserId;
                await this.Update(wxUserInfo);
            }
            return wxUserInfo;
        }

        public async Task<WxAppUserEntity> GetWxUser(string appId, int userId)
        {
            return await this.Query(m => m.Appid == appId && m.UserId == userId).FirstOrDefaultAsync();
        }
        public async Task<WxAppUserEntity> GetWxUser(string appId, string openId)
        {
            return await this.Query(m => m.Appid == appId && m.Openid == openId).FirstOrDefaultAsync();
        }
        public  WxAppUserEntity GetByOpenId(string openId)
        {
            return this.Query(m => m.Openid == openId).FirstOrDefault();
        }
    }
}