using Hncore.Infrastructure.Service;
using Hncore.Pass.Vpn.Domain;
using Microsoft.AspNetCore.Http;
using Hncore.Infrastructure.Extension;
using Hncore.Pass.Vpn.Model;
using System.Collections.Generic;
using System.Linq;
using Hncore.Pass.Vpn.Request.Product;
using Hncore.Infrastructure.WebApi;
using System.Threading.Tasks;
using Hncore.Infrastructure.Common;
using System;
using Microsoft.EntityFrameworkCore;
using Hncore.Pass.Sells.Service;
using Hncore.Infrastructure.Data;
using BaseUserService = Hncore.Pass.BaseInfo.Service.UserService;
using Hncore.Pass.BaseInfo.Request.User;
using Hncore.Pass.BaseInfo.Models;
using ScoreType = Hncore.Pass.BaseInfo.Models.ScoreType;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore.Internal;
using Hncore.Infrastructure.SMS;
using Hncore.Pass.BaseInfo.Service;

namespace Hncore.Pass.Vpn.Service
{
    public partial class ProductOrderService : ServiceBase<ProductOrderEntity>, IFindService
    {
        private ManageService m_ManageService;
        private static readonly AsyncLock _mutex1 = new AsyncLock();
        CourseContext m_DbContext;
        ProductService m_ProductService;
        ProductPackageService m_ProductPackageService;
        UserService m_UserService;
        BaseUserService m_BaseUserService;
        ProductOrderItemService m_ProductOrderItemService;
        ProductAccountService m_ProductAccountService;
        AgentService m_AgentService;
        ProductUserPriceService m_ProductUserPriceService;
        CouponService m_CouponService;
        ProductUserPriceService m_UserPriceService;
        AgentUserService m_AgentUserService;
        AgentScoreService m_AgentScoreService;
        AgentPriceService m_AgentPriceService;
        ProductPriceSchemeService m_ProductPriceSchemeService;
        public ProductOrderService(CourseContext dbContext
            , AgentUserService _AgentUserService
            , AgentScoreService _AgentScoreService
            , ProductPriceSchemeService _ProductPriceSchemeService
            , AgentPriceService _AgentPriceService
            , ProductService _ProductService
            , ProductPackageService _ProductPackageService
            , UserService _UserService
           , ProductOrderItemService _ProductOrderItemService
            , ProductAccountService _ProductAccountService
            , AgentService _AgentService
            , ProductUserPriceService m_ProductUserPriceService
            , CouponService _CouponService
            , BaseUserService _BaseUserService
            , ManageService _ManageService
            , IHttpContextAccessor httpContextAccessor) : base(dbContext, httpContextAccessor)
        {
            m_DbContext = dbContext;
            m_AgentUserService = _AgentUserService;
            m_ProductPriceSchemeService = _ProductPriceSchemeService;
            m_AgentScoreService = _AgentScoreService;
            m_AgentPriceService = _AgentPriceService;
            m_ProductService = _ProductService;
            m_ProductPackageService = _ProductPackageService;
            m_UserService = _UserService;
            m_ProductOrderItemService = _ProductOrderItemService;
            m_ProductAccountService = _ProductAccountService;
            m_AgentService = _AgentService;
            this.m_ProductUserPriceService = m_ProductUserPriceService;
            m_CouponService = _CouponService;
            m_ManageService = _ManageService;
            m_BaseUserService = _BaseUserService;

        }

        public List<OrderStatisticModel> Statistics()
        {
            string sql = @"SELECT ProductName, PackageName,
	sum(
	CASE OrderType
	WHEN 1 THEN ConnectCount
    WHEN 2 THEN ConnectCount
	ELSE 0 END) 'NewBuyCount',

	sum(
	CASE OrderType
	WHEN 1 THEN PaymentAmount
	WHEN 2 THEN PaymentAmount
    ELSE 0 END) 'NewBuyAmount',

	sum(
	CASE OrderType
	WHEN 3 THEN ConnectCount
	WHEN 4 THEN ConnectCount
	ELSE 0 END) 'AgainBuyCount',

	sum(
	CASE OrderType
	WHEN 3 THEN PaymentAmount
	WHEN 4 THEN PaymentAmount
	ELSE 0 END) 'AgainBuyAmount',

	sum(
	CASE OrderType	
	WHEN 5 THEN AccountCount
	ELSE 0 END) 'RefundCount',

	sum(
	CASE OrderType	
	WHEN 5 THEN PaymentAmount
	ELSE 0 END) 'RefundAmount'

FROM product_order where OrderState=20 or OrderState=90 or OrderState=40 or OrderState=50 GROUP BY ProductName, PackageName order by ProductName, PackageName";
            return m_DbContext.ExecSqlQuery<OrderStatisticModel>(sql).ToList();
        }

        public List<OrderStatisticModel> Statistics(DateTime? bTime, DateTime? eTime, int ProductId)
        {
            string where = $" (OrderState=20 or OrderState=90 or OrderState=40 or OrderState=50 or OrderState=30)  ";
            // if (bTime.HasValue && eTime.HasValue)
            // {
                // where += $"and UpdateTime>DATE_SUB(CURDATE(), INTERVAL 30 DAY) and UpdateTime<now()";
            // }
            if (bTime.HasValue && eTime.HasValue)
            {
                where += $"and UpdateTime>'{bTime.Value.ToString("yyyy-MM-dd")}' and UpdateTime<'{eTime.Value.ToString("yyyy-MM-dd")}'";
            }

            if (ProductId!=0){
                where += $"and ProductId='{ProductId}'";
            }


            string sql = $@"SELECT ProductName, PackageName,
	sum(
	CASE OrderType
	WHEN 1 THEN ConnectCount*AccountCount
    WHEN 2 THEN ConnectCount*AccountCount
	ELSE 0 END) 'NewBuyCount',

	sum(
	CASE OrderType
	WHEN 1 THEN PaymentAmount
	WHEN 2 THEN PaymentAmount
    ELSE 0 END) 'NewBuyAmount',

	sum(
	CASE OrderType
	WHEN 3 THEN ConnectCount*AccountCount
	WHEN 4 THEN ConnectCount*AccountCount
	ELSE 0 END) 'AgainBuyCount',

	sum(
	CASE OrderType
	WHEN 3 THEN PaymentAmount
	WHEN 4 THEN PaymentAmount
	ELSE 0 END) 'AgainBuyAmount',

	sum(
	CASE OrderType	
	WHEN 5 THEN AccountCount
	ELSE 0 END) 'RefundCount',

	sum(
	CASE OrderType	
	WHEN 5 THEN RefundAmount
	ELSE 0 END) 'RefundAmount'

FROM product_order where {where} GROUP BY ProductName, PackageName order by ProductName, PackageName";
            return m_DbContext.ExecSqlQuery<OrderStatisticModel>(sql).ToList();
        }

        public List<OrderStatisticModel> SellerStatistics(DateTime? bTime, DateTime? eTime, string Channel)
        {

            string where = $" OrderState=90 and   Channel IS NOT NULL  ";
            if (bTime.HasValue && eTime.HasValue)
            {
                where += $"and CreateTime>'{bTime.Value.ToString("yyyy-MM-dd")}' and CreateTime<'{eTime.Value.ToString("yyyy-MM-dd")}'";
            } else
            {
                where += $"and CreateTime>'{DateTime.Now.ToString("yyyy-MM-dd")}' and CreateTime<'{DateTime.Now.AddDays(1).ToString("yyyy-MM-dd")}'";
            }
            if (Channel.Has()){
                where += $"and Channel='{Channel}'";
            }

            string sql = $@"SELECT Channel,ProductName,
	sum(
	CASE OrderType
	WHEN 1 THEN ConnectCount
    WHEN 2 THEN ConnectCount
	ELSE 0 END) 'NewBuyCount',

	sum(
	CASE OrderType
	WHEN 1 THEN PaymentAmount
	WHEN 2 THEN PaymentAmount
    ELSE 0 END) 'NewBuyAmount',

	sum(
	CASE OrderType
	WHEN 3 THEN ConnectCount
	WHEN 4 THEN ConnectCount
	ELSE 0 END) 'AgainBuyCount',

	sum(
	CASE OrderType
	WHEN 3 THEN PaymentAmount
	WHEN 4 THEN PaymentAmount
	ELSE 0 END) 'AgainBuyAmount',

	sum(
	CASE OrderType	
	WHEN 5 THEN AccountCount
	ELSE 0 END) 'RefundCount',

	sum(
	CASE OrderType	
	WHEN 5 THEN PaymentAmount
	ELSE 0 END) 'RefundAmount'

FROM product_order where {where}  GROUP BY Channel,ProductName order by Channel,ProductName";
            return m_DbContext.ExecSqlQuery<OrderStatisticModel>(sql).ToList();
        }


        public async Task<ApiResult<ProductOrderEntity>> CreateOrder(CreateOrderRequest request, int userId)
        {

            var packageEntity = await m_ProductPackageService.GetById(request.PackageId);
            if (packageEntity == null)
            {
                return new ApiResult<ProductOrderEntity>(ResultCode.C_INVALID_ERROR, "没有选择套餐");
            }
            var productEntity = await m_ProductService.GetById(packageEntity.ProductId);
            if (productEntity == null)
            {
                return new ApiResult<ProductOrderEntity>(ResultCode.C_INVALID_ERROR, "产品不存在或者下架");
            }
            // if (productEntity.Status == 0)
            // {
            //     return new ApiResult<ProductOrderEntity>(ResultCode.C_INVALID_ERROR, "产品不存在或者下架");
            // }
            // if (productEntity.Status == 0)
            // {
            //     return new ApiResult<ProductOrderEntity>(ResultCode.C_INVALID_ERROR, "服务不在线");
            // }

            if (request.Account == request.Pwd)
            {
                return new ApiResult<ProductOrderEntity>(ResultCode.C_INVALID_ERROR, "账号和密码不能一致");
            }

            var userEntity = await m_UserService.GetById(userId);

            //天卡0.1元
            var ExpiredProductAccountCount = userEntity.ExpiredProductAccountCount;

            var is_verify = userEntity.is_verify;   
            

            

            if (is_verify == 0)
            {
                return new ApiResult<ProductOrderEntity>(ResultCode.C_INVALID_ERROR, "请前往实名认证");
            }     

            if (request.ConnectCount<=0){
                return new ApiResult<ProductOrderEntity>(ResultCode.C_INVALID_ERROR, "链接数至少为1！");
            }

            


            //是否已经设置会员价
            var is_user_price = true;

            var price = packageEntity.Price;

            var dis_price =  1000000M;
            
            if((userEntity.agent_id == 0||(userEntity.agent_id != 0 && userEntity.discount_id != 0)) && userEntity.discount_id >= 0){
            //根据折扣设置价格
                var discount  = await m_ProductPriceSchemeService.GetById(userEntity.discount_id);
                if (discount != null)
                {
                    dis_price = packageEntity.LinePrice * discount.discount / 100;
                    if(discount.discount < 65){
                        is_user_price = false;
                    }
                }
            } else {
            //根据会员价
                var userPrice = await this.m_ProductUserPriceService.Query(true).FirstOrDefaultAsync(m => m.UserId == userId && m.PackageId == packageEntity.Id && m.Status == 1);
                if (userPrice != null && userPrice.UserPrice > 0)
                {
                    dis_price = userPrice.UserPrice;
                    is_user_price = false;
                }
            }

            //确定价格
            if(dis_price<price){
                price = dis_price;
            }
            //最低价
            if(price<packageEntity.MinPrice){
                price = packageEntity.MinPrice;
            }

            //为超过免费的测试卡改价格
            if (packageEntity.IsTest == 1 && ((userEntity.TestCountLimit!=0 && userEntity.TestCountLimit<=userEntity.UseTestCount) || (userEntity.TestCountLimit ==0 && userEntity.UseTestCount>2))) {
                price = 1.00M;
            }

            if (request.PackageId == 1012&&ExpiredProductAccountCount == 0 && request.OrderType != OrderType.News && (packageEntity.DayCount == 1||packageEntity.DayCount == 2) && request.ConnectCount == 1 && request.OrderType!=OrderType.AgainBuy&& request.OrderType!=OrderType.AgainBuys){
                price = 0.1M;
                userEntity.ExpiredProductAccountCount = 1;
                await m_UserService.Update(userEntity);
            }
            var order = new ProductOrderEntity()
            {
                AccountCount = 1,
                ConnectCount = request.ConnectCount,
                CouponId = request.CouponId,
                OrderName = packageEntity.Name,
                OrderNo = GeneratOrderNO(userId, request.OrderType),
                OrderState = OrderStatus.NoPay,
                OrderType = request.OrderType,
                PackageId = request.PackageId,
                PackageName = packageEntity.Name,
                ProductId = productEntity.Id,
                ProductName = productEntity.Name,
                PayType = request.OPayType,
                UserId = userId,
                UserName = userEntity.LoginCode,
                DayCount = packageEntity.DayCount,
                DayPrice = price,//(packageEntity.DayCount * request.ConnectCount),
                AccountPwd = request.Pwd,
                StartTime = DateTime.Now,
                EndTime = DateTime.Now.AddDays(packageEntity.DayCount),
                PayChannel = request.PayChannel,
                Channel = request.Channel,
                IsAutoRefund = productEntity.AutoRefund,
                agent_id = userEntity.agent_id,
                Remark = request.phone
            };
            if (request.OrderType == OrderType.New || request.OrderType == OrderType.AgainBuy)
            {
                order.OrderAmount = price * request.ConnectCount;
                order.Accounts = request.Account;
                
                //双月卡活动
                // var isExit = await m_ProductAccountService.CheckMonthAccountExist(request.Account);
                // if(isExit){
                //     return new ApiResult<ProductOrderEntity>(ResultCode.C_INVALID_ERROR, request.Account + "此IP账号已享受该优惠套餐，无法再次购买,若要购买此优惠套餐，请新开或续费其他账号。");
                // }
            }

            if (request.OrderType == OrderType.News)
            {
                var accounts = GreateBatchAccount(request.Account, request.MinPostfix, request.MaxPostfix);
                order.AccountCount = accounts.Count;
                order.OrderAmount = price * request.ConnectCount * accounts.Count;
                order.Accounts = string.Join(",", accounts);
            }

            if (request.OrderType == OrderType.AgainBuys)
            {
                // if (request.PackageId >1029 && request.PackageId <1034) {
                //     return new ApiResult<ProductOrderEntity>(ResultCode.C_INVALID_ERROR, "不允许续费此套餐");
                // }
                int count = request.Account.Split(",").Length;
                order.AccountCount = count;
                order.OrderAmount = price * request.ConnectCount * count;
                order.Accounts = request.Account;
            }

            // if (userEntity.Id != 18157){           
            //     if (packageEntity.Name =="测试卡" && (order.AccountCount !=1 || order.ConnectCount != 1) ){
            //         return new ApiResult<ProductOrderEntity>(ResultCode.C_INVALID_ERROR, "如果再非法操作，juip官网将对您进行制裁，冻结您的账号");
            //     }
            // } 

            //双月卡活动
            // foreach (var account in order.Accounts.Split(",").ToList())
            // {
            //     var isExit = await m_ProductAccountService.CheckMonthAccountExist(account);
            //     if(isExit){
            //         return new ApiResult<ProductOrderEntity>(ResultCode.C_INVALID_ERROR, account + "此IP账号已享受该优惠套餐，无法再次购买,若要购买此优惠套餐，请新开或续费其他账号。");
            //     }
            // }
            await CheckRequest(order);

            var ret = await CaclePaymentAmount(order, request.UseAccountAmount, is_user_price);
            
            if (ret.Code != ResultCode.C_SUCCESS) return ret;
            
            using (var tran1 = await m_DbContext.Database.BeginTransactionAsync())
            {
                try
                {
                    await ProcessIfZeroOrder(order);
                    await this.Add(order);
                    if (request.CouponId > 0)
                        await m_CouponService.Use(request.CouponId, order.OrderNo, userId, 1);
                    tran1.Commit();
                }
                catch (Exception ex)
                {                    
                    LogHelper.Error("CreateOrder", ex.Message);
                    tran1.Rollback();
                    return new ApiResult<ProductOrderEntity>(ResultCode.C_UNKNOWN_ERROR, "提交订单失败");
                }
            }
            return new ApiResult<ProductOrderEntity>(order);
        }

        public async Task<ApiResult<ProductOrderEntity>> CaclePaymentAmount(ProductOrderEntity order, int useAccountAmount, bool is_user_price = true)
        {
            using (await _mutex1.LockAsync())
            {
                var userEntity = await m_UserService.GetById(order.UserId);
                //使用优惠券
                var couponAmount = 0m;
                if (order.CouponId > 0 && order.CouponId != 10000000)
                {
                    var currentCoupon = await m_CouponService.GetOneUserAvailableCoupon(userEntity.Id, order.CouponId.Value);
                    if(currentCoupon.Coupon.Id<16 ){
                        if(is_user_price){
                            if (currentCoupon == null)
                                return new ApiResult<ProductOrderEntity>(ResultCode.C_INVALID_ERROR, "没有可用的优惠券");
                            if (currentCoupon.Coupon.AllowMinAmount > 0 && order.OrderAmount < currentCoupon.Coupon.AllowMinAmount)
                            {
                                return new ApiResult<ProductOrderEntity>(ResultCode.C_INVALID_ERROR, $"满{currentCoupon.Coupon.AllowMinAmount}元才能使用");
                            }
                            if (currentCoupon.Coupon.CouponType == Sells.Model.ECouponType.Minus)
                                couponAmount = currentCoupon.Coupon.CouponValue;
                            else
                                couponAmount = order.OrderAmount * (currentCoupon.Coupon.CouponValue * 0.1m);
                        } else {
                            return new ApiResult<ProductOrderEntity>(ResultCode.C_INVALID_ERROR, "您已经享有会员优惠价，无法与优惠券共享！如有需求，请联系客服！");
                        }
                    } else {
                        if (currentCoupon == null)
                            return new ApiResult<ProductOrderEntity>(ResultCode.C_INVALID_ERROR, "没有可用的优惠券");
                        if (currentCoupon.Coupon.AllowMinAmount > 0 && order.OrderAmount < currentCoupon.Coupon.AllowMinAmount)
                        {
                            return new ApiResult<ProductOrderEntity>(ResultCode.C_INVALID_ERROR, $"满{currentCoupon.Coupon.AllowMinAmount}元才能使用");
                        }
                        if (currentCoupon.Coupon.CouponType == Sells.Model.ECouponType.Minus)
                            couponAmount = currentCoupon.Coupon.CouponValue;
                        else
                            couponAmount = order.OrderAmount * (currentCoupon.Coupon.CouponValue * 0.1m);
                    }
                }

                order.CouponAmount = couponAmount;
                order.PaymentAmount = order.OrderAmount - couponAmount;
                order.PaymentAmount = order.PaymentAmount < 0 ? 0 : order.PaymentAmount;
                //使用余额
                if (useAccountAmount == 1)
                {
                    if (userEntity.RestAmount >= order.PaymentAmount)
                        order.AccountPayAmount = order.PaymentAmount;
                    else
                    {
                        return new ApiResult<ProductOrderEntity>(ResultCode.C_UNKNOWN_ERROR, "余额不足");
                    }
                }
                order.OtherPayAmount = order.PaymentAmount - order.AccountPayAmount;
            }
            return new ApiResult<ProductOrderEntity>(order);
        }

        public async Task<ProductOrderEntity> ProcessIfZeroOrder(ProductOrderEntity order)
        {
            //账户余额支付
            if (order.AccountPayAmount > 0)
            {
                
                var amountInfo = new UpdateAmountRequest()
                {
                    Amount = order.AccountPayAmount.Value,
                    OpAmountType = ScoreType.Pay,
                    UserId = order.UserId,
                    AttchInfo = order.OrderNo,
                    OperateUserName = order.UserName,
                };
                var ret = await m_BaseUserService.UpdateAmount(amountInfo,order.ProductName,order.PackageName,order.Accounts);
                if (ret.Code != ResultCode.C_SUCCESS)
                {
                    order.OtherPayAmount = order.PaymentAmount;
                }
            }
            //全是余额支付
            if (order.OtherPayAmount == 0)
            {
                order.PayType = PayType.Amount;
                order.OrderState = OrderStatus.PayOk;

            }
            return order;
        }


        private async Task<ApiResult> CheckRequest(ProductOrderEntity request)
        {
            if (request.Accounts.NotHas())
            {
                BusinessException.Throw("账号不能为空");
            }
            var accounts = new List<string>();
            if (request.OrderType == OrderType.New || request.OrderType == OrderType.AgainBuy)
            {
                accounts.Add(request.Accounts);
            }
            else
            {
                accounts = request.Accounts.Split(",").ToList();
            }

            if (request.OrderType == OrderType.New || request.OrderType == OrderType.News)
            {
                var exist = await m_ProductAccountService.CheckAccountExist(request.ProductId, accounts);
                if (exist)
                {
                    BusinessException.Throw("账号已经存在");
                }
            }
            else
            {
                foreach (var account in accounts)
                {
                    var ret = await m_AgentService.GetOriginAccountInfo(request.ProductId, account);
                    if (ret.Code != ResultCode.C_SUCCESS)
                    {
                        BusinessException.Throw($"账号【{account}】不存在");
                    }
                    var accountInfo = await m_ProductAccountService.GetAccountNotRefundInfo(account);
                    if (accountInfo.Status == AccountStatus.Refund)
                    {
                        BusinessException.Throw($"已退款的账号禁止续费，请重新开号");
                    }
                }
            }
            return new ApiResult(1);
        }

        public List<string> GreateBatchAccount(string account, int min, int count)
        {
            List<string> accountList = new List<string>();
            while (count-- > 0)
            {
                accountList.Add($"{account}{min++}");
            }
            return accountList;
        }

        private string GeneratOrderNO(int userId, OrderType oType)
        {
            var code = ValidateCodeHelper.MakeNumCode(6);
            var userStr = userId.ToString().PadRight(6, '0');
            var str = $"{DateTime.Now.ToString("yyyyMMdd")}{userStr}{code}";
            var pre = "";
            if (oType == OrderType.New) pre = "xk";
            if (oType == OrderType.News) pre = "plxk";
            if (oType == OrderType.AgainBuy) pre = "xf";
            if (oType == OrderType.AgainBuys) pre = "plxf";
            if (oType == OrderType.Refund) pre = "tk";
            return pre + str;
        }

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

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

        public async Task<List<ProductOrderEntity>> GetLimitTimeOrders(OrderStatus status = 0, int minutes = 5, int top = 50)
        {
            var orders = await this.Query(m => m.OrderState == status && (DateTime.Now - m.CreateTime)
            .TotalMinutes >= minutes)
            .OrderByDescending(m => m.Id)
            .Take(top)
            .ToListAsync();
            return orders;
        }

        public async Task CreateAccountByOrder(string OrderNo)
        {
            var order = await this.GetOrderByNo(OrderNo, OrderStatus.PayOk);
            if (order == null) return;

            await ProcessOrderAccount(order);
        }

        /// <summary>
        /// 处理成功的订单
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        public async Task ProcessOrderAccount(ProductOrderEntity order)
        {
            if (order.OrderState != OrderStatus.PayOk || order.Accounts == null) return;

            var isOk = true;
            var accounts = order.Accounts.Split(',').ToList();
            accounts = accounts.Distinct().ToList();

            var userEntity = await m_UserService.GetById(order.UserId);

            var user_remark = "";

            if(order.ProductId == 8||order.ProductId == 7) {
                //用户信息
                user_remark = userEntity.Name.Substring(0,1) + "**" + userEntity.Phone.Substring(0,3) + "********" + userEntity.id_code.Substring(0,3)+"***************";
                
            }
            
            if (order.OrderType == OrderType.New || order.OrderType == OrderType.News)
            {
                var accountEntitys = new List<ProductAccountEntity>();

                var end_time = DateTime.Now.AddDays(order.DayCount);
                if (order.PackageName == "测试卡" || order.PackageName == "测试卡(高级)" || order.PackageName == "测试卡(普通)") {
                    end_time = DateTime.Now.AddHours(order.DayCount);
                    userEntity.ProductAccountCount = 1;
                }
                
                
                await accounts.ForEachAsync(async account =>
                {
                    var accountEntity = new ProductAccountEntity()
                    {
                        Account = account,
                        AccountType = (int)order.OrderType,
                        ConnectCount = order.ConnectCount,
                        StartTime = DateTime.Now,
                        EndTime = end_time,
                        PackageId = order.PackageId,
                        PackageName = order.PackageName,
                        ProductId = order.ProductId,
                        ProductName = order.ProductName,
                        Pwd = order.AccountPwd,
                        ChargeStatus = AccountChargeStatus.Normal,
                        UserId = order.UserId,
                        UserCode = order.UserName,
                        agent_id = order.agent_id,
                        UserPhone = order.Remark
                    };
                    accountEntitys.Add(accountEntity);
                });
                using (var tran2 = await m_DbContext.Database.BeginTransactionAsync())
                {
                    try
                    {
                        await m_ProductAccountService.Adds(accountEntitys);
                        order.OrderState = OrderStatus.Complete;
                        order.StartTime = DateTime.Now;
                        order.EndTime = end_time;
                        await this.Update(order);
                        tran2.Commit();
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error("处理订单创建账号", ex);
                        isOk = false;
                        tran2.Rollback();
                    }
                }
                if (isOk)
                {
                    var accountError = "";
                    await accountEntitys.ForEachAsync(async accountEntity =>
                    {
                        
                        var ret = new ApiResult();
                        if(accountEntity.PackageId.Value == 86 || accountEntity.PackageId.Value == 88){
                            ret = await m_AgentService.NewAccount(order.Id, accountEntity.PackageId.Value, accountEntity.Account, accountEntity.Pwd, accountEntity.ConnectCount,1,2);
                        } else if(accountEntity.ProductId.Value == 8 || accountEntity.ProductId.Value == 7){
                            var account_remark = accountEntity.Account + "-" + user_remark;
                            ret = await m_AgentService.NewAccount(order.Id, accountEntity.PackageId.Value, account_remark, accountEntity.Pwd, accountEntity.ConnectCount,1,2);
                        } else if (accountEntity.PackageId.Value > 1034 && accountEntity.PackageId.Value < 1040) {
                            ret = await m_AgentService.NewAccount(order.Id, accountEntity.PackageId.Value, accountEntity.Account, accountEntity.Pwd, accountEntity.ConnectCount,2);
                        }
                         else if (accountEntity.PackageId.Value > 1040 && accountEntity.PackageId.Value < 1046) {
                            ret = await m_AgentService.NewAccount(order.Id, accountEntity.PackageId.Value, accountEntity.Account, accountEntity.Pwd, accountEntity.ConnectCount,3);
                        }
                        else {
                            ret = await m_AgentService.NewAccount(order.Id, accountEntity.PackageId.Value, accountEntity.Account, accountEntity.Pwd, accountEntity.ConnectCount);
                        }
                        
                        if (ret.Code != ResultCode.C_SUCCESS)
                        {
                            accountEntity.ChargeStatus = AccountChargeStatus.Exception;
                            accountEntity.Remark = ret.Message;
                            await m_ProductAccountService.Update(accountEntity);
                               
                        }
                        else if (ret.Data != null && ret.Data.ToString().Has())
                        {
                            accountEntity.Raw = ret.Data.ToString();
                            await m_ProductAccountService.Update(accountEntity);
                        }
                    });
                    if (accountError.Has())
                    {
                        order.Remark = accountError;
                        await this.Update(order);
                    }                      
                }
            }
            else if (order.OrderType == OrderType.AgainBuy || order.OrderType == OrderType.AgainBuys)
            {
                var accountEntitys = await m_ProductAccountService.Query(p => p.UserId == order.UserId && p.DeleteTag == 0 && p.ProductId == order.ProductId && accounts.Contains(p.Account)).ToListAsync();

                accountEntitys = accountEntitys.Distinct(new AccountEntityEq()).ToList();

                await accountEntitys.ForEachAsync(async account =>
                {
                    if (account.EndTime < DateTime.Now)
                    {
                        account.StartTime = DateTime.Now;
                        account.EndTime = DateTime.Now.AddDays(order.DayCount);
                    }
                    else
                    {
                        account.EndTime = account.EndTime.Value.AddDays(order.DayCount);
                    }
                    account.PackageId = order.PackageId;
                    account.PackageName = order.PackageName;
                    account.ProductId = order.ProductId;
                    account.ProductName = order.ProductName;
                    account.AccountType = (int)order.OrderType;
                });
                using (var tran3 = await m_DbContext.Database.BeginTransactionAsync())
                {
                    try
                    {
                        await m_ProductAccountService.Update(accountEntitys);
                        order.OrderState = OrderStatus.Complete;
                        order.StartTime = DateTime.Now;
                        order.EndTime = DateTime.Now.AddDays(order.DayCount);
                        await this.Update(order);
                        tran3.Commit();
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error("处理续费订单", ex);
                        isOk = false;
                        tran3.Rollback();
                    }
                }
                if (isOk)
                {
                    var accountError = "";
                    var product = await m_ProductService.GetById(order.ProductId);
                    await accountEntitys.ForEachAsync(async accountEntity =>
                    {
                        var account = accountEntity.Account;
                        // if (product.GroupNO == "g7") account = accountEntity.Raw;
                        var ret = new ApiResult();
                        if (order.PackageId == 86){
                            ret = await m_AgentService.ReNewAccount(order.Id, order.PackageId, account, order.ConnectCount,2);
                        } else {
                            ret = await m_AgentService.ReNewAccount(order.Id, order.PackageId, account, order.ConnectCount);
                        }
                        if (ret.Code != ResultCode.C_SUCCESS)
                        {
                            accountEntity.ChargeStatus = AccountChargeStatus.Exception;
                            accountEntity.Remark = ret.Message;
                            await m_ProductAccountService.Update(accountEntity);
                            accountError += $"{accountEntity.Account}{accountEntity.Remark},";
                        }
                    });
                    if (accountError.Has())
                    {
                        order.Remark = accountError;
                        await this.Update(order);
                    }
                }
            }
            
            
            if(order.agent_id != 0 && order.PaymentAmount != 0.1M){
                var agentEntity = await m_AgentUserService.Query(m => m.id == order.agent_id).FirstOrDefaultAsync();

                //根据折扣设置价格
                var score_money = 0.00M;
                // if((userEntity.agent_id == 0||(userEntity.agent_id != 0 && userEntity.discount_id != 0)) && userEntity.discount_id >= 0){
                //     //获取代理折扣
                //     var discount  = await m_ProductPriceSchemeService.GetById(agentEntity.discount_id);
                //     var packageEntity = await m_ProductPackageService.GetById(order.PackageId);
                //     var price = packageEntity.LinePrice * discount.discount / 100;
                //     score_money = order.PaymentAmount - order.ConnectCount * order.AccountCount * price;
                // } else {
                //     var agentPriceEntity = await m_AgentPriceService.Query(m => m.agent_id == order.agent_id && m.package_id == order.PackageId).FirstOrDefaultAsync();
                //     score_money = order.PaymentAmount - order.ConnectCount * order.AccountCount * agentPriceEntity.price;
                // }
                if(agentEntity.discount_id != 0){
                    //获取代理折扣
                    var discount  = await m_ProductPriceSchemeService.GetById(agentEntity.discount_id);
                    var packageEntity = await m_ProductPackageService.GetById(order.PackageId);
                    var price = packageEntity.LinePrice * discount.discount / 100;
                    score_money = order.PaymentAmount - order.ConnectCount * order.AccountCount * price;
                }
                

                var agnetScoreEntity = new AgentScoreEntity()
                {
                    agent_id = order.agent_id,
                    order_id = order.Id,
                    score_type = 1,
                    score_value = score_money,
                    remark = "客户购买产品" + order.Accounts,
                    agent_name = agentEntity.username,
                    op_user = order.UserName,
                    rest_amount1 = agentEntity.account,
                    rest_amount2 = agentEntity.account + score_money
                };

                agentEntity.account += score_money;

                await m_AgentScoreService.Add(agnetScoreEntity);
                await m_AgentUserService.Update(agentEntity);
            }


            // userEntity.pay_time = DateTime.Now.ToString();
            // await m_UserService.Update(userEntity);
        }

    /// <summary>
        /// 处理成功的订单
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        public async Task ApiProcessOrderAccount(ProductOrderEntity order,string remark)
        {
            if (order.OrderState != OrderStatus.PayOk || order.Accounts == null) return;

            var isOk = true;
            var accounts = order.Accounts.Split(',').ToList();
            accounts = accounts.Distinct().ToList();

            var userEntity = await m_UserService.GetById(order.UserId);
            var user_remark = "";

            if(order.ProductId == 8||order.ProductId == 7) {
                //用户信息
                user_remark = userEntity.Name.Substring(0,1) + "**" + userEntity.Phone.Substring(0,3) + "********" + userEntity.id_code.Substring(0,3)+"***************";
                
            }
            
            if (order.OrderType == OrderType.New || order.OrderType == OrderType.News)
            {
                var accountEntitys = new List<ProductAccountEntity>();
                
                await accounts.ForEachAsync(async account =>
                {
                    var accountEntity = new ProductAccountEntity()
                    {
                        Account = account,
                        AccountType = (int)order.OrderType,
                        ConnectCount = order.ConnectCount,
                        StartTime = DateTime.Now,
                        EndTime = DateTime.Now.AddDays(order.DayCount),
                        PackageId = order.PackageId,
                        PackageName = order.PackageName,
                        ProductId = order.ProductId,
                        ProductName = order.ProductName,
                        Pwd = order.AccountPwd,
                        ChargeStatus = AccountChargeStatus.Normal,
                        UserId = order.UserId,
                        UserCode = order.UserName,
                        agent_id = order.agent_id,
                        UserPhone = order.Remark,
                        Remark = remark
                    };
                    accountEntitys.Add(accountEntity);
                });
                using (var tran2 = await m_DbContext.Database.BeginTransactionAsync())
                {
                    try
                    {
                        await m_ProductAccountService.Adds(accountEntitys);
                        order.OrderState = OrderStatus.Complete;
                        order.StartTime = DateTime.Now;
                        order.EndTime = DateTime.Now.AddDays(order.DayCount);
                        order.Remark = remark;
                        await this.Update(order);
                        tran2.Commit();
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error("处理订单创建账号", ex);
                        isOk = false;
                        tran2.Rollback();
                    }
                }
                if (isOk)
                {
                    var accountError = "";
                    await accountEntitys.ForEachAsync(async accountEntity =>
                    {
                        
                        var ret = new ApiResult();
                        if(accountEntity.PackageId.Value == 86 || accountEntity.PackageId.Value == 88){
                            ret = await m_AgentService.NewAccount(order.Id, accountEntity.PackageId.Value, accountEntity.Account, accountEntity.Pwd, accountEntity.ConnectCount,1,2);
                        } else if(accountEntity.ProductId.Value == 8 || accountEntity.ProductId.Value == 7){
                            var account_remark = accountEntity.Account + "-" + user_remark;
                            ret = await m_AgentService.NewAccount(order.Id, accountEntity.PackageId.Value, account_remark, accountEntity.Pwd, accountEntity.ConnectCount,1,2);
                        } else if (accountEntity.PackageId.Value > 1034 && accountEntity.PackageId.Value < 1040) {
                            ret = await m_AgentService.NewAccount(order.Id, accountEntity.PackageId.Value, accountEntity.Account, accountEntity.Pwd, accountEntity.ConnectCount,2);
                        }
                         else if (accountEntity.PackageId.Value > 1040 && accountEntity.PackageId.Value < 1046) {
                            ret = await m_AgentService.NewAccount(order.Id, accountEntity.PackageId.Value, accountEntity.Account, accountEntity.Pwd, accountEntity.ConnectCount,3);
                        }
                        else {
                            ret = await m_AgentService.NewAccount(order.Id, accountEntity.PackageId.Value, accountEntity.Account, accountEntity.Pwd, accountEntity.ConnectCount);
                        }
                        
                        if (ret.Code != ResultCode.C_SUCCESS)
                        {
                            accountEntity.ChargeStatus = AccountChargeStatus.Exception;
                            accountEntity.Remark = ret.Message;
                            await m_ProductAccountService.Update(accountEntity);
                               
                        }
                        else if (ret.Data != null && ret.Data.ToString().Has())
                        {
                            accountEntity.Raw = ret.Data.ToString();
                            await m_ProductAccountService.Update(accountEntity);
                        }
                        if (accountEntity.PackageId == 13) {
                            await Task.Delay(30);
                        }
                    });
                    if (accountError.Has())
                    {
                        order.Remark = accountError;
                        await this.Update(order);
                    }                      
                }
            }
            else if (order.OrderType == OrderType.AgainBuy || order.OrderType == OrderType.AgainBuys)
            {
                var accountEntitys = await m_ProductAccountService.Query(p => p.UserId == order.UserId && p.DeleteTag == 0 && p.ProductId == order.ProductId && accounts.Contains(p.Account)).ToListAsync();

                accountEntitys = accountEntitys.Distinct(new AccountEntityEq()).ToList();

                await accountEntitys.ForEachAsync(async account =>
                {
                    if (account.EndTime < DateTime.Now)
                    {
                        account.StartTime = DateTime.Now;
                        account.EndTime = DateTime.Now.AddDays(order.DayCount);
                    }
                    else
                    {
                        account.EndTime = account.EndTime.Value.AddDays(order.DayCount);
                    }
                    account.PackageId = order.PackageId;
                    account.PackageName = order.PackageName;
                    account.ProductId = order.ProductId;
                    account.ProductName = order.ProductName;
                    account.AccountType = (int)order.OrderType;
                });
                using (var tran3 = await m_DbContext.Database.BeginTransactionAsync())
                {
                    try
                    {
                        await m_ProductAccountService.Update(accountEntitys);
                        order.OrderState = OrderStatus.Complete;
                        order.StartTime = DateTime.Now;
                        order.EndTime = DateTime.Now.AddDays(order.DayCount);
                        order.Remark = remark;
                        await this.Update(order);
                        tran3.Commit();
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error("处理续费订单", ex);
                        isOk = false;
                        tran3.Rollback();
                    }
                }
                if (isOk)
                {
                    var accountError = "";
                    var product = await m_ProductService.GetById(order.ProductId);
                    await accountEntitys.ForEachAsync(async accountEntity =>
                    {
                        var account = accountEntity.Account;
                        // if (product.GroupNO == "g7") account = accountEntity.Raw;
                        var ret = new ApiResult();
                        if (order.PackageId == 86){
                            ret = await m_AgentService.ReNewAccount(order.Id, order.PackageId, account, order.ConnectCount,2);
                        } else {
                            ret = await m_AgentService.ReNewAccount(order.Id, order.PackageId, account, order.ConnectCount);
                        }
                        if (ret.Code != ResultCode.C_SUCCESS)
                        {
                            accountEntity.ChargeStatus = AccountChargeStatus.Exception;
                            accountEntity.Remark = ret.Message;
                            await m_ProductAccountService.Update(accountEntity);
                            accountError += $"{accountEntity.Account}{accountEntity.Remark},";
                        }
                    });
                    if (accountError.Has())
                    {
                        order.Remark = accountError;
                        await this.Update(order);
                    }
                }
            }
            
            
            if(order.agent_id != 0 && order.PaymentAmount != 0.1M){
                var agentEntity = await m_AgentUserService.Query(m => m.id == order.agent_id).FirstOrDefaultAsync();

                //根据折扣设置价格
                var score_money = 0.00M;
                // if((userEntity.agent_id == 0||(userEntity.agent_id != 0 && userEntity.discount_id != 0)) && userEntity.discount_id >= 0){
                //     //获取代理折扣
                //     var discount  = await m_ProductPriceSchemeService.GetById(agentEntity.discount_id);
                //     var packageEntity = await m_ProductPackageService.GetById(order.PackageId);
                //     var price = packageEntity.LinePrice * discount.discount / 100;
                //     score_money = order.PaymentAmount - order.ConnectCount * order.AccountCount * price;
                // } else {
                //     var agentPriceEntity = await m_AgentPriceService.Query(m => m.agent_id == order.agent_id && m.package_id == order.PackageId).FirstOrDefaultAsync();
                //     score_money = order.PaymentAmount - order.ConnectCount * order.AccountCount * agentPriceEntity.price;
                // }
                if(agentEntity.discount_id != 0){
                    //获取代理折扣
                    var discount  = await m_ProductPriceSchemeService.GetById(agentEntity.discount_id);
                    var packageEntity = await m_ProductPackageService.GetById(order.PackageId);
                    var price = packageEntity.LinePrice * discount.discount / 100;
                    score_money = order.PaymentAmount - order.ConnectCount * order.AccountCount * price;
                }
                

                var agnetScoreEntity = new AgentScoreEntity()
                {
                    agent_id = order.agent_id,
                    order_id = order.Id,
                    score_type = 1,
                    score_value = score_money,
                    remark = "客户购买产品" + order.Accounts,
                    agent_name = agentEntity.username,
                    op_user = order.UserName,
                    rest_amount1 = agentEntity.account,
                    rest_amount2 = agentEntity.account + score_money
                };

                agentEntity.account += score_money;

                await m_AgentScoreService.Add(agnetScoreEntity);
                await m_AgentUserService.Update(agentEntity);
            }


        }



        public async Task<ApiResult> Refund(int userId, string account)
        {
            using (await _mutex1.LockAsync())
            {
                var reason = "";
                if(account.Contains("-")){
                    string[] arrStr = account.Split('-');
                    account = arrStr[0];
                    reason = arrStr[1];
                }
                var accountInfo = await m_ProductAccountService.GetAccountInfo(account, userId);

                if (accountInfo == null)
                {
                    return new ApiResult(ResultCode.C_Illegal_Operation, "账户不存在");
                }
                if(accountInfo.ProductId == 20||accountInfo.ProductId == 21){
                    return new ApiResult(ResultCode.C_Illegal_Operation, "无极账号不允许退款");
                }
                if (accountInfo.AccountType == (int)AccountType.Origin)
                {
                    return new ApiResult(ResultCode.C_Illegal_Operation, "认证的账号不能退款");
                }
                if (accountInfo.EndTime < DateTime.Now)
                {
                    return new ApiResult(ResultCode.C_Illegal_Operation, "已经过期");
                }
                var pacageInfo = await m_ProductPackageService.GetById(accountInfo.PackageId);

                if (pacageInfo.DayCount == 1)
                {
                    return new ApiResult(ResultCode.C_Illegal_Operation, "天卡不能退款");
                }
                if (pacageInfo.IsTest == 1)
                {
                    return new ApiResult(ResultCode.C_Illegal_Operation, "测试卡不能退款");
                }
                var product = await this.m_ProductService.GetById(pacageInfo.ProductId);

                //折扣
                var refundDayPrice = 10.00M;
                var userEntity = await m_UserService.GetById(userId);
                if((userEntity.agent_id == 0||(userEntity.agent_id != 0 && userEntity.discount_id != 0)) && userEntity.discount_id >= 0){
                    //获取代理折扣
                    var discount  = await m_ProductPriceSchemeService.GetById(userEntity.discount_id);
                    if (discount != null){
                        refundDayPrice = (product.RefundDayPrice * discount.discount / 100).ToDecimal();
                    } else {
                        refundDayPrice = (product.RefundDayPrice).ToDecimal();
                    }
                } else {
                    var userPrice = await m_ProductUserPriceService.GetPackageUserPrice(pacageInfo.Id, userId);

                    refundDayPrice = (userPrice != null && userPrice.RefundDayPrice > 0 ? userPrice.RefundDayPrice : product.RefundDayPrice).ToDecimal();
                }


                

                var lastOrder = await GetLastOrderByAccount(account);

                var useDay = (int)Math.Ceiling((DateTime.Now - lastOrder.UpdateTime).TotalDays);
                var refundAmount = lastOrder.PaymentAmount / lastOrder.AccountCount - useDay * refundDayPrice * accountInfo.ConnectCount;
                refundAmount = refundAmount <= 0 ? 0 : refundAmount;

                //退款用户总消费修改
                userEntity.ConsumeAmount -= refundAmount;
                await m_UserService.Update(userEntity);

                var order = new ProductOrderEntity()
                {
                    AccountCount = 1,
                    ConnectCount = accountInfo.ConnectCount,
                    OrderName = accountInfo.ProductName,
                    OrderNo = GeneratOrderNO(userId, OrderType.Refund),
                    OrderState = OrderStatus.RequestRefund,
                    OrderType = OrderType.Refund,
                    PackageId = accountInfo.PackageId.Value,
                    PackageName = accountInfo.PackageName,
                    ProductId = accountInfo.ProductId.Value,
                    ProductName = accountInfo.ProductName,
                    PayType = PayType.None,
                    UserId = userId,
                    UserName = accountInfo.UserCode,
                    DayCount = (accountInfo.EndTime - DateTime.Now).Value.Days,
                    DayPrice = refundDayPrice,
                    Accounts = account,
                    PaymentAmount = lastOrder.PaymentAmount/ lastOrder.AccountCount,
                    RefundAmount = refundAmount,
                    RefundCount = 1,
                    Remark = "退款",
                    RefundReason = reason,
                    agent_id = accountInfo.agent_id
                };
                var time = (accountInfo.EndTime - DateTime.Now).Value;
                order.RefundRestTime = time.ToString(@"d\天hh\时mm\分");

                //短信内容
                var tpl_info = new Dictionary<string, string>(){
                    {"product",accountInfo.ProductName},
                    {"package",accountInfo.PackageName },
                    {"connect",accountInfo.ConnectCount.ToString() },
                    {"account",account },
                    {"resttime",order.RefundRestTime},
                };
                

               

                var againBuy = lastOrder.OrderType == OrderType.AgainBuy || lastOrder.OrderType == OrderType.AgainBuys;

                var laoyingXunFei = againBuy && lastOrder.ProductId == 4;
                if (product.AutoRefund == 1 && !laoyingXunFei)
                {
                    var refundRet = await this.m_AgentService.Refund(pacageInfo, accountInfo);
                    if (refundRet.Code == ResultCode.C_SUCCESS)
                    {
                        order.OrderState = OrderStatus.AutoRefundOver;
                    }
                }
                var amountInfo = new BaseInfo.Request.User.UpdateAmountRequest()
                {
                    Amount = order.RefundAmount,
                    OpAmountType = ScoreType.AccountRefund,
                    UserId = order.UserId,
                    AttchInfo = order.OrderNo,
                    OperateUserName = accountInfo.UserCode
                };
                var retAmount = await m_BaseUserService.UpdateAmount(amountInfo);
                accountInfo.EndTime = DateTime.Now;
                accountInfo.Status = AccountStatus.Refund;
                await m_ProductAccountService.Update(accountInfo);
                await this.Add(order);
                
                if(order.agent_id != 0 ){


                    var agentEntity = await m_AgentUserService.Query(m => m.id == order.agent_id).FirstOrDefaultAsync();
                    var agentScoreEntity = await m_AgentScoreService.Query(m => m.agent_id == order.agent_id && m.order_id == lastOrder.Id).FirstOrDefaultAsync();
                    
                    var deduct_money = agentScoreEntity.score_value / lastOrder.AccountCount;

                    //
                    
                    var re_money = 0.00M;
                    // if((userEntity.agent_id == 0||(userEntity.agent_id != 0 && userEntity.discount_id != 0)) && userEntity.discount_id >= 0){
                    // //获取代理折扣
                    //     var discount  = await m_ProductPriceSchemeService.GetById(agentEntity.discount_id);
                    //     re_money = useDay * (refundDayPrice - (product.RefundDayPrice).ToDecimal() * discount.discount / 100) * accountInfo.ConnectCount;
                    // } else {
                    //     var agentPriceEntity = await m_AgentPriceService.Query(m => m.agent_id == order.agent_id && m.package_id == order.PackageId).FirstOrDefaultAsync();
                    //     //使用天数 回补佣金
                    //     re_money = useDay * (refundDayPrice - agentPriceEntity.refund) * accountInfo.ConnectCount;
                    // }
                    if(agentEntity.discount_id != 0){
                        var discount  = await m_ProductPriceSchemeService.GetById(agentEntity.discount_id);
                        re_money = useDay * (refundDayPrice - (product.RefundDayPrice).ToDecimal() * discount.discount / 100) * accountInfo.ConnectCount;
                    }

                    //佣金
                    var score_money = agentEntity.account - deduct_money + re_money;

                    var agnetScoreEntity = new AgentScoreEntity()
                    {
                        agent_id = order.agent_id,
                        order_id = order.Id,
                        score_type = 2,
                        score_value = re_money - deduct_money,
                        remark = "客户退款" + account,
                        agent_name = agentEntity.username,
                        op_user = order.UserName,
                        rest_amount1 = agentEntity.account,
                        rest_amount2 = score_money
                    };

                    agentEntity.account = score_money;

                    await m_AgentScoreService.Add(agnetScoreEntity);
                    await m_AgentUserService.Update(agentEntity);
                }
                var managerEntity = await m_ManageService.GetById(userEntity.ManagerId.ToInt());
                if (managerEntity.TenantId == 1  && managerEntity.RoleId == 100 && DateTime.Now.Hour<23 && DateTime.Now.Hour>8) {
                    AliSmsService.Send("SMS_462300235", new { name = userEntity.ManagerName,phone=userEntity.Phone }, "聚IP", managerEntity.Phone);
                }
                return new ApiResult(1);
            }
        }

        public async Task<ApiResult> CaclRefund(int userId, string account)
        {
            var accountInfo = await m_ProductAccountService.GetAccountInfo(account, userId);
            
            if(accountInfo.Status == AccountStatus.Refund){
                return new ApiResult(ResultCode.C_Illegal_Operation, "此类帐号不允许退款");
            }

            if (accountInfo == null)
            {
                return new ApiResult(ResultCode.C_Illegal_Operation, "账户不存在");
            }
            if (accountInfo.EndTime < DateTime.Now)
            {
                return new ApiResult(ResultCode.C_Illegal_Operation, "已经过期");
            }
            var pacageInfo = await m_ProductPackageService.GetById(accountInfo.PackageId);

            if (pacageInfo.DayCount == 1)
            {
                return new ApiResult(ResultCode.C_Illegal_Operation, "天卡不能退款");
            }
            var product = await this.m_ProductService.GetById(pacageInfo.ProductId);



            //折扣
                var refundDayPrice = 10.00M;
                var userEntity = await m_UserService.GetById(userId);
                if((userEntity.agent_id == 0||(userEntity.agent_id != 0 && userEntity.discount_id != 0)) && userEntity.discount_id >= 0){
                    //获取代理折扣
                    var discount  = await m_ProductPriceSchemeService.GetById(userEntity.discount_id);
                     if (discount != null){
                        refundDayPrice = (product.RefundDayPrice * discount.discount / 100).ToDecimal();
                    } else {
                        refundDayPrice = (product.RefundDayPrice).ToDecimal();
                    }
                } else {
                    var userPrice = await m_ProductUserPriceService.GetPackageUserPrice(pacageInfo.Id, userId);

                    refundDayPrice = (userPrice != null && userPrice.RefundDayPrice > 0 ? userPrice.RefundDayPrice : product.RefundDayPrice).ToDecimal();
                }

            var lastOrder = await GetLastOrderByAccount(account);
            var useDay = (int)Math.Ceiling((DateTime.Now - lastOrder.UpdateTime).TotalDays);
            var RefundAmount = lastOrder.PaymentAmount / lastOrder.AccountCount - useDay * refundDayPrice * accountInfo.ConnectCount;
            RefundAmount = RefundAmount <= 0 ? 0 : RefundAmount;

            var time = (lastOrder.EndTime - DateTime.Now).Value;
            var RefundRestTime = time.ToString(@"d\天hh\时mm\分");

            var info = $"{accountInfo.Account}已使用{useDay}天，剩余{RefundRestTime}，可退金额{RefundAmount}元";
            return new ApiResult(new { RefundAmount, info });
        }


        /// <summary>
        ///  //当前账号最近一次付款记录
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public async Task<ProductOrderEntity> GetLastOrderByAccount(string account)
        {
            var accountOrders = await this.Query(m => m.OrderState == OrderStatus.Complete && m.Accounts.Contains(account)).ToListAsync();

            var lastAccountOrder = accountOrders.Where(m => m.Accounts.Split(",").Contains(account))
             .OrderByDescending(m => m.Id)
             .FirstOrDefault();
            return lastAccountOrder;
        }



        public async Task TestProcessOrderAccount()
        {

            var order = await this.GetById(5249);

            var accounts = order.Accounts.Split(',').ToList();

            var accountEntitys = await m_ProductAccountService.Query(p => accounts.Contains(p.Account)).ToListAsync();

            await accountEntitys.ForEachAsync(async accountEntity =>
            {
                Console.WriteLine(accountEntity.Account);
            });
        }

        public PageData<UserConsumeStatisticsModel> UserConsumeStatistics(int page, int limit,string userName)
        {
            string where = $" (OrderState=20 or OrderState=90)   ";

            if (userName.Has())
            {
                where += " and UserName=" + userName;
            }

            //当年
            string sql = $@" SELECT UserName,sum(PaymentAmount) Value FROM product_order  where {where}   GROUP BY UserName";

            //当天
            string sql1 = $@" SELECT UserName,sum(PaymentAmount) Value FROM product_order  where {where} and to_days(CreateTime)=to_days(now()) GROUP BY UserName";

            //当月
            string sql2 = $@" SELECT UserName,sum(PaymentAmount) Value FROM product_order  where {where} and DATE_FORMAT(CreateTime, '%Y%m' )=DATE_FORMAT(now( ) , '%Y%m' )  GROUP BY UserName";

            //当年
            string sql3 = $@" SELECT UserName,sum(PaymentAmount) Value FROM product_order  where {where} and YEAR(CreateTime)=YEAR(NOW())  GROUP BY UserName";


            string accountWhere = $" DeleteTag=0   ";
            if (userName.Has())
            {
                accountWhere += " and UserCode=" + userName;
            }
            //使用中账号
            string sql4 = $"select UserCode UserName, sum(ConnectCount) Value from product_account  where {accountWhere} and EndTime>now()  GROUP BY UserCode";

            //过期
            string sql5 = $"select UserCode UserName, sum(ConnectCount) Value from product_account  where {accountWhere} and  EndTime<=now()  GROUP BY UserCode";

            var data0 = m_DbContext.ExecSqlQuery<UserDataMode>(sql).ToList();
            var data1 = m_DbContext.ExecSqlQuery<UserDataMode>(sql1).ToList();
            var data2 = m_DbContext.ExecSqlQuery<UserDataMode>(sql2).ToList();
            var data3 = m_DbContext.ExecSqlQuery<UserDataMode>(sql3).ToList();
            var data4 = m_DbContext.ExecSqlQuery<UserDataMode>(sql4).ToList();
            var data5 = m_DbContext.ExecSqlQuery<UserDataMode>(sql5).ToList();

            PageData<UserConsumeStatisticsModel> ret = new PageData<UserConsumeStatisticsModel>()
            {
                RowCount = data0.Count
            };
            if (page <= 1) page = 1;
            var data = data0.Skip((page - 1) * limit).Take(limit);
            foreach (var item in data)
            {
                ret.List.Add(new UserConsumeStatisticsModel()
                {
                    UserName = item.UserName,
                    TotalAmount = item.Value,
                    YearAmount = data3.FirstOrDefault(m => m.UserName == item.UserName)?.Value,
                  //  MonthAmount = data2.FirstOrDefault(m => m.UserName == item.UserName)?.Value,
                    DayAmount = data1.FirstOrDefault(m => m.UserName == item.UserName)?.Value,
                    UsingAccountCount = Convert.ToInt32(data4.FirstOrDefault(m => m.UserName == item.UserName)?.Value),
                    ExpirdAccountCount = Convert.ToInt32(data5.FirstOrDefault(m => m.UserName == item.UserName)?.Value),
                });
            }
            return ret;
        }

        public PageData<UserConsumeStatisticsModel> UserConsumeStatistics1(int page, int limit, string userName,DateTime? bTime1,DateTime? eTime1,DateTime? bTime2,DateTime? eTime2,int managerId=0)
        {
            if (!bTime1.HasValue || !eTime1.HasValue)
            {
                bTime1 = DateTime.Now.LastDayOfPrdviousMonth();
                eTime1 = new DateTime(bTime1.Value.Year, bTime1.Value.Month, DateTime.Now.Day);
            }

            if (!bTime2.HasValue || !eTime2.HasValue)
            {
                bTime2 = DateTime.Now.FirstDayOfMonth();
                eTime2 = DateTime.Now;
            }
            

            string where = $" (OrderState=20 or OrderState=90)   ";

            //上月月
            var lastMonthWhere = where + $" and CreateTime> '{bTime1.Value.ToString("yyyy-MM-dd")}' and CreateTime <'{eTime1.Value.ToString("yyyy-MM-dd")}'";
            string sql1 = $@" SELECT UserName,sum(PaymentAmount) Value FROM product_order  where {lastMonthWhere}  GROUP BY UserName";
            var data1 = m_DbContext.ExecSqlQuery<UserDataMode>(sql1).ToList();

            //当月
            var currentMonthWhere = where + $" and CreateTime> '{bTime2.Value.ToString("yyyy-MM-dd")}' and CreateTime <'{eTime2.Value.ToString("yyyy-MM-dd")}'";
            string sql2 = $@" SELECT UserName,sum(PaymentAmount) Value FROM product_order  where {currentMonthWhere} GROUP BY UserName";
            var data2 = m_DbContext.ExecSqlQuery<UserDataMode>(sql2).ToList();

            var data = data1.Select(m=>m.UserName).Union(data2.Select(m=>m.UserName));


            //PageData<UserConsumeStatisticsModel> ret = new PageData<UserConsumeStatisticsModel>()
            //{
            //    RowCount = userList.RowCount
            //};           
            //foreach (var item in userList.List)
            //{
            //    ret.List.Add(new UserConsumeStatisticsModel()
            //    {
            //        UserInfo=item,
            //        UserName = item.LoginCode,
            //        CreateTime=item.CreateTime,                   
            //        // YearAmount = data3.FirstOrDefault(m => m.UserName == item.UserName)?.Value,
            //        PrevMonthAmount = Convert.ToDecimal(data1.FirstOrDefault(m => m.UserName == item.LoginCode)?.Value),
            //        MonthAmount = Convert.ToDecimal(data2.FirstOrDefault(m => m.UserName == item.LoginCode)?.Value),
            //       // DayAmount = data1.FirstOrDefault(m => m.UserName == item.LoginCode)?.Value,
            //        UsingAccountCount = Convert.ToInt32(data3.FirstOrDefault(m => m.UserName == item.LoginCode)?.Value),
            //        ExpirdAccountCount = Convert.ToInt32(data4.FirstOrDefault(m => m.UserName == item.LoginCode)?.Value),                  
            //    });
            //}
            //return ret;          

           var pageData= data.Skip((page - 1) * limit).Take(limit);

            var inUser= $"{string.Join(',', pageData.Select(m => $"'{m}'"))}";
            string accountWhere = $" DeleteTag=0   ";
            if (userName.Has())
            {
                accountWhere += " and UserCode=" + userName;
            }
            accountWhere += $" and UserCode in ({inUser})";

            //使用中账号
            string sql3 = $"select UserCode UserName, sum(ConnectCount) Value from product_account  where {accountWhere} and EndTime>now()  and AccountType!=200 GROUP BY UserCode";
            var data3 = m_DbContext.ExecSqlQuery<UserDataMode>(sql3).ToList();

            //过期
            string sql4 = $"select UserCode UserName, sum(ConnectCount) Value from product_account  where {accountWhere} and  EndTime<=now() and AccountType!=200  GROUP BY UserCode";
            var data4 = m_DbContext.ExecSqlQuery<UserDataMode>(sql4).ToList();


            var userList = default(PageData<UserEntity>);
            //用户
            if (userName.Has())
            {
                where += " and UserName=" + userName;
                userList = m_UserService.PageDesc(1, limit, m => m.LoginCode == userName && (managerId == 0 || m.ManagerId == managerId), true, m => m.Id).Result;
            }
            else
            {
                userList = m_UserService.PageDesc(1, limit, m => (managerId == 0 || m.ManagerId == managerId)&& pageData.Contains(m.LoginCode), true, m => m.Id).Result;
            }

            PageData<UserConsumeStatisticsModel> ret = new PageData<UserConsumeStatisticsModel>()
            {
                RowCount = data.Count()
            };

            foreach (var item in userList.List)
            {
                ret.List.Add(new UserConsumeStatisticsModel()
                {
                    UserInfo = item,
                    UserName = item.LoginCode,
                    CreateTime = item.CreateTime,
                    // YearAmount = data3.FirstOrDefault(m => m.UserName == item.UserName)?.Value,
                    PrevMonthAmount = Convert.ToDecimal(data1.FirstOrDefault(m => m.UserName == item.LoginCode)?.Value),
                    MonthAmount = Convert.ToDecimal(data2.FirstOrDefault(m => m.UserName == item.LoginCode)?.Value),
                    // DayAmount = data1.FirstOrDefault(m => m.UserName == item.LoginCode)?.Value,
                    UsingAccountCount = Convert.ToInt32(data3.FirstOrDefault(m => m.UserName == item.LoginCode)?.Value),
                    ExpirdAccountCount = Convert.ToInt32(data4.FirstOrDefault(m => m.UserName == item.LoginCode)?.Value),
                });
            }
            return ret;

        }

        public PageData<UserConsumeStatisticsModel> UserConsumeStatistics(int page, int limit, string userName, DateTime? bTime1, DateTime? eTime1, DateTime? bTime2, DateTime? eTime2, int managerId = 0, string sortLable = "", int sortOrder = 0,string profile="")
        {
            if (!bTime1.HasValue || !eTime1.HasValue)
            {
                bTime1 = DateTime.Now.LastDayOfPrdviousMonth();
                eTime1 = new DateTime(bTime1.Value.Year, bTime1.Value.Month, DateTime.Now.Day);
            }

            if (!bTime2.HasValue || !eTime2.HasValue)
            {
                bTime2 = DateTime.Now.FirstDayOfMonth();
                eTime2 = DateTime.Now;
            }


            string where = $" (OrderState=20 or OrderState=90)   ";

            //上月月
            var lastMonthWhere = where + $" and CreateTime> '{bTime1.Value.ToString("yyyy-MM-dd")}' and CreateTime <'{eTime1.Value.ToString("yyyy-MM-dd")}'";
            string sql1 = $@" SELECT UserName,sum(PaymentAmount) Value FROM product_order  where {lastMonthWhere}  GROUP BY UserName";
            var data1 = m_DbContext.ExecSqlQuery<UserDataMode>(sql1).ToList();

            //当月
            var currentMonthWhere = where + $" and CreateTime> '{bTime2.Value.ToString("yyyy-MM-dd")}' and CreateTime <'{eTime2.Value.ToString("yyyy-MM-dd")}'";
            string sql2 = $@" SELECT UserName,sum(PaymentAmount) Value FROM product_order  where {currentMonthWhere} GROUP BY UserName";
            var data2 = m_DbContext.ExecSqlQuery<UserDataMode>(sql2).ToList();

            var data = data1.Select(m => m.UserName).Union(data2.Select(m => m.UserName));
            

            var inUser = $"{string.Join(',', data.Select(m => $"'{m}'"))}";
            string accountWhere = $" DeleteTag=0   ";
            if (userName.Has())
            {
                accountWhere += " and UserCode=" + userName;
            }
            accountWhere += $" and UserCode in ({inUser})";

            //使用中账号
            string sql3 = $"select UserCode UserName, sum(ConnectCount) Value from product_account  where {accountWhere} and EndTime>now()  and AccountType!=200 GROUP BY UserCode";
            var data3 = m_DbContext.ExecSqlQuery<UserDataMode>(sql3).ToList();

            //过期
            string sql4 = $"select UserCode UserName, sum(ConnectCount) Value from product_account  where {accountWhere} and  EndTime<=now() and AccountType!=200  GROUP BY UserCode";
            var data4 = m_DbContext.ExecSqlQuery<UserDataMode>(sql4).ToList();


            var userList = new List<UserEntity>();// 
            //用户
            if (userName.Has())
            {
                where += " and UserName=" + userName;
                var retUser = m_UserService.Query(m => m.LoginCode == userName && (managerId == 0 || m.ManagerId == managerId)).FirstOrDefault();
                userList.Add(retUser);
            }
            else
            {
                userList = m_UserService.Query(m => (managerId == 0 || m.ManagerId == managerId) && data.Contains(m.LoginCode), true).ToList();
            }

            var retData = new List<UserConsumeStatisticsModel>();

            foreach (var item in userList)
            {
                if (item.Profile == null || item.Profile == "0") item.Profile = "暂无";
                retData.Add(new UserConsumeStatisticsModel()
                {
                    UserInfo = item,
                    UserName = item.LoginCode,
                    CreateTime = item.CreateTime,
                    // YearAmount = data3.FirstOrDefault(m => m.UserName == item.UserName)?.Value,
                    PrevMonthAmount = Convert.ToDecimal(data1.FirstOrDefault(m => m.UserName == item.LoginCode)?.Value),
                    MonthAmount = Convert.ToDecimal(data2.FirstOrDefault(m => m.UserName == item.LoginCode)?.Value),
                    // DayAmount = data1.FirstOrDefault(m => m.UserName == item.LoginCode)?.Value,
                    UsingAccountCount = Convert.ToInt32(data3.FirstOrDefault(m => m.UserName == item.LoginCode)?.Value),
                    ExpirdAccountCount = Convert.ToInt32(data4.FirstOrDefault(m => m.UserName == item.LoginCode)?.Value),
                });
            }
            if (profile.Has())
            {
                retData = retData.Where(m=>m.UserInfo.Profile==profile).ToList();
            }

            if (sortLable == "PrevMonthAmount")
            {
                retData = sortOrder == 0 ? retData.OrderBy(m => m.PrevMonthAmount).ToList() : retData.OrderByDescending(m => m.PrevMonthAmount).ToList();
            }
            if (sortLable == "MonthAmount")
            {
                retData = sortOrder == 0 ? retData.OrderBy(m => m.MonthAmount).ToList() : retData.OrderByDescending(m => m.MonthAmount).ToList();
            }

            if (sortLable == "AddAmount")
            {
                retData = sortOrder == 0 ? retData.OrderBy(m => m.AddAmount).ToList() : retData.OrderByDescending(m => m.AddAmount).ToList();
            }

            if (sortLable == "UsingAccountCount")
            {
                retData = sortOrder == 0 ? retData.OrderBy(m => m.UsingAccountCount).ToList() : retData.OrderByDescending(m => m.UsingAccountCount).ToList();
            }

            if (sortLable == "ExpirdAccountCount")
            {
                retData = sortOrder == 0 ? retData.OrderBy(m => m.ExpirdAccountCount).ToList() : retData.OrderByDescending(m => m.ExpirdAccountCount).ToList();
            }

            if (sortLable == "TotalAccountCount")
            {
                retData = sortOrder == 0 ? retData.OrderBy(m => m.TotalAccountCount).ToList() : retData.OrderByDescending(m => m.TotalAccountCount).ToList();
            }

            var pageData = retData.Skip((page - 1) * limit).Take(limit).ToList();
            PageData<UserConsumeStatisticsModel> ret = new PageData<UserConsumeStatisticsModel>()
            {
                RowCount = retData.Count(),
                List = pageData
            };

            return ret;

        }


        public List<UserConsumeStatisticsModel> ExportUserConsumeStatisticsData(string userName, DateTime? bTime1, DateTime? eTime1, DateTime? bTime2, DateTime? eTime2, int managerId = 0, string sortLable = "", int sortOrder = 0, string profile = "")
        {
            if (!bTime1.HasValue || !eTime1.HasValue)
            {
                bTime1 = DateTime.Now.LastDayOfPrdviousMonth();
                eTime1 = new DateTime(bTime1.Value.Year, bTime1.Value.Month, DateTime.Now.Day);
            }

            if (!bTime2.HasValue || !eTime2.HasValue)
            {
                bTime2 = DateTime.Now.FirstDayOfMonth();
                eTime2 = DateTime.Now;
            }


            string where = $" (OrderState=20 or OrderState=90)   ";

            //上月月
            var lastMonthWhere = where + $" and CreateTime> '{bTime1.Value.ToString("yyyy-MM-dd")}' and CreateTime <'{eTime1.Value.ToString("yyyy-MM-dd")}'";
            string sql1 = $@" SELECT UserName,sum(PaymentAmount) Value FROM product_order  where {lastMonthWhere}  GROUP BY UserName";
            var data1 = m_DbContext.ExecSqlQuery<UserDataMode>(sql1).ToList();

            //当月
            var currentMonthWhere = where + $" and CreateTime> '{bTime2.Value.ToString("yyyy-MM-dd")}' and CreateTime <'{eTime2.Value.ToString("yyyy-MM-dd")}'";
            string sql2 = $@" SELECT UserName,sum(PaymentAmount) Value FROM product_order  where {currentMonthWhere} GROUP BY UserName";
            var data2 = m_DbContext.ExecSqlQuery<UserDataMode>(sql2).ToList();

            var data = data1.Select(m => m.UserName).Union(data2.Select(m => m.UserName));


            var inUser = $"{string.Join(',', data.Select(m => $"'{m}'"))}";
            string accountWhere = $" DeleteTag=0   ";
            if (userName.Has())
            {
                accountWhere += " and UserCode=" + userName;
            }
            accountWhere += $" and UserCode in ({inUser})";

            //使用中账号
            string sql3 = $"select UserCode UserName, sum(ConnectCount) Value from product_account  where {accountWhere} and EndTime>now()  and AccountType!=200 GROUP BY UserCode";
            var data3 = m_DbContext.ExecSqlQuery<UserDataMode>(sql3).ToList();

            //过期
            string sql4 = $"select UserCode UserName, sum(ConnectCount) Value from product_account  where {accountWhere} and  EndTime<=now() and AccountType!=200  GROUP BY UserCode";
            var data4 = m_DbContext.ExecSqlQuery<UserDataMode>(sql4).ToList();


            var userList = new List<UserEntity>();// 
            //用户
            if (userName.Has())
            {
                where += " and UserName=" + userName;
                var retUser = m_UserService.Query(m => m.LoginCode == userName && (managerId == 0 || m.ManagerId == managerId)).FirstOrDefault();
                userList.Add(retUser);
            }
            else
            {
                userList = m_UserService.Query(m => (managerId == 0 || m.ManagerId == managerId) && data.Contains(m.LoginCode), true).ToList();
            }

            var retData = new List<UserConsumeStatisticsModel>();

            foreach (var item in userList)
            {
                if (item.Profile == null || item.Profile == "0") item.Profile = "暂无";
                retData.Add(new UserConsumeStatisticsModel()
                {
                    UserInfo = item,
                    UserName = item.LoginCode,
                    CreateTime = item.CreateTime,
                    // YearAmount = data3.FirstOrDefault(m => m.UserName == item.UserName)?.Value,
                    PrevMonthAmount = Convert.ToDecimal(data1.FirstOrDefault(m => m.UserName == item.LoginCode)?.Value),
                    MonthAmount = Convert.ToDecimal(data2.FirstOrDefault(m => m.UserName == item.LoginCode)?.Value),
                    // DayAmount = data1.FirstOrDefault(m => m.UserName == item.LoginCode)?.Value,
                    UsingAccountCount = Convert.ToInt32(data3.FirstOrDefault(m => m.UserName == item.LoginCode)?.Value),
                    ExpirdAccountCount = Convert.ToInt32(data4.FirstOrDefault(m => m.UserName == item.LoginCode)?.Value),
                });
            }
            if (profile.Has())
            {
                retData = retData.Where(m => m.UserInfo.Profile == profile).ToList();
            }

            if (sortLable == "PrevMonthAmount")
            {
                retData = sortOrder == 0 ? retData.OrderBy(m => m.PrevMonthAmount).ToList() : retData.OrderByDescending(m => m.PrevMonthAmount).ToList();
            }
            if (sortLable == "MonthAmount")
            {
                retData = sortOrder == 0 ? retData.OrderBy(m => m.MonthAmount).ToList() : retData.OrderByDescending(m => m.MonthAmount).ToList();
            }

            if (sortLable == "AddAmount")
            {
                retData = sortOrder == 0 ? retData.OrderBy(m => m.AddAmount).ToList() : retData.OrderByDescending(m => m.AddAmount).ToList();
            }

            if (sortLable == "UsingAccountCount")
            {
                retData = sortOrder == 0 ? retData.OrderBy(m => m.UsingAccountCount).ToList() : retData.OrderByDescending(m => m.UsingAccountCount).ToList();
            }

            if (sortLable == "ExpirdAccountCount")
            {
                retData = sortOrder == 0 ? retData.OrderBy(m => m.ExpirdAccountCount).ToList() : retData.OrderByDescending(m => m.ExpirdAccountCount).ToList();
            }

            if (sortLable == "TotalAccountCount")
            {
                retData = sortOrder == 0 ? retData.OrderBy(m => m.TotalAccountCount).ToList() : retData.OrderByDescending(m => m.TotalAccountCount).ToList();
            }            

            return retData;

        }



        public List<ManagerSellStatisticModel> SellAmountStatistics(DateTime? bTime, DateTime? eTime)
        {
            string amountWhere = $" (OrderState=20 or OrderState=90) ";
            if (bTime.HasValue && eTime.HasValue)
            {

                amountWhere += $" and  b.CreateTime>'{bTime.Value.ToString("yyyy-MM-dd")}' and b.CreateTime<'{eTime.Value.ToString("yyyy-MM-dd")}'";
            }


            string sqlAmount = $@"select m.RealName,sum(b.orderamount) Amount from product_order  b

INNER JOIN  `user` a on a.Id=b.userId

LEFT JOIN manager  m on  a.managerId=m.id

where {amountWhere}

group by m.RealName";
            var amountInfo = m_DbContext.ExecSqlQuery<ManagerSellStatisticModel>(sqlAmount).ToList();


            return amountInfo;
        }


        public List<ManagerSellStatisticModel> UserCountStatistics(DateTime? bTime, DateTime? eTime)
        {          
            string userCountWhere = "";
            if (bTime.HasValue && eTime.HasValue)
            {
                userCountWhere = $"where a.CreateTime>'{bTime.Value.ToString("yyyy-MM-dd")}' and a.CreateTime<'{eTime.Value.ToString("yyyy-MM-dd")}'";

            }


            string sql = $@"
SELECT m.RealName,count(1) UserCount from `user` a 
LEFT JOIN manager  m on  a.managerId=m.id
{userCountWhere}
group by m.RealName";
            var userCountInfo = m_DbContext.ExecSqlQuery<ManagerSellStatisticModel>(sql).ToList();

            return userCountInfo;
        }



    }

    class AccountEntityEq : IEqualityComparer<ProductAccountEntity>
    {
        public bool Equals(ProductAccountEntity x, ProductAccountEntity y)
        {
            return x.Account == y.Account;
        }

        public int GetHashCode(ProductAccountEntity obj)
        {
            return 0;
        }
    }
}
