using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XYY.Common.Standard;
using XYY.Core.Standard.Mvc;
using XYY.Data.Standard.Finance;
using XYY.Model.Standard.Finance;
using XYY.Model.Standard.User;
using XYY.Model.Standard.User.Enums;
using XYY.Service.Standard.Customer;
using XYY.Service.Standard.Finance.RedisCache;

namespace XYY.Service.Standard.Finance
{
    /// <summary>
    /// 导入补款
    /// </summary>
    public interface IFinance_Customer_SupplementService
    {
        Task InputFinanceCustomerSupplements(FinanceCustomerSupplementOrDeductionType type, List<Finance_Customer_Supplement> supplements);

        Task<PageResult<ViewFinance_Customer_Supplement>> GetPageResult(QueryModel queryModel);

        Task Add(Finance_Customer_Supplement fcs);

        Task Edit(Finance_Customer_Supplement fcs);

        Task Remave(Finance_Customer_Supplement fcs);

        Task<List<Finance_Customer_Supplement>> Load_Customer_Supplement(int customerId, FinanceCustomerSupplementOrDeductionType financeCustomerSupplementType, string month);
        Task<List<Finance_Customer_Supplement>> Load_Customer_Supplement(int customerId, FinanceCustomerSupplementOrDeductionType financeCustomerSupplementType, DateTime start, DateTime end);
    }

    public class Finance_Customer_SupplementService : IFinance_Customer_SupplementService
    {
        private IFinance_Customer_SupplementRepository repository;
        private ICustomerService customerService;
        public Finance_Customer_SupplementService(IFinance_Customer_SupplementRepository repository, ICustomerService customerService)
        {
            this.repository = repository;
            this.customerService = customerService;
        }

        public async Task Add(Finance_Customer_Supplement fcs)
        {
            await this.repository.InsertAsync(fcs);
        }

        public async Task Edit(Finance_Customer_Supplement fcs)
        {
            await this.repository.UpdateAsync(fcs);
        }

        public async Task<PageResult<ViewFinance_Customer_Supplement>> GetPageResult(QueryModel queryModel)
        {
            return await this.repository.GetPageResult(queryModel);
        }

        private void AddMQ(List<Finance_Customer_SupplementNew> supplementNews)
        {
            string baseUrl = $"http://localhost:22707/api/NewCustomerFeeTest/AddSupplementMQ";
            var client = new RestSharp.RestClient(baseUrl);
            var request = new RestSharp.RestRequest();
            request.AddJsonBody(supplementNews);
            var response = client.Execute(request,RestSharp.Method.POST);
            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                throw new Exception(response.ErrorMessage ?? response.Content);
            }
        }

        private FeeQuerResultSimple getRemoteFee(string code)
        {
            string baseUrl = $"http://localhost:22707/api/NewCustomerFeeTest/GetFedexOrDHLRemote?code={code}";
            var client = new RestSharp.RestClient(baseUrl);
            var request = new RestSharp.RestRequest();
            var response = client.Execute(request);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var l = Newtonsoft.Json.JsonConvert.DeserializeObject<FeeQuerResultSimple>(response.Content);
                return l;
            }
            else
            {
                throw new Exception(response.ErrorMessage ?? response.Content);
            }
        }

        public class Finance_Customer_SupplementNew : Finance_Customer_Supplement
        {
            public List<FeeItemDto> feeItemDtos { get; set; }
        }

        public async Task InputFinanceCustomerSupplements(FinanceCustomerSupplementOrDeductionType type, List<Finance_Customer_Supplement> supplements)
        {
            var fedexRemote = getRemoteFee("Fedex");
            var dhlRemote = getRemoteFee("DHL");


            //写入DB
            supplements = await this.repository.GetInputFinanceCustomerSupplements(supplements);
            //写入MQ
            List<Finance_Customer_SupplementNew> supplementNews = new List<Finance_Customer_SupplementNew>();
            foreach (var supplement in supplements)
            {
                supplement.Guid = Guid.NewGuid().ToString();
                Finance_Customer_SupplementNew supplementNew = supplement.Copy<Finance_Customer_SupplementNew>();
                supplementNews.Add(supplementNew);
                if (supplement.FeeString.Contains("燃油"))
                {
                    if (supplement.CreateOrderChannelId == 48)
                    {
                        supplement.Fee = fedexRemote.totalFee;
                        supplementNew.Fee = fedexRemote.totalFee;
                        supplementNew.feeItemDtos = fedexRemote.feeItemDtoList;

                    }
                    else if (supplement.CreateOrderChannelId == 50)
                    {
                        supplement.Fee = dhlRemote.totalFee;
                        supplementNew.Fee = dhlRemote.totalFee;
                        supplementNew.feeItemDtos = dhlRemote.feeItemDtoList;
                    }
                };
            }
            await this.repository.BulkToDBAsync(supplements);
            AddMQ(supplementNews);
        }


        public async Task<List<Finance_Customer_Supplement>> Load_Customer_Supplement(int customerId, FinanceCustomerSupplementOrDeductionType financeCustomerSupplementType, string month)
        {
            string sql = $@"select * from Finance_Customer_Supplement(nolock) where customerId={customerId} and financeCustomerSupplementType={financeCustomerSupplementType.GetValue()} and month='{month}'";
            return (await this.repository.QueryBySqlAsync(sql)).ToList();
        }

        public async Task<List<Finance_Customer_Supplement>> Load_Customer_Supplement(int customerId, FinanceCustomerSupplementOrDeductionType financeCustomerSupplementType, DateTime start, DateTime end)
        {
            string sql = $@"select * from Finance_Customer_Supplement(nolock) 
                                where customerId={customerId} and financeCustomerSupplementType={financeCustomerSupplementType.GetValue()}
                                    and createtime between '{start}' and '{end.AddDays(1)}'";
            return (await this.repository.QueryBySqlAsync(sql)).ToList();

        }

        public async Task Remave(Finance_Customer_Supplement fcs)
        {
            await this.repository.DeleteByIdAsync(fcs.Id);
        }
    }
}
