using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XYY.Core.Standard.Data.Infrastructure;
using XYY.Model.Standard.Finance;
using Dapper;
using XYY.Model.Standard.MpsOrder;
using XYY.Model.Standard.Order;
using XYY.Service.Standard.Finance.Charging.Base;
using XYY.Model.Standard;
using XYY.Service.Standard.Finance.Charging.CustomerOrderFee;
using XYY.Core.Standard.ExcelHelper.MSExcelHelper;
using Newtonsoft.Json;
using XYY.Core.Standard.Mvc;
using XYY.Data.Standard.UserExtend;

namespace XYY.Data.Standard.Order
{
    public interface IFBA_IncidentalRepository : IBaseRepository<FBA_Incidental>
    {
        Task<List<FBA_Incidental>> GetFBA_Incidentals(FBAIncidentalDto dto);
        Task<List<string>> GetFeeTypes(FBAIncidentalCalculateTarget Target);

        Task SaveOtherFee(FBAIncidentalDto dto);

        Task SetComfig(FBAIncidentalDto dto);

        Task UpdateFee(FBAIncidentalDto dto);

        Task<int?> GetBranchCopanyId(int customerId);

        Task<FBAFeeResult> GetFBAFee(int OrderId);
        //Task GetFees(int orderId);
        Task<FBAIncidentalDto> GetFBAIncidentalDto(FBAIncidentalDto dto);
        Task<bool> IncFBAIncidentals(int IncFBATarget, System.IO.Stream formFile);
    }

    public class FBAFeeResult
    {
        public List<Finance_Order_Charges> JSSum
        {
            get; set;
        }

        public List<Finance_Order_Charges> KHSum
        {
            get; set;
        }
        public List<Finance_Order_Charges> CBSum
        {
            get; set;
        }

        public List<Finance_ChargesDetail> JSDetail
        {
            get; set;
        }

        public List<Finance_ChargesDetail> KHDetail
        {
            get; set;
        }
        public List<Finance_ChargesDetail> CBDetail
        {
            get; set;
        }
    }

    public class FBAIncidentalRepository : BaseRepository<FBA_Incidental>, IFBA_IncidentalRepository
    {
        public FBAIncidentalRepository(IUnitOfWork unitOfWork) : base(unitOfWork)
        {

        }

        public async Task<List<FBA_Incidental>> GetFBA_Incidentals(FBAIncidentalDto dto)
        {
            return (await QueryAsync(x => x.Target == dto.Target && x.OrderId == dto.OrderId)).ToList();
        }

        public async Task<List<string>> GetFeeTypes(FBAIncidentalCalculateTarget Target)
        {
            string sql = $"select distinct Name from FBA_Incidental(nolock) where Target = @Target";
            return (await _unitOfWork.QueryBySqlAsync<string>(sql, null, new { Target = Target })).ToList();
        }
        public async Task<FBAIncidentalDto> GetFBAIncidentalDto(FBAIncidentalDto dto)
        {
            var result = (await QueryAsync(x => x.Target == dto.Target && x.OrderId == dto.OrderId)).ToList();
            if (dto.Target > 0)
            {
                string sql = "select* from Order_MpsOrder where OrderId = @orderId";
                var orderInfo = (await QueryAsync<Order_MpsOrder>(sql, new { orderId = dto.OrderId })).FirstOrDefault();
                dto.ChargedWeight = orderInfo.ChargedWeight ?? 0;
                dto.CostPrice = orderInfo.CostPrice ?? 0;
            }
            dto.Incidentals = result ?? new List<FBA_Incidental>();
            return dto;
        }

        public async Task SetComfig(FBAIncidentalDto dto)
        {
            if (dto.Target == FBAIncidentalCalculateTarget.客户)
            {
                await _unitOfWork.UpdateByConditionAsync<Order_MpsOrder, bool>(x => x.OrderId == dto.OrderId, new
                {
                    CustomerSettlement = true
                });
            }
            else
            {
                await _unitOfWork.UpdateByConditionAsync<Order_MpsOrder, bool>(x => x.OrderId == dto.OrderId, new
                {
                    BranchOfficeSettlement = true
                });
            }
        }
        public async Task<FBAFeeResult> GetFBAFee(int OrderId)
        {
            FBAFeeResult result = new FBAFeeResult
            {
                JSSum = new List<Finance_Order_Charges> { },
                JSDetail = new List<Finance_ChargesDetail> { },
                KHDetail = new List<Finance_ChargesDetail> { },
                KHSum = new List<Finance_Order_Charges> { },
                CBSum = new List<Finance_Order_Charges> { },
                CBDetail = new List<Finance_ChargesDetail> { },
            };
            var order =
                (await _unitOfWork.QueryAsync<Order_Order>(x => x.Id == OrderId)).FirstOrDefault();
            if (order != null)
            {
                var orderFee = await _unitOfWork.QueryAsync<Finance_Order_Charges>(x => !x.Offset && x.SystemNo == order.SystemNo);
                result.KHSum = orderFee.Where(x => x.CustomerId == order.CustomerId).ToList();
                result.JSSum = orderFee.Where(x => x.CustomerId != order.CustomerId && x.CustomerId != 0).ToList();
                result.CBSum = orderFee.Where(x => x.CustomerId == 0).ToList();

                var orderDetails = await _unitOfWork.QueryAsync<Finance_ChargesDetail>(x => !x.Offset && x.BillNo == order.SystemNo);
                result.KHDetail = orderDetails.Where(x => x.CustomerId == order.CustomerId).ToList();
                result.JSDetail = orderDetails.Where(x => x.CustomerId != order.CustomerId && x.CustomerId != 0).ToList();
                result.CBDetail = orderDetails.Where(x => x.CustomerId == 0).ToList();
            }
            return result;

        }

        public async Task<int?> GetBranchCopanyId(int customerId)
        {
            var customers = (await _unitOfWork.QueryBySqlAsync<dynamic>("select Id,BranchCompanyId from User_Customer(nolock) ")).ToList();

            var customer = customers.Where(x => x.Id == customerId).FirstOrDefault();
            return customer?.BranchCompanyId;
        }

        public async Task UpdateFee(FBAIncidentalDto dto)
        {
            decimal sumFee = 0;
            var list = (await _unitOfWork.QueryAsync<FBA_Incidental>(x => x.OrderId == dto.OrderId && x.Target == dto.Target)).ToList();
            var order = (await _unitOfWork.QueryAsync<Order_Order>(x => x.Id == dto.OrderId)).FirstOrDefault();
            string AO = "OA" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
            List<Finance_ChargesDetail> details = new List<Finance_ChargesDetail>();
            int? branchCopanyId = null;
            if (order != null && (order.OrderStatus == 2 || order.OrderStatus == 3))
            {
                int customerId = order.CustomerId;
                var customer = (await _unitOfWork.QueryBySqlAsync<User_CustomerExtend>($"select * from User_Customer where Id={customerId}")).FirstOrDefault();

                //获取计算的实际重量
                decimal mpsWeight = 0.0m;
                if (dto.Target == FBAIncidentalCalculateTarget.结算价)
                {
                    mpsWeight = (dto.ChargedWeight ?? 0) > 0 ? dto.ChargedWeight.Value : (order.OPWeight / 1000.0M);
                    branchCopanyId = await GetBranchCopanyId(customerId);
                    if (!branchCopanyId.HasValue)
                        throw new Exception("当前客户未配置结算公司");
                    customerId = branchCopanyId.Value;
                    //优先计费运费
                    string message = Charges(new ChargesRequest(order.ChannelId,
                       order.CreateOrderChannelId,
                       order.ReceiverCountryCode, 0,
                       customerId,
                       order.Id, order.ReceiveTime.Value,
                      Convert.ToDouble(mpsWeight), order.SystemNo, false, order.TrackingNumber, branchCopanyId
                      , true, order.ReceiverZipCode, "FBA费用", order.ReceiverStreet));
                    if (!message.Contains("成功")) { throw new Exception(message); }

                }
                else//客户计费重量
                {
                    mpsWeight = customer.CalculateWeightType == 0 ? Math.Ceiling(order.OPWeight / 1000.0m) : Math.Ceiling(order.CustomerWeight / 1000.0m);
                    //最小计费重 21kg
                    mpsWeight = mpsWeight < 21 ? 21 : mpsWeight;
                }

                //清理
                await _unitOfWork.UpdateByConditionAsync<Finance_ChargesDetail, bool>(x =>
                x.BillNo == order.SystemNo
                && x.BillType == "FBA杂费" && x.CustomerId == customerId, new
                {
                    Offset = 1
                });
                foreach (var item in list)
                {
                    string TransactionNo = "OF" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    decimal itemFee = 0;
                    if (item.CalculateType == FBAIncidentalCalculateType.称重_KG)
                    {
                        sumFee += item.Fee * mpsWeight;
                        itemFee = item.Fee * mpsWeight;
                    }
                    else if (item.CalculateType == FBAIncidentalCalculateType.固定)
                    {
                        sumFee += item.Fee;
                        itemFee = item.Fee;
                    }
                    Finance_ChargesDetail chargesDetail = new Finance_ChargesDetail()
                    {
                        BillNo = order.SystemNo,
                        AccountingNo = AO,
                        TransactionNo = TransactionNo,
                        ChargeName = item.Name,
                        FeeDescription = item.Name,
                        AccountingDate = DateTime.Now,
                        ClientOrderNo = order.CustomerOrderNo,
                        Currency = "CNY",
                        CreateTime = DateTime.Now,
                        AmountinOriginalCurrency = itemFee,
                        SettlementAmount = itemFee,
                        BillingWeight = mpsWeight,
                        CustomerId = customerId,
                        SettlementCurrency = "CNY",
                        SettlementRate = 1,
                        BillType = "FBA杂费",
                        IncomeOrESxpense = "收入",
                        Offset = false,
                        PriceVersion = 0,
                        TransactionTime = order.ReceiveTime.Value,
                        TransactionType = 1,
                        SettlementCompleted = false,
                        Remark = item.CalculateType == FBAIncidentalCalculateType.称重_KG ? item.Fee.ToString() + "元/KG" : "固定"
                    };
                    details.Add(chargesDetail);
                }

                //更新附加费
                var orderFee =
                    (await _unitOfWork.QueryAsync<Finance_Order_Charges>(
                        x => x.SystemNo == order.SystemNo && x.Offset == false
                    && x.CustomerId == customerId)).FirstOrDefault();
                if (orderFee != null)
                {
                    orderFee.AttachFee = sumFee;
                    await _unitOfWork.UpdateByConditionAsync<Finance_Order_Charges, bool>(x => x.Id == orderFee.Id, new { AttachFee = sumFee });

                }
                if (dto.Target == FBAIncidentalCalculateTarget.结算价)
                {
                    //如果是结算价，重算利润
                    var oldFee = (await _unitOfWork.QueryAsync<Finance_Order_Charges>(x =>
                    x.SystemNo == order.SystemNo && x.CustomerId == order.CustomerId&&x.Offset==false)).FirstOrDefault();
                    if (oldFee != null)
                    {
                        orderFee.Profit =
                             (oldFee.ShippingFee + oldFee.AttachFee + oldFee.EUTariff) - (orderFee.ShippingFee + orderFee.AttachFee + orderFee.EUTariff);
                        await _unitOfWork.UpdateByConditionAsync<Finance_Order_Charges, bool>(x => x.Id == orderFee.Id, new { Profit = orderFee.Profit });
                    }
                    //调用成本记录写入
                    await InsCostFee(dto, list, order, orderFee);
                }
                else if (dto.Target == FBAIncidentalCalculateTarget.客户)
                {
                    branchCopanyId = await GetBranchCopanyId(customerId);
                    if (!branchCopanyId.HasValue)
                        throw new Exception("当前客户未配置结算公司");
                    customerId = branchCopanyId.Value;
                    var jsjFee =
                       (await _unitOfWork.QueryAsync<Finance_Order_Charges>(
                           x => x.SystemNo == order.SystemNo&&x.Offset==false
                       && x.CustomerId == customerId)).FirstOrDefault();
                    if (jsjFee != null)
                    {
                        jsjFee.Profit =
                             (orderFee.ShippingFee + orderFee.AttachFee + orderFee.EUTariff)
                             - (jsjFee.ShippingFee + jsjFee.AttachFee + jsjFee.EUTariff);
                        await _unitOfWork.UpdateByConditionAsync<Finance_Order_Charges, bool>(x => x.Id == jsjFee.Id, new { Profit = jsjFee.Profit });
                    }
                }


                await _unitOfWork.BulkToDBAsync(details);
            }


        }
        public static string Charges(
          ChargesRequest chargesRequest
         )
        {
            string host = "http://localhost:9503/";

            if (!string.IsNullOrEmpty(chargesRequest.CountryCode))
            {
                chargesRequest.CountryCode = chargesRequest.CountryCode.ToUpper();
                if (chargesRequest.CountryCode == "UK")
                {
                    chargesRequest.CountryCode = "GB";
                }
            }
            RestSharp.IRestRequest request = new RestSharp.RestRequest(method: RestSharp.Method.POST);
            request.AddHeader("Authorization", "token 132A7468DE079C6CEB59F383A661E612");
            request.AddJsonBody(new
            {
                chargesRequest.ExpressId,
                chargesRequest.PublicExpressId,
                chargesRequest.CountryCode,
                chargesRequest.GoodsDeclared,
                chargesRequest.CustomerId,
                chargesRequest.OrderId,
                chargesRequest.TransactionTime,
                AccountingDate = chargesRequest.TransactionTime,
                chargesRequest.BillingWeight,
                BillType = "全程派送运费",
                BillNo = chargesRequest.systemNO,
                IncomeOrESxpense = "支出",
                Bookkeeping = chargesRequest.Bookkeeping,
                chargesRequest.TrackingNumber,
                chargesRequest.BranchCompanyCustomerId,
                chargesRequest.HasIOSS,
                chargesRequest.ZipCode,
                chargesRequest.FeeDescription,
                chargesRequest.Stree,
            });
            RestSharp.IRestClient client = new RestSharp.RestClient($"{host}api/ExpressFee/Recalculation");
            client.Timeout = 180 * 1000;//3分钟等待
            var reponse = client.Execute(request);
            if (reponse.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return Newtonsoft.Json.JsonConvert.DeserializeObject<ChargesItem>(reponse.Content).data;
            }
            else
            {
                try
                {
                    return Newtonsoft.Json.JsonConvert.DeserializeObject<ChargesItem>(reponse.ErrorMessage ?? reponse.Content).data;
                }
                catch
                {
                    return reponse.ErrorMessage ?? reponse.Content;
                }
            }
        }
        public async Task InsCostFee(FBAIncidentalDto dto, List<FBA_Incidental> list, Order_Order order, Finance_Order_Charges oldFee)
        {
            //成本费用记录与更新   仅记录 类型为3
            decimal sumFee = 0;
            List<Finance_ChargesDetail> details = new List<Finance_ChargesDetail>();
            string AO = "OA" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
            #region 详细数据初始化
            decimal mpsWeight = (dto.ChargedWeight ?? 0) > 0 ? dto.ChargedWeight.Value : (order.OPWeight / 1000.0M);
            //清理
            await _unitOfWork.UpdateByConditionAsync<Finance_ChargesDetail, bool>(x =>
            x.BillNo == order.SystemNo
            && x.BillType == "FBA成本费用记录" && x.CustomerId == 0, new
            {
                Offset = 1
            });
            details.Add(new Finance_ChargesDetail()
            {
                BillNo = order.SystemNo,
                AccountingNo = AO,
                TransactionNo = "OF" + DateTime.Now.ToString("yyyyMMddHHmmssfff"),
                ChargeName = "运费成本记录",
                FeeDescription = "运费成本记录",
                AccountingDate = DateTime.Now,
                ClientOrderNo = order.CustomerOrderNo,
                Currency = "CNY",
                CreateTime = DateTime.Now,
                AmountinOriginalCurrency = (dto.CostPrice ?? 0) * mpsWeight,
                SettlementAmount = (dto.CostPrice ?? 0) * mpsWeight,
                BillingWeight = mpsWeight,
                CustomerId = 0,//
                SettlementCurrency = "CNY",
                SettlementRate = 1,
                BillType = "FBA成本费用记录",//写死
                IncomeOrESxpense = "支出",
                Offset = false,
                PriceVersion = 0,
                TransactionTime = order.ReceiveTime.Value,
                TransactionType = 3,//3表示成本
                SettlementCompleted = false,
                Remark = dto.CostPrice + "元/KG",
            });
            foreach (var item in list)
            {
                string TransactionNo = "OF" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
                decimal itemFee = 0;
                if (item.CalculateType == FBAIncidentalCalculateType.称重_KG)
                {
                    sumFee += item.Fee * Math.Ceiling(mpsWeight);
                    itemFee = item.Fee * Math.Ceiling(mpsWeight);
                }
                else if (item.CalculateType == FBAIncidentalCalculateType.固定)
                {
                    sumFee += item.Fee;
                    itemFee = item.Fee;
                }
                Finance_ChargesDetail chargesDetail = new Finance_ChargesDetail()
                {
                    BillNo = order.SystemNo,
                    AccountingNo = AO,
                    TransactionNo = TransactionNo,
                    ChargeName = item.Name,
                    FeeDescription = item.Name,
                    AccountingDate = DateTime.Now,
                    ClientOrderNo = order.CustomerOrderNo,
                    Currency = "CNY",
                    CreateTime = DateTime.Now,
                    AmountinOriginalCurrency = itemFee,
                    SettlementAmount = itemFee,
                    BillingWeight = (mpsWeight),
                    CustomerId = 0,//
                    SettlementCurrency = "CNY",
                    SettlementRate = 1,
                    BillType = "FBA成本费用记录",//写死
                    IncomeOrESxpense = "支出",
                    Offset = false,
                    PriceVersion = 0,
                    TransactionTime = order.ReceiveTime.Value,
                    TransactionType = 3,//3表示成本
                    SettlementCompleted = false,
                    Remark = item.CalculateType == FBAIncidentalCalculateType.称重_KG ? item.Fee.ToString() + "元/KG" : "固定"
                };
                details.Add(chargesDetail);
            }
            await _unitOfWork.BulkToDBAsync(details);
            #endregion
            #region 主表数据初始化
            decimal totalSumFee = (dto.CostPrice ?? 0) * mpsWeight;
            //更新附加费
            var orderFee =
                (await _unitOfWork.QueryAsync<Finance_Order_Charges>(
                    x => x.SystemNo == order.SystemNo && x.Offset == false
                && x.CustomerId == 0)).FirstOrDefault();
            if (orderFee != null)//修改
            {
                orderFee.Profit = 0;
                if (oldFee != null)
                {
                    orderFee.Profit = (oldFee.ShippingFee + oldFee.AttachFee + oldFee.EUTariff) - (sumFee + totalSumFee);
                }
                await _unitOfWork.UpdateByConditionAsync<Finance_Order_Charges, bool>(x => x.Id == orderFee.Id, new { AttachFee = sumFee, ShippingFee = totalSumFee, Profit = orderFee.Profit });
            }
            else//新增
            {
                Finance_Order_Charges finance_Order_Charges = new Finance_Order_Charges
                {
                    ChannelId = 0,
                    OrderCreateChannelId = 0,
                    TransactionTime = DateTime.Now,
                    CountryCode = "",
                    AccountingNo = AO,
                    CustomerId = 0,
                    GoodsDeclaredVal = 0,
                    SystemNo = order.SystemNo,
                    TrackingNumber = order.TrackingNumber,
                    Weight = mpsWeight,
                    Offset = false,
                    FeeDescription = "FBA成本费用记录",
                    IncomeOrESxpense = "支出",
                    HasIOSS = false,
                    ZipCode = "",
                    ChargeTarget = null,
                    AttachFee = sumFee,
                    ShippingFee = totalSumFee,
                };
                if (oldFee != null)
                {
                    finance_Order_Charges.Profit =
                         (oldFee.ShippingFee + oldFee.AttachFee + oldFee.EUTariff) - (finance_Order_Charges.AttachFee + finance_Order_Charges.ShippingFee);
                }
                await _unitOfWork.InsertAsync<Finance_Order_Charges>(finance_Order_Charges);
            }
            #endregion

        }
        public async Task SaveOtherFee(FBAIncidentalDto dto)
        {
            await DeleteAsync(x => x.OrderId == dto.OrderId && x.Target == dto.Target);
            if (dto.Incidentals != null)
            {
                dto.Incidentals.ForEach(x =>
                {
                    x.OrderId = dto.OrderId;
                    x.Target = dto.Target;
                    x.CreateTime = System.DateTime.Now;
                });

                await BulkToDBAsync(dto.Incidentals);
                string filed = string.Empty;
                if (dto.Target == FBAIncidentalCalculateTarget.客户)
                {
                    filed = "CustomerSettlement=1";
                }
                else
                {
                    filed = $"BranchOfficeSettlement=1,ChargedWeight={dto.ChargedWeight},CostPrice={dto.CostPrice}";
                }
                if (!string.IsNullOrEmpty(dto.LadingBillNumber)) { filed += $",LadingBillNumber='{dto.LadingBillNumber}' "; }
                string sql = $" update Order_MpsOrder set {filed} where OrderId= {dto.OrderId}";
                await _unitOfWork.ExecuteAsync(sql);
                await UpdateFee(dto);
            }
        }

        public async Task<bool> IncFBAIncidentals(int IncFBATarget, System.IO.Stream formFile)
        {
            bool result = true;
            MSExcelHelper excelHelper = new MSExcelHelper();
            var list = excelHelper.LoadDataAsStream<IncFBAIncidentalDtoMpping, IncFBAIncidentalDto>(formFile)?.Where(i => !string.IsNullOrWhiteSpace(i.FBANumber)).ToList();
            List<FBAIncidentalDto> dtos = await ConvertToFBAIncidentalDtos(IncFBATarget, list);
            StringBuilder sb = new StringBuilder();
            foreach (var item in dtos)
            {
                //改请求的写法
                string host = "http://localhost:9521/";
                RestSharp.IRestRequest request = new RestSharp.RestRequest(method: RestSharp.Method.POST);
                request.AddHeader("Authorization", "token 132A7468DE079C6CEB59F383A661E612");
                request.AddJsonBody(JsonConvert.SerializeObject(item));
                RestSharp.IRestClient client = new RestSharp.RestClient($"{host}api/FBAIncidental/SaveFee");
                var reponse = client.Execute(request);
                string msg = string.Empty;
                if (reponse.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    msg = Newtonsoft.Json.JsonConvert.DeserializeObject<ApiJsonModel>(reponse.Content).message;
                }
                else
                {
                    try
                    {
                        msg = Newtonsoft.Json.JsonConvert.DeserializeObject<ApiJsonModel>(reponse.ErrorMessage ?? reponse.Content).message;
                    }
                    catch
                    {
                        msg = reponse.ErrorMessage ?? reponse.Content;
                    }
                }
                if (msg != "成功")
                {
                    throw new Exception(item.CustomerOrderNo + ":" + msg);
                }
            }
            if (sb.Length > 0)
                throw new Exception("以下订单导入失败" + sb.ToString());
            return result;
        }


        private async Task<List<FBAIncidentalDto>> ConvertToFBAIncidentalDtos(int IncFBATarget, List<IncFBAIncidentalDto> incDtos)
        {
            //数据验证
            if (IncFBATarget == (int)FBAIncidentalCalculateTarget.结算价 && incDtos.Any(x => x.CostFee == 0)) { throw new Exception("成本费用，必须全部填写成本单价！"); }
            List<FBAIncidentalDto> incidentalDtos = new List<FBAIncidentalDto>();
            #region 基础数据提取
            //var customerDto = incDtos.Where(x => (x.CostWeight) == 0).ToList();
            //var costDto = incDtos.Where(x => (x.CostWeight) > 0).ToList();
            List<string> allNumbers = incDtos.Select(x => x.FBANumber.Trim()).Distinct().ToList();
            //获取db数据
            string sqlByOrder = "select * from Order_Order(nolock) where CustomerOrderNo in @CustomerOrderNumber and MpsOrderId>0 and OrderStatus>0  ";//避免更新到已取消订单
            var dbOrderDatas = await _unitOfWork.QueryBySqlAsync<Order_Order>(sqlByOrder, null, new { CustomerOrderNumber = allNumbers });

            string sql = " select * from Order_MpsOrder where Id in @Id ";
            var mpsId = dbOrderDatas.Select(x => x.MpsOrderId).Distinct().ToList();
            var dbMpsOrderDatas = await _unitOfWork.QueryBySqlAsync<Order_MpsOrder>(sql, null, new { Id = mpsId });
            //结算价
            if (IncFBATarget != (int)FBAIncidentalCalculateTarget.客户 && incDtos.Any(x => x.CostWeight == 0))
            {
                incDtos.ForEach(x =>
                {
                    if (x.CostWeight == 0)
                    {
                        x.CostWeight = dbOrderDatas.Where(y => y.CustomerOrderNo == x.FBANumber).FirstOrDefault().OPWeight / 1000.0M;
                    }
                });
            }
            #endregion
            //解析数据
            if (incDtos != null && incDtos.Count > 0)
            {
                List<string> Numbers = incDtos.Select(x => x.FBANumber.Trim()).Distinct().ToList();
                foreach (var item in Numbers)
                {
                    var IncDto = incDtos.Where(x => x.FBANumber.Trim() == item).FirstOrDefault();
                    if ((IncDto?.SendOutTime).HasValue)//发货时间更新
                    {
                        await _unitOfWork.ExecuteAsync($"update Order_Order set SendOutTime='{IncDto?.SendOutTime}' where CustomerOrderNo='{item}' ");
                    }
                    var singleDto = ConvertToFBAIncidentalDto(item, (FBAIncidentalCalculateTarget)IncFBATarget, dbMpsOrderDatas, dbOrderDatas, incDtos);
                    if (singleDto != null)
                    {
                        incidentalDtos.Add(singleDto);
                    }
                }
            }

            return incidentalDtos;
        }
        private FBAIncidentalDto ConvertToFBAIncidentalDto(string fbaNumber, FBAIncidentalCalculateTarget target, IEnumerable<Order_MpsOrder> dbDatas, IEnumerable<Order_Order> orders, List<IncFBAIncidentalDto> allToConvertData)
        {
            var dbData = dbDatas.Where(x => x.CustomerOrderNumber == fbaNumber).FirstOrDefault();
            if (dbData != null)
            {
                var toConvertData = allToConvertData.Where(x => x.FBANumber == fbaNumber).ToList();
                var tempData = toConvertData.Where(x => (x.CostFee) > 0)?.FirstOrDefault();
                FBAIncidentalDto incidentalDto = new FBAIncidentalDto()
                {
                    OrderId = dbData.OrderId ?? 0,
                    Target = target,
                    CostPrice = tempData?.CostFee,
                    ChargedWeight = tempData?.CostWeight,
                    CustomerOrderNo = fbaNumber,
                    LadingBillNumber = toConvertData.FirstOrDefault().LadingBillNumber,
                };
                foreach (var item in toConvertData)
                {
                    string Name = item.IncidentalName;
                    decimal ratio = 1.0M;//费用占比数据
                    decimal fee = 0;//费用金额
                    FBAIncidentalCalculateType CalculateType = FBAIncidentalCalculateType.称重_KG; //默认kg计费
                    //费用获取
                    if (item.Fee.IndexOf('/') > -1)
                    {
                        string feeStr = item.Fee.Substring(0, item.Fee.IndexOf('/')).Trim();
                        fee = Convert.ToDecimal(feeStr);
                        if (item.Fee.IndexOf("票") > -1) { CalculateType = FBAIncidentalCalculateType.固定; }
                    }
                    else
                    {
                        fee = Convert.ToDecimal(item.Fee.Trim());
                    }
                    //if (fee==0) { throw new Exception("附加费不能为0，合并列填写相同费用即可！"); }
                    //合并信息获取
                    if (!string.IsNullOrEmpty(item.Remake))
                    {
                        decimal totalWeight = 1; decimal currentWeight = 1;
                        List<string> CombineNumber = allToConvertData.Where(x => x.Remake == item.Remake).Select(x => x.FBANumber).ToList();
                        if (target == FBAIncidentalCalculateTarget.客户)
                        {
                            //取订单OPWeight
                            var combineOrder = orders.Where(x => CombineNumber.Contains(x.CustomerOrderNo)).ToList();
                            totalWeight = combineOrder.Sum(x => x.OPWeight);
                            currentWeight = combineOrder.Where(x => x.CustomerOrderNo == fbaNumber).FirstOrDefault().OPWeight;
                        }
                        else
                        {
                            //成本 费用 取录入的计费重
                            var combineOrder = allToConvertData.Where(x => CombineNumber.Contains(x.FBANumber))
                                .Select(x => (x.FBANumber, x.CostWeight)).Distinct().ToList();
                            totalWeight = combineOrder.Sum(x => x.CostWeight);
                            if (totalWeight > 0)
                            {
                                currentWeight = combineOrder.Where(x => x.FBANumber == fbaNumber && (x.CostWeight) > 0)?.FirstOrDefault().CostWeight ?? 0;
                            }
                            else//都没有重量
                            {
                                totalWeight = orders.Where(x => CombineNumber.Contains(x.CustomerOrderNo)).Sum(x => x.OPWeight) / 1000.0M;
                                currentWeight = orders.Where(x => x.CustomerOrderNo == fbaNumber).FirstOrDefault().OPWeight / 1000.0M;
                            }

                        }
                        ratio = (currentWeight / totalWeight);
                        ratio = ratio > 0 ? ratio : 1;//计算为0，数据错误，默认全额
                        Name += $"(合并费用{fee}，占比{Math.Round(ratio, 2)})";
                    }
                    else
                    {
                        Name += $"({item.Description})";
                    }

                    FBA_Incidental incidental = new FBA_Incidental()
                    {
                        OrderId = dbData.OrderId ?? 0,
                        Name = Name,
                        Fee = Math.Round(fee * ratio, 2),
                        CalculateType = CalculateType,
                    };
                    incidentalDto.Incidentals.Add(incidental);
                }
                return incidentalDto;
            }
            else
            {
                return null;
            }
        }
    }
}
