using Hncore.Infrastructure.Common;
using Hncore.Infrastructure.Data;
using Hncore.Infrastructure.Service;
using Hncore.Infrastructure.WebApi;
using Hncore.Pass.BaseInfo.Models;
using Hncore.Pass.BaseInfo.Request;
using Hncore.Pass.BaseInfo.Request.User;
using Hncore.Pass.BaseInfo.Service;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Hncore.Pass.Vpn.Service
{
    public partial class UserChargeOrderService : ServiceBase<UserChargeOrderEntity>, IFindService
    {
        UserDbContext m_DbContext;
        UserService m_UserService;
        public UserChargeOrderService(UserDbContext dbContext
            , UserService _UserService
            , IHttpContextAccessor httpContextAccessor) : base(dbContext, httpContextAccessor)
        {
            m_DbContext = dbContext;
            m_UserService = _UserService;
        }

        public async Task<ApiResult<UserChargeOrderEntity>> CreateOrder(CreateOrderRequest request, int userId)
        {
            if (request.ChargeAmount <= 0)
            {
                BusinessException.Throw("充值金额不正确");
            }
            var userEntity = await m_UserService.GetById(userId);

            if (userEntity == null)
            {
                BusinessException.Throw("用户不存在");
            }
            var order = new UserChargeOrderEntity()
            {
                OrderName = $"充值{request.ChargeAmount}",
                OrderNo = GeneratOrderNO(userId),
                OrderState = UOrderStatus.NoPay,
                UserId = userId,
                UserName = userEntity.LoginCode,
                PayChannel = request.PayChannel,
                Channel = request.Channel,
                OrderAmount = request.ChargeAmount,
                PaymentAmount = request.ChargeAmount,
            };
            await this.Add(order);
            return new ApiResult<UserChargeOrderEntity>(order);
        }

        private string GeneratOrderNO(int userId)
        {
            var code = ValidateCodeHelper.MakeNumCode(6);
            var userStr = userId.ToString().PadRight(6, '0');
            var str = $"{DateTime.Now.ToString("yyyyMMdd")}{userStr}{code}";
            var pre = "cz";
            return pre + str;
        }

        public async Task<UserChargeOrderEntity> GetOrderByNo(string no, UOrderStatus status = 0)
        {
            var order = await this.Query(m => m.OrderNo == no && (status == 0 || m.OrderState == status)).FirstOrDefaultAsync();
            return order;
        }

        public async Task<List<UserChargeOrderEntity>> GetOrders(UOrderStatus status = 0, int top = 100)
        {
            var orders = await this.Query(m => m.OrderState == status).OrderByDescending(m => m.Id).Take(top).ToListAsync();
            return orders;
        }


        /// <summary>
        /// 处理成功的订单
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        public async Task<bool> ProcessOrderAccount(UserChargeOrderEntity order)
        {
            if (order.OrderState != UOrderStatus.PayOk) return false;

            var request = new UpdateAmountRequest()
            {
                Amount = order.OrderAmount,
                AttchInfo = order.OrderNo,
                OpAmountType = ScoreType.UserCharge,
                OperateUserName = order.UserName,
                UserId = order.UserId
            };

            try
            {
                var ret = await m_UserService.UpdateAmount(request);
                if (ret.Code == ResultCode.C_SUCCESS)
                {
                    order.OrderState = UOrderStatus.Complete;
                    await this.Update(order);
                }               
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Error("处理充值订单", ex);              
                return false;
            }
        }
    }
}
