using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XYY.Core.Standard.Data.Infrastructure;
using XYY.Core.Standard.Data.Redis;
using XYY.Service.Standard.Finance.Charging.Base;
using XYY.Service.Standard.Finance.Charging.Express;
using Dapper;
using XYY.Core.Standard.Mvc;
using System.Threading;

namespace XYY.Service.Standard.Finance.Charging.EUExchange
{
    /// <summary>
    /// 欧盟税费计算，需要传入申报总值，国家，计费时间
    /// </summary>
    public interface IEUExchangeService : IChargesService<ExpressFeechargesModel>
    {
        Task<ApiJsonModel> RefreshRedisCache();
    }
    public class EUExchangeService : IEUExchangeService
    {
        IUnitOfWork _unitOfWork;
        IDatabase db;
        IServer server;
        public EUExchangeService(RedisHelper helper, IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
            if (_unitOfWork == null)
                throw new EUExchangeException(EUExchangeException.DB_ConnectionError);
            this.db = helper.GetDatabase();
            server = helper.GetServer();
        }

        public async Task<ApiJsonModel> Charges(ExpressFeechargesModel t)
        {
            ThreadPool.SetMinThreads(200, 200);
            if (t.HasIOSS)
                return ApiJsonModel.Error("客户包含IOSS，不计费");
            if (t.PublicExpressId == 29)
                return ApiJsonModel.Error("");
            var fb = new EUExchangeBase(t.CountryCode, t.TransactionTime, 0);
            var set = await db.SortedSetRangeByScoreAsync(fb.Key, 0, fb.DateTimeVersion, order: Order.Descending, take: 1);
            if (set.Length == 0)
            {
                return ApiJsonModel.Error("未设置欧盟税率");
            }
            else
            {
                var fee = (double)set[0];
                t.AmountinOriginalCurrency = t.GoodsDeclared * (decimal)fee;
                t.Currency = "EUR";
                t.Remark = fee.ToString();
                return ApiJsonModel.OK(t);
            }
        }

        public async Task<ApiJsonModel> RefreshRedisCache()
        {
            try
            {
                ThreadPool.SetMinThreads(200, 200);
                #region 操作
                long deleteCount = await db.DeleteScanKey( "EUExchange*");
                string sql = @"select * from Finance_EUExchangeRateDetail(nolock)";
                var data = await _unitOfWork.QueryBySqlAsync<dynamic>(sql);
                foreach (var item in data)
                {
                    EUExchangeBase Base = new EUExchangeBase(item.ReceiveryCountryCode, item.StartTime, (double)item.Rate);
                    db.SortedSetAdd(Base.Key, Base.Rate, Base.DateTimeVersion);
                }
                #endregion
            }
            catch (Exception ex)
            {
                return ApiJsonModel.Error(ex.Message);
            }
            return ApiJsonModel.OK("成功");

        }
    }
}
