using AlibabaCloud.SDK.Dingtalkim_1_0.Models;
using AspectCore.DynamicProxy;
using Nest;
using Org.BouncyCastle.Ocsp;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XYY.Common.Standard;
using XYY.Core.Standard.ExcelHelper.MSExcelHelper;
using XYY.Data.Standard.Finance;
using XYY.Model.Standard.Finance;
using static XYY.Data.Standard.Finance.Finance_Customer_SupplementRepository;

namespace XYY.Service.Standard.Finance
{
    public interface IFinance_ServiceSurchargeService
    {
        Task AddServiceSurchargeService(Finance_ServiceSurcharge surcharge);

        Task UpdateServiceSurchargeService(Finance_ServiceSurcharge surcharge);

        Task<List<Finance_ServiceSurcharge>> QueryServiceSurchargeService(int expresssId);
        byte[] DownloadServiceSurchargeService(int expresssId);
        Task<List<Finance_ServiceSurchargeLog>> GetLogs(int Id);
        Task<List<View_Quotation>> ConcertToQuotation(int ExpressId, byte[] data);
        Task AddServiceSurcharge(Finance_QutationApprove approveQuotation);
        Task<List<Finance_ServiceSurchargeDetailDto>> QueryDetail(QueryModel query);
        Task<List<Logistics_Fee_Other>> GetFeeOther(QueryModel query);
    }

    public class Finance_ServiceSurchargeService : IFinance_ServiceSurchargeService
    {
        IFinance_ServiceSurchargeRepository _serviceSurchargeRepository;
        IFinance_ServiceSurchargeDetailRepository _serviceSurchargeDetailRepository;

        public Finance_ServiceSurchargeService(IFinance_ServiceSurchargeRepository serviceSurchargeRepository,
            IFinance_ServiceSurchargeDetailRepository serviceSurchargeDetailRepository = null)
        {
            _serviceSurchargeRepository = serviceSurchargeRepository;
            _serviceSurchargeDetailRepository = serviceSurchargeDetailRepository;
        }

        public async Task AddServiceSurchargeService(Finance_ServiceSurcharge surcharge)
        {
            MSExcelHelper helper = new MSExcelHelper();

            if (surcharge.ExpressId == 0)
                throw new Exception("未传入渠道Id");

            var ver = (await _serviceSurchargeRepository.QueryAsync(x => x.ExpressId == surcharge.ExpressId))?.FirstOrDefault()?.Versions ?? 0;
            ver++;
            var id = (int)(await _serviceSurchargeRepository.InsertAsync(surcharge));
            var list = helper.LoadDataByUrl<InputInfo, Finance_ServiceSurchargeDetail>(surcharge.FileUrl);
            if (list.Count == 0)
                throw new Exception("费用明细不可为空");
            list.ForEach(x =>
            {
                x.ExpressId = surcharge.ExpressId;
                x.EnableTime = surcharge.EnableTime;
                x.BaseId = id;
                x.IsDelete = false;
                x.CreateTime = DateTime.Now;
            });
            await _serviceSurchargeDetailRepository.BulkToDBAsync(list);
        }

        public async Task<List<Finance_ServiceSurchargeLog>> GetLogs(int Id)
        {
            return await _serviceSurchargeRepository.GetLogs(Id);
        }

        public byte[] DownloadServiceSurchargeService(int expresssId)
        {
            MSExcelHelper helper = new MSExcelHelper();
            return helper.OutDataAsByte<InputInfo, Finance_ServiceSurchargeDetail>(new List<Finance_ServiceSurchargeDetail>());
        }

        public async Task<List<Finance_ServiceSurcharge>> QueryServiceSurchargeService(int expresssId)
        {
            var list = (await _serviceSurchargeRepository.QueryAsync(x => x.ExpressId == expresssId)).ToList();
            return list;
        }

        public async Task UpdateServiceSurchargeService(Finance_ServiceSurcharge surcharge)
        {
            var d = (await _serviceSurchargeRepository.GetAsync(surcharge.Id));
            if (d == null)
                throw new Exception("找不到相应的主表");
            if (!string.IsNullOrEmpty(surcharge.FileUrl) && d.FileUrl != surcharge.FileUrl)
            {
                d.FileUrl = surcharge.FileUrl;
                //重新处理明细
                MSExcelHelper helper = new MSExcelHelper();
                var list = helper.LoadDataByUrl<InputInfo, Finance_ServiceSurchargeDetail>(surcharge.FileUrl);
                await _serviceSurchargeDetailRepository.UpdateByConditionAsync(x => x.BaseId == surcharge.Id && x.IsDelete == false, new
                {
                    IsDelete = true
                });
                list.ForEach(x =>
                {
                    x.ExpressId = d.ExpressId;
                    x.EnableTime = surcharge.EnableTime;
                    x.BaseId = d.Id;
                    x.IsDelete = false;
                    x.CreateTime = DateTime.Now;
                });
                await _serviceSurchargeDetailRepository.BulkToDBAsync(list);
            }

            if (d.EnableTime != surcharge.EnableTime
                && d.EnableTime < DateTime.Now)
            {
                d.EnableTime = surcharge.EnableTime;
                //重算流程
            }

            await _serviceSurchargeRepository.UpdateAsync(d);
        }

        public async Task<List<View_Quotation>> ConcertToQuotation(int ExpressId, byte[] data)
        {
            MSExcelHelper helper = new MSExcelHelper();
            var list = helper.LoadDataByByte<ServiceSurchargeDetailMapping, Finance_ServiceSurchargeDetail>(data);
            List<View_Quotation> quotations = new List<View_Quotation>();
            //获取分区对应数据
            var zoneInfo = await _serviceSurchargeRepository.GetZoneInfos(ExpressId);
            foreach (var item in list)
            {
                var tempData = zoneInfo.Where(x => x.zone == item.CountryCode).ToList();
                if (tempData != null && tempData.Count > 0)
                {
                    foreach (var z in tempData)
                    {
                        View_Quotation quotation = new View_Quotation()
                        {
                            起重 = item.FristWeight.ToString(),
                            起重费 = item.FristFee.ToString(),
                            续重 = item.ContinuedWeight.ToString(),
                            续重费 = item.ContinuedFee.ToString(),
                            操作费 = item.CountryCode.ToString(),
                            国家 = z.code,
                        };
                        quotations.Add(quotation);
                    }
                }
            }
            return quotations;
        }
        /// <summary>
        /// 通过审批添加附加费
        /// </summary>
        /// <param name="approveQuotation"></param>
        /// <returns></returns>
        public async Task AddServiceSurcharge(Finance_QutationApprove approveQuotation)
        {
            MSExcelHelper helper = new MSExcelHelper();

            if (approveQuotation.ExpressId == 0)
                throw new Exception("附加费未传入渠道Id");

            var list = helper.LoadDataByUrl<ServiceSurchargeDetailMapping, Finance_ServiceSurchargeDetail>(approveQuotation.UploadedFileUrl);
            if (list.Count == 0)
                throw new Exception("附加费，费用明细不可为空");
            List<Finance_ServiceSurchargeDetail> details = new List<Finance_ServiceSurchargeDetail>();
            //获取分区对应数据
            var zoneInfo = await _serviceSurchargeRepository.GetZoneInfos(approveQuotation.ExpressId);
            foreach (var item in list)
            {
                var tempData = zoneInfo.Where(x => x.zone == item.CountryCode).ToList();
                if (tempData != null && tempData.Count > 0)
                {
                    foreach (var d in tempData)
                    {
                        Finance_ServiceSurchargeDetail detail = new Finance_ServiceSurchargeDetail()
                        {
                            ExpressId = approveQuotation.ExpressId,
                            EnableTime = approveQuotation.EnableTime,
                            CountryCode = d.code,
                            IsDelete = false,
                            FristWeight = item.FristWeight,
                            FristFee = item.FristFee,
                            ContinuedWeight = item.ContinuedWeight,
                            ContinuedFee = item.ContinuedFee,
                            CreateTime = DateTime.Now,
                        };
                        details.Add(detail);
                    }
                }
            }

            //数值对应处理
            string[] custoerIds = approveQuotation.CustomerIds.Split(',', StringSplitOptions.RemoveEmptyEntries);
            foreach (var item in custoerIds)
            {
                Finance_ServiceSurcharge surcharge = new Finance_ServiceSurcharge()
                {
                    ExpressId = approveQuotation.ExpressId,
                    EnableTime = approveQuotation.EnableTime,
                    VersionsName = approveQuotation.EnableTime.ToString("MM.dd"),
                    Versions = 0,
                    FileUrl = approveQuotation.UploadedFileUrl,
                    CustomerId = Convert.ToInt32(item),
                    CreateTime = DateTime.Now,
                };
                var id = (int)(await _serviceSurchargeRepository.InsertAsync(surcharge));
                details.ForEach(x => x.BaseId = id);
                await _serviceSurchargeDetailRepository.BulkToDBAsync(details);
            }
        }
        public async Task<List<Finance_ServiceSurchargeDetailDto>> QueryDetail(QueryModel query)
        {
            string where = string.Empty;
            string sql = $"select a.*,b.分区 [zone] from Finance_ServiceSurchargeDetail a left join Finance_ServiceSurcharge c on c.Id=a.BaseId ";
            //处理查询条件
            if (query.QueryParamer != null && query.QueryParamer.Count > 0)
            {
                if (!query.QueryParamer.Any(x => x.Filed == "ExpressId")) { throw new Exception("必须选择渠道进行查询！"); }
                foreach (var item in query.QueryParamer)
                {
                    if (item.Filed == "CustomerId") { where += $" and CustomerId in ({item.Value})"; }
                    if (item.Filed == "ExpressId")
                    {
                        if (item.Value == "48")
                        {
                            sql += " left join Logistics_FedexZone b on b.二字代码=a.CountryCode ";
                        }
                        else if (item.Value == "50")
                        {
                            sql += " left join Logistics_ExpressDHLZone b on b.Code=a.CountryCode ";
                        }
                        else { throw new Exception("目前仅支持fedex/DHL单个渠道查询！"); }
                        where += $" and ExpressId in ({item.Value})";
                    }
                }
            }
            sql += $" where BaseId= (select top 1 Id from Finance_ServiceSurcharge where 1=1 {where} order by id desc) ";
            //只按 渠道 单一客户 显示
            if (!string.IsNullOrEmpty(where))
            {
                return (await _serviceSurchargeDetailRepository.QueryAsync<Finance_ServiceSurchargeDetailDto>(sql)).ToList();
            }
            else { return new List<Finance_ServiceSurchargeDetailDto>(); }
        }
        public async Task<List<Logistics_Fee_Other>> GetFeeOther(QueryModel query) 
        {
            //这个查询只看用户为0的
            string sql = $@"select top 20 [Id]
      ,[ExpressId]
      ,[FeeType]
      ,[Price]*100 [Price]
      ,[EffectiveDate]
      ,[CreateTime]
      ,[CreateUserName]
      ,[UpdateTime]
      ,[UpdateUserName]
      ,[IsEffective]
      ,[IsPercentByCodHandCost]
      ,[CustomerId]
      ,[Remark] from Logistics_Fee_Other where CustomerId=0 and FeeType=2 and ExpressId={query?.QueryParamer.Where(x=>x.Filed== "ExpressId")?.FirstOrDefault()?.Value??"0"} order by EffectiveDate desc ";
            return (await _serviceSurchargeDetailRepository.QueryAsync<Logistics_Fee_Other>(sql)).ToList();
        }
    }
    public class InputInfo : MSExcelClassMapping<Finance_ServiceSurchargeDetail>
    {
        public InputInfo()
        {
            Map(x => x.CountryCode).Name("国家简码");
            Map(x => x.FristWeight).Name("首重重量(kg)");
            Map(x => x.FristFee).Name("首重费用");
            Map(x => x.ContinuedWeight).Name("续重重量(kg)");
            Map(x => x.ContinuedFee).Name("续重费用");
        }
    }
    public class ServiceSurchargeDetailMapping : MSExcelClassMapping<Finance_ServiceSurchargeDetail>
    {
        public ServiceSurchargeDetailMapping()
        {
            Map(x => x.CountryCode).Name("分区");
            Map(x => x.FristWeight).Name("首重重量(g)");
            Map(x => x.FristFee).Name("首重费用");
            Map(x => x.ContinuedWeight).Name("续重重量(g)");
            Map(x => x.ContinuedFee).Name("续重费用");
        }
    }
}
