using Org.BouncyCastle.Ocsp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using XYY.Common.Standard;
using XYY.Data.Standard.Order;
using XYY.Model.Standard.Enums;
using XYY.Model.Standard.Finance;
using XYY.Model.Standard.MpsOrder;
using XYY.Model.Standard.MpsOrder.dto;
using XYY.Model.Standard.MpsOrder.Report;
using XYY.Model.Standard.MpsOrder.views;
using XYY.Service.Standard.Finance.Charging.Base;
using XYY.Service.Standard.Finance.Charging.CustomerOrderFee;
using XYY.Service.Standard.Finance.Charging.Dto;

namespace XYY.Service.Standard.Order.FBA
{
    public interface IFBAOrderService
    {
        Task<PageResult<View_Order_ReceivingInfo>> GetReceivingInfo(QueryModel queryModel);
        Task<IEnumerable<Order_MpsOrderBox>> GetReceivingBoxs(IEnumerable<int> orderIds);
        Task<bool> UpdateReceivingBoxs(List<Order_MpsOrderBox> boxs);

        Task<View_Order_ReceivingInfo> GetOrderReceivingInfo(int orderId);
        Task<bool> GoToPrint(IEnumerable<int> Ids);
        Task<bool> GoToIncome(IEnumerable<int> Ids);

        //Task SaveOrderRceiveingInfo(View_Order_ReceivingInfo order);

        Task<PageResult<View_Order_Print>> GetPrintList(QueryModel queryModel);
        Task<ReceivingAddress> GetReceivingAddress(int orderId);
        Task<IEnumerable<Order_MpsOrderGoods>> GetReceivingGoods(int orderId);
        Task<MpsPrint> GetPrint(int orderId);
        Task<bool> UpdatePrintBoxs(MpsPrint boxs);
        //Task SavePrintInfos(View_Order_Print order);
        Task<PageResult<View_Order_CustomerConfirm>> GetCustomerConfirmList(QueryModel queryModel);
        Task<MpsCustomerConfirm> GetCustomerConfirm(int orderId);
        Task<List<ConfirmWeight>> GetBatchConfirmWeight(IEnumerable<int> Ids);
        Task<List<ConfirmWeight>> GetBatchSettlementWeight(IEnumerable<int> Ids);
        Task<bool> UpdateBatchSettlementWeight(List<ConfirmWeight> confirmWeights);
        Task<bool> UpdateBatchConfirmWeight(List<ConfirmWeight> confirmWeights);

        Task<IEnumerable<FBA_Incidental>> GetBatchIncidenta(IEnumerable<int> Ids, FBAIncidentalCalculateTarget target);
        Task<bool> UpdateBatchConfirmIncidenta(List<FBA_Incidental> incidentals);
        Task<bool> UpdateBatchSettlementIncidenta(List<FBA_Incidental> incidentals);

        Task<bool> UpdateCustomerConfirm(MpsCustomerConfirm dto);
        Task<decimal> GetUnitPrice(int OrderId);
        Task<bool> GoToSettlement(IEnumerable<int> Ids, string NiceName);
        Task<bool> GoToEnd(IEnumerable<int> Ids, string NiceName);

        Task SaveCustomerConfirm(View_Order_CustomerConfirm order);
        //Task<View_Order_CustomerConfirm> GetCustomerConfirm(int orderId);
        Task<PageResult<View_Order_SettlementConfirm>> GetSettlementConfirmList(QueryModel queryModel);
        Task SaveSettlementConfirm(View_Order_SettlementConfirm order);
        Task<MpsSettlementConfirm> GetSettlementConfirm(int orderId);

        Task<bool> UpdateSettlementConfirm(MpsSettlementConfirm dto);
        Task<bool> UpdateSettlementConfirmForTable(MpsSettlementConfirmTableData dto);
        Task<bool> SettlementConfirmOperation(int orderId,string NiceName);

        Task<PageResult<GrossProfitByCustomer>> GetGrossProfitByCustomer(QueryModel queryModel);
        Task<PageResult<GrossProfitByOrder>> GetGrossProfitByOrder(QueryModel qm);
    }

    public class FBAOrderService : IFBAOrderService
    {
        IFBAOrderRepository orderRepository;
        IFBAOtherFeeService fBAOtherFeeService;

        public FBAOrderService(IFBAOrderRepository orderRepository, IFBAOtherFeeService fBAOtherFeeService)
        {
            this.orderRepository = orderRepository;
            this.fBAOtherFeeService = fBAOtherFeeService;
        }

        //public async Task<View_Order_CustomerConfirm> GetCustomerConfirm(int orderId)
        //{
        //    return await this.orderRepository.GetCustomerConfirm(orderId);
        //}
        public async Task<IEnumerable<Order_MpsOrderBox>> GetReceivingBoxs(IEnumerable<int> orderIds)
        {
            return await orderRepository.GetReceivingBoxs(orderIds);
        }
        public async Task<bool> UpdateReceivingBoxs(List<Order_MpsOrderBox> boxs)
        {
            var boxUpdate = orderRepository.UpdateReceivingBoxs(boxs);
            var boxsGroup = boxs.GroupBy(x => x.MpsOrderId);
            List<MpsOrderWeight> mps = new List<MpsOrderWeight>();
            foreach (var item in boxsGroup)
            {
                //更新订单表汇总数据
                mps.Add(new MpsOrderWeight()
                {
                    MpsOrderId = item.Key,
                    Identification = item.Any(x => x.Identification),
                    GoodsNames = string.Join(";", item.Where(x => !string.IsNullOrEmpty(x.GoodsNames)).Select(x => x.GoodsNames).Distinct()),
                    Remark = string.Join(";", item.Where(x => !string.IsNullOrEmpty(x.Remark)).Select(x => x.Remark).Distinct()),
                    InputWeight = item.Sum(x => x.OpInputWeight),
                    VolumeWeight = item.Sum(x => x.VolumeWeight)
                });
            }
            try
            {
                await orderRepository.UpdateReceivingMpsOrders(mps);
                var Ids = boxsGroup.Select(x => x.Key);
                await orderRepository.UpdateOrderReceiveTime(Ids);
                await boxUpdate;
            }
            catch (Exception ex)
            {
                throw new Exception("收货数据修改异常！" + ex.Message);
            }
            return true;
        }
        public async Task<bool> GoToPrint(IEnumerable<int> Ids)
        {
            var datas = await orderRepository.CheackBoxIntegrity(Ids);
            if (datas != null && datas.Count() > 0) { throw new Exception("以下单号存在未收货完成的箱子，请完成收货后重试！\r\n " + string.Join(",", datas)); }
            await orderRepository.UpdateMpsOrdersStatus(Ids, (int)MpsOrderStatus.打单);
            return true;
        }
        public async Task<bool> GoToIncome(IEnumerable<int> Ids)
        {
            await orderRepository.UpdateMpsOrdersStatus(Ids, (int)MpsOrderStatus.收款);
            return true;
        }
        public async Task<PageResult<View_Order_CustomerConfirm>> GetCustomerConfirmList(QueryModel queryModel)
        {
            return await this.orderRepository.GetCustomerConfirmList(queryModel);
        }

        public async Task<View_Order_ReceivingInfo> GetOrderReceivingInfo(int orderId)
        {
            return await this.orderRepository.GetOrderReceivingInfo(orderId);
        }
        public async Task<ReceivingAddress> GetReceivingAddress(int orderId)
        {
            return await orderRepository.GetReceivingAddress(orderId);
        }
        public async Task<IEnumerable<Order_MpsOrderGoods>> GetReceivingGoods(int orderId)
        {
            return await orderRepository.GetReceivingGoods(orderId);
        }
        public async Task<MpsPrint> GetPrint(int orderId)
        {
            MpsPrint mpsPrint = new MpsPrint() { OrderId = orderId };
            mpsPrint.ReceivingAddress = await orderRepository.GetReceivingAddress(orderId);
            mpsPrint.mpsOrderBoxes = await orderRepository.GetReceivingBoxs(new List<int>() { orderId });
            mpsPrint.MpsOrderGoods = await orderRepository.GetReceivingGoods(orderId);
            return mpsPrint;
        }

        public async Task<PageResult<View_Order_Print>> GetPrintList(QueryModel queryModel)
        {
            return await this.orderRepository.GetPrintList(queryModel);
        }
        public async Task<bool> UpdatePrintBoxs(MpsPrint boxs)
        {
            //更新地址
            await orderRepository.UpdatePrintReviceAddress(boxs.ReceivingAddress, boxs.OrderId);
            //更新箱子信息
            await orderRepository.UpdatePrintBoxs(boxs.mpsOrderBoxes.ToList());
            //更新商品信息
            await orderRepository.UpdatePrintGoods(boxs.MpsOrderGoods.ToList(), boxs.OrderId);
            return true;
        }
        public async Task<MpsCustomerConfirm> GetCustomerConfirm(int orderId)
        {
            MpsCustomerConfirm mpsCustomerConfirm = new MpsCustomerConfirm();
            mpsCustomerConfirm.mpsOrderBoxes = await orderRepository.GetReceivingBoxs(new List<int>() { orderId });
            mpsCustomerConfirm.incidentals = await orderRepository.GetFBA_Incidentals(orderId, FBAIncidentalCalculateTarget.客户);
            return mpsCustomerConfirm;
        }
        public async Task<List<ConfirmWeight>> GetBatchConfirmWeight(IEnumerable<int> Ids)
        {
            return (await orderRepository.GetBatchConfirmWeight(Ids)).ToList();
        }
        public async Task<List<ConfirmWeight>> GetBatchSettlementWeight(IEnumerable<int> Ids)
        {
            return (await orderRepository.GetBatchSettlementWeight(Ids)).ToList();
        }
        public async Task<bool> UpdateBatchSettlementWeight(List<ConfirmWeight> confirmWeights)
        {
            return await orderRepository.UpdateBatchSettlementWeight(confirmWeights);
        }
        public async Task<bool> UpdateBatchConfirmWeight(List<ConfirmWeight> confirmWeights)
        {
            return await orderRepository.UpdateBatchConfirmWeight(confirmWeights);
        }
        public async Task<bool> UpdateCustomerConfirm(MpsCustomerConfirm dto)
        {
            //处理附加费
            List<FBA_Incidental> incidentals = dto.incidentals.ToList();
            if (incidentals != null && incidentals.Count() > 0)
            {
                var tempData = incidentals.Where(x => (x.SysncJS ?? false)).ToList().CopyList<FBA_Incidental>();
                foreach (var x in tempData) { x.Target = FBAIncidentalCalculateTarget.结算价; }
                if (tempData != null && tempData.Count > 0) { incidentals.AddRange(tempData); }
                foreach (var item in incidentals)
                {
                    item.OrderId = dto.OrderId;
                }
                //保存附加费
                await orderRepository.SaveFBA_Incidentals(incidentals, dto.OrderId);
            }
            else
            {
                //清空所有附加费
                await orderRepository.DelFBA_Incidentals(dto.OrderId);
            }
            //更新订单确认数据
            if (dto.customerConfirmOrderDtos != null && dto.customerConfirmOrderDtos.Count() > 0) { await orderRepository.UpdateCustomerOrderConfirm(dto.customerConfirmOrderDtos, dto.OrderId); }
            //更新箱子信息
            if (dto.mpsOrderBoxes != null && dto.mpsOrderBoxes.Count() > 0) { await orderRepository.UpdateCustomerConfirmBoxs(dto.mpsOrderBoxes); }
            return true;
        }
        public async Task<IEnumerable<FBA_Incidental>> GetBatchIncidenta(IEnumerable<int> Ids, FBAIncidentalCalculateTarget target)
        {
            return await orderRepository.GetBatchIncidenta(Ids, target);
        }
        public async Task<bool> UpdateBatchConfirmIncidenta(List<FBA_Incidental> incidentals)
        {
            var incidentalGroup = incidentals.GroupBy(x => x.OrderId);
            foreach (var item in incidentalGroup)
            {
                var orderIdItem = item.ToList();
                var tempData = orderIdItem.Where(x => (x.SysncJS ?? false)).ToList().CopyList<FBA_Incidental>();
                foreach (var x in tempData) { x.Target = FBAIncidentalCalculateTarget.结算价; }
                if (tempData != null && tempData.Count > 0) { orderIdItem.AddRange(tempData); }
                //逐单保存
                await orderRepository.SaveFBA_Incidentals(orderIdItem, item.Key);
            }
            List<ConfirmIncidenta> incidentas = incidentalGroup.Select(x => new ConfirmIncidenta()
            {
                OrderId = x.Key,
                TotalSurcharges = x.Sum(x => x.Fee)
            }).ToList();
            //更新主表计费数据
            if (incidentas.Count > 0) { await orderRepository.UpdateBatchConfirmIncidenta(incidentas); }
            return true;
        }
        public async Task<bool> UpdateBatchSettlementIncidenta(List<FBA_Incidental> incidentals)
        {
            var incidentalGroup = incidentals.GroupBy(x => x.OrderId);
            foreach (var item in incidentalGroup)
            {
                var orderIdItem = item.ToList();
                foreach (var x in orderIdItem) { x.Target = FBAIncidentalCalculateTarget.结算价; }
                //逐单保存
                await orderRepository.SaveFBA_Incidentals(orderIdItem, item.Key, true);
            }
            List<ConfirmIncidenta> incidentas = incidentalGroup.Select(x => new ConfirmIncidenta()
            {
                OrderId = x.Key,
                TotalSurcharges = x.Sum(x => x.Fee)
            }).ToList();
            //更新主表计费数据
            if (incidentas.Count > 0) { await orderRepository.UpdateBatchSettlementConfirmIncidenta(incidentas); }
            return true;
        }
        public async Task<decimal> GetUnitPrice(int OrderId)
        {
            KPUnitPriceRequest dto = new KPUnitPriceRequest();
            var mpsOrder = await orderRepository.GetMpsOrder(OrderId);
            if (mpsOrder.Status == MpsOrderStatus.收款)
            {
                var data = await orderRepository.GetCustomerConfirm(OrderId);
                dto.PublicExpressId = data.CreateOrderChannelId;
                dto.CustomerId = data.CustomerId;
                dto.ZipCode = data.ReceiverZipCode;
                dto.TransactionTime = data.ReceiveTime;
                dto.gWeight = Convert.ToDouble(data.OpBillWeight);
                return await orderRepository.GetUnitPrice(dto);
            }
            else if (mpsOrder.Status == MpsOrderStatus.结算)
            {
                var data = await orderRepository.GetSettlementConfirm(OrderId);
                dto.PublicExpressId = data.CreateOrderChannelId;
                dto.CustomerId = data.BranchCompanyId;
                dto.ZipCode = data.ReceiverZipCode;
                dto.TransactionTime = data.ReceiveTime;
                dto.gWeight = Convert.ToDouble(data.OpBillWeight);
                return await orderRepository.GetUnitPrice(dto);
            }
            else { return 0; }

        }
        #region 转入结算流程

        public async Task<bool> GoToSettlement(IEnumerable<int> Ids, string NiceName)
        {
            var confirms = await orderRepository.GetCustomerConfirmList(Ids);
            //数据校验
            await IncomeDataVerify(confirms);
            //转换计费数据
            var toBulkData = await ConvertToConfimCharge(confirms, NiceName);
            //写入计费数据
            bool res = await orderRepository.UpdateCharge(toBulkData);
            //计费写入成功才更新状态
            if (res) { await orderRepository.UpdateMpsOrdersStatus(Ids, (int)MpsOrderStatus.结算); }
            return true;
        }
        private async Task<bool> IncomeDataVerify(IEnumerable<View_Order_CustomerConfirm> confirms)
        {
            if (confirms.Any(x => x.CustomerConfirmBillWeight < 1))
            {
                throw new Exception("以下订单无确认收费重量！" + string.Join(",", confirms.Where(x => x.CustomerConfirmBillWeight < 1)
                    .Select(x => x.SystemNo).Distinct().ToList())
                    );
            }
            if (confirms.Any(x => x.CustomerConfirmUnitPrice < 1))
            {
                throw new Exception("以下订单无单价！" + string.Join(",", confirms.Where(x => x.CustomerConfirmUnitPrice < 1)
                   .Select(x => x.SystemNo).Distinct().ToList())
                   );
            }
            if (confirms.Any(x => x.CustomerConfirmTotal < 1))
            {
                throw new Exception("以下订单无应收总额！" + string.Join(",", confirms.Where(x => x.CustomerConfirmTotal < 1)
                   .Select(x => x.SystemNo).Distinct().ToList())
                   );
            }
            return true;
        }
        #endregion
        #region 生成结算计费
        public async Task<bool> GoToEnd(IEnumerable<int> Ids, string NiceName)
        {
            var settlements = await orderRepository.GetSettlementConfirmList(Ids);
            //数据校验
            await SettlementDataVerify(settlements);
            //转换计费数据
            var toBulkData = await ConvertToSettlementCharge(settlements, NiceName);
            //写入计费数据
            bool res = await orderRepository.UpdateCharge(toBulkData);
            return res;
        }
        private async Task<bool> SettlementDataVerify(IEnumerable<View_Order_SettlementConfirm> confirms)
        {
            if (confirms.Any(x => x.SettlementConfirmBillWeight < 1))
            {
                throw new Exception("以下订单无确认收费重量！" + string.Join(",", confirms.Where(x => x.SettlementConfirmBillWeight < 1)
                    .Select(x => x.SystemNo).Distinct().ToList())
                    );
            }
            if (confirms.Any(x => x.SettlementConfirmUnitPrice < 1))
            {
                throw new Exception("以下订单无单价！" + string.Join(",", confirms.Where(x => x.SettlementConfirmUnitPrice < 1)
                   .Select(x => x.SystemNo).Distinct().ToList())
                   );
            }
            if (confirms.Any(x => x.SettlementConfirmTotal < 1))
            {
                throw new Exception("以下订单无应收总额！" + string.Join(",", confirms.Where(x => x.SettlementConfirmTotal < 1)
                   .Select(x => x.SystemNo).Distinct().ToList())
                   );
            }
            return true;
        }
        #endregion 
        #region 计费相关处理
        //计费数据转换
        public async Task<KPCharges> ConvertToConfimCharge(IEnumerable<View_Order_CustomerConfirm> confirms, string NiceName)
        {
            //获取附加费
            List<Finance_Order_Charges> charges = new List<Finance_Order_Charges>();
            List<Finance_ChargesDetail> chargesDetails = new List<Finance_ChargesDetail>();
            var allIncidentals = await fBAOtherFeeService.GetAll();
            foreach (var confirm in confirms)
            {
                var incidentals = await orderRepository.GetFBA_Incidentals(confirm.Id, FBAIncidentalCalculateTarget.客户);

                string AccountingNo = $"ANO{DateTime.Now.ToString("yyyyMMddHHmmss")}{confirm.Id}";
                DateTime CreateTime= DateTime.Now.ToLocalTime();
                Finance_Order_Charges finance_Order_Charges = new Finance_Order_Charges
                {
                    ShippingFee = confirm.CustomerConfirmBillWeight * confirm.CustomerConfirmUnitPrice,
                    AttachFee = confirm.CustomerConfirmTotalSurcharges,
                    ChannelId = confirm.ChannelId,
                    OrderCreateChannelId = confirm.CreateOrderChannelId,
                    TransactionTime = confirm.ReceiveTime,
                    CountryCode = confirm.ReceiverCountryCode,
                    AccountingNo = AccountingNo,
                    CustomerId = confirm.CustomerId,
                    GoodsDeclaredVal = 0,
                    SystemNo = confirm.SystemNo,
                    TrackingNumber = confirm.TrackingNumber,
                    Weight = confirm.CustomerConfirmBillWeight,
                    Offset = false,
                    FeeDescription = "FBA费用",
                    IncomeOrESxpense = "支出",
                    HasIOSS = false,
                    ZipCode = confirm.ReceiverZipCode,
                    ChargeTarget = ChargeTarget.客户,
                    Length = 0,
                    Height = 0,
                    Width = 0,
                    CreateTime = CreateTime,
                    CreateUserName = NiceName,
                    Remark=confirm.CustomerConfirmUnitPrice.ToString(),
                };
                charges.Add(finance_Order_Charges);
                //始终记录一条全程派送费
                List<Finance_ChargesDetail> details = new List<Finance_ChargesDetail>()
                {
                    new Finance_ChargesDetail
                    {
                        BillNo=confirm.SystemNo,
                        BillType="全程派送运费",
                        ClientOrderNo=null,
                        AccountingDate=null,
                        PriceVersion=0,
                        TransactionType=(int)TransactionType.Consume,
                        TransactionNo="OF" + DateTime.Now.ToString("yyyyMMddHHmmssfff"),
                        ChargeName="运费(含燃油)",
                        TransactionTime=confirm.ReceiveTime,
                        IncomeOrESxpense="支出",
                        Currency="CNY",
                        AmountinOriginalCurrency=confirm.CustomerConfirmBillWeight * confirm.CustomerConfirmUnitPrice,
                        SettlementRate=1,
                        SettlementCurrency="CNY",
                        SettlementAmount=confirm.CustomerConfirmBillWeight * confirm.CustomerConfirmUnitPrice,
                        FeeDescription="FBA费用",
                        CreateUserName=NiceName,
                        CreateTime=DateTime.Now,
                        Remark=confirm.CustomerConfirmUnitPrice+"/KG",
                        Offset=false,
                        CustomerId=confirm.CustomerId,
                        AccountingNo=AccountingNo,
                        BillingWeight=confirm.CustomerConfirmBillWeight,
                    }
                };
                foreach (var item in incidentals)
                {
                    //取个名称的数据而已
                    var tempIncidentals = allIncidentals.Where(x => x.Id == item.FBAOtherFeeId)?.FirstOrDefault();
                    details.Add(new Finance_ChargesDetail
                    {
                        BillNo = confirm.SystemNo,
                        BillType = "FBA杂费",
                        ClientOrderNo = confirm.CustomerOrderNo,
                        AccountingDate = DateTime.Now,
                        PriceVersion = 0,
                        TransactionType = (int)TransactionType.Consume,
                        TransactionNo = "OF" + DateTime.Now.ToString("yyyyMMddHHmmssfff"),
                        ChargeName = tempIncidentals?.Name ?? "附加费",
                        TransactionTime = confirm.ReceiveTime,
                        IncomeOrESxpense = "支出",
                        Currency = "CNY",
                        AmountinOriginalCurrency = item.Fee,
                        SettlementRate = 1,
                        SettlementCurrency = "CNY",
                        SettlementAmount = item.Fee,
                        FeeDescription = tempIncidentals?.Name ?? "附加费",
                        CreateUserName = NiceName,
                        CreateTime = DateTime.Now,
                        Remark = item.CustomerRemark,
                        Offset = false,
                        CustomerId = confirm.CustomerId,
                        AccountingNo = AccountingNo,
                        BillingWeight = confirm.CustomerConfirmBillWeight,
                    });
                }
                chargesDetails.AddRange(details);
            }
            return new KPCharges()
            {
                charges = charges,
                chargesDetails = chargesDetails,
            };

        }
        public async Task<KPCharges> ConvertToSettlementCharge(IEnumerable<View_Order_SettlementConfirm> confirms, string NiceName)
        {
            //获取附加费
            List<Finance_Order_Charges> charges = new List<Finance_Order_Charges>();
            List<Finance_ChargesDetail> chargesDetails = new List<Finance_ChargesDetail>();
            var allIncidentals = await fBAOtherFeeService.GetAll();
            foreach (var confirm in confirms)
            {
                var incidentals = await orderRepository.GetFBA_Incidentals(confirm.Id, FBAIncidentalCalculateTarget.结算价);

                string AccountingNo = $"ANO{DateTime.Now.ToString("yyyyMMddHHmmss")}{confirm.Id}";
                DateTime TransactionTime = confirm.ReceiveTime;
                Finance_Order_Charges finance_Order_Charges = new Finance_Order_Charges
                {
                    ShippingFee = confirm.SettlementConfirmBillWeight * confirm.SettlementConfirmUnitPrice,
                    AttachFee = confirm.SettlementConfirmTotalSurcharges,
                    ChannelId = confirm.ChannelId,
                    OrderCreateChannelId = confirm.CreateOrderChannelId,
                    TransactionTime = TransactionTime,
                    CountryCode = confirm.ReceiverCountryCode,
                    AccountingNo = AccountingNo,
                    CustomerId = confirm.BranchCompanyId,
                    GoodsDeclaredVal = 0,
                    SystemNo = confirm.SystemNo,
                    TrackingNumber = confirm.TrackingNumber,
                    Weight = confirm.SettlementConfirmBillWeight,
                    Offset = false,
                    FeeDescription = "FBA费用",
                    IncomeOrESxpense = "支出",
                    HasIOSS = false,
                    ZipCode = confirm.ReceiverZipCode,
                    ChargeTarget = ChargeTarget.分公司,
                    Length = 0,
                    Height = 0,
                    Width = 0,
                    CreateTime = TransactionTime,
                    CreateUserName = NiceName,
                    Profit = confirm.SettlementConfirmTotal - confirm.CustomerConfirmTotal,
                };
                charges.Add(finance_Order_Charges);
                //始终记录一条全程派送费
                List<Finance_ChargesDetail> details = new List<Finance_ChargesDetail>()
                {
                    new Finance_ChargesDetail
                    {
                        BillNo=confirm.SystemNo,
                        BillType="全程派送运费",
                        ClientOrderNo=null,
                        AccountingDate=null,
                        PriceVersion=0,
                        TransactionType=(int)TransactionType.Consume,
                        TransactionNo="OF" + DateTime.Now.ToString("yyyyMMddHHmmssfff"),
                        ChargeName="运费(含燃油)",
                        TransactionTime=TransactionTime,
                        IncomeOrESxpense="支出",
                        Currency="CNY",
                        AmountinOriginalCurrency=confirm.SettlementConfirmBillWeight * confirm.SettlementConfirmUnitPrice,
                        SettlementRate=1,
                        SettlementCurrency="CNY",
                        SettlementAmount=confirm.SettlementConfirmBillWeight * confirm.SettlementConfirmUnitPrice,
                        FeeDescription="FBA费用",
                        CreateUserName=NiceName,
                        CreateTime=DateTime.Now,
                        Remark=confirm.SettlementConfirmUnitPrice+"/KG",
                        Offset=false,
                        CustomerId=confirm.BranchCompanyId,
                        AccountingNo=AccountingNo,
                        BillingWeight=confirm.SettlementConfirmBillWeight,
                    }
                };
                foreach (var item in incidentals)
                {
                    //取个名称的数据而已
                    var tempIncidentals = allIncidentals.Where(x => x.Id == item.FBAOtherFeeId)?.FirstOrDefault();
                    details.Add(new Finance_ChargesDetail
                    {
                        BillNo = confirm.SystemNo,
                        BillType = "FBA杂费",
                        ClientOrderNo = confirm.CustomerOrderNo,
                        AccountingDate = DateTime.Now,
                        PriceVersion = 0,
                        TransactionType = (int)TransactionType.Consume,
                        TransactionNo = "OF" + DateTime.Now.ToString("yyyyMMddHHmmssfff"),
                        ChargeName = tempIncidentals?.Name ?? "附加费",
                        TransactionTime = TransactionTime,
                        IncomeOrESxpense = "支出",
                        Currency = "CNY",
                        AmountinOriginalCurrency = item.Fee,
                        SettlementRate = 1,
                        SettlementCurrency = "CNY",
                        SettlementAmount = item.Fee,
                        FeeDescription = tempIncidentals?.Name ?? "附加费",
                        CreateUserName = NiceName,
                        CreateTime = DateTime.Now,
                        Remark = item.JSRemark,
                        Offset = false,
                        CustomerId = confirm.BranchCompanyId,
                        AccountingNo = AccountingNo,
                        BillingWeight = confirm.SettlementConfirmBillWeight,
                    });
                }
                chargesDetails.AddRange(details);
            }
            return new KPCharges()
            {
                charges = charges,
                chargesDetails = chargesDetails,
            };

        }
        #endregion
        public async Task<PageResult<View_Order_ReceivingInfo>> GetReceivingInfo(QueryModel queryModel)
        {
            return await this.orderRepository.GetReceivingInfo(queryModel);
        }

        public async Task<MpsSettlementConfirm> GetSettlementConfirm(int orderId)
        {
            MpsSettlementConfirm mpsSettlementConfirm = new MpsSettlementConfirm();
            mpsSettlementConfirm.mpsOrderBoxes = await orderRepository.GetReceivingBoxs(new List<int>() { orderId });
            mpsSettlementConfirm.incidentals = await orderRepository.GetFBA_Incidentals(orderId, FBAIncidentalCalculateTarget.结算价);
            return mpsSettlementConfirm;
        }

        public async Task<PageResult<View_Order_SettlementConfirm>> GetSettlementConfirmList(QueryModel queryModel)
        {
            return await this.orderRepository.GetSettlementConfirmList(queryModel);
        }

        public async Task<bool> UpdateSettlementConfirm(MpsSettlementConfirm dto)
        {
            //处理附加费
            List<FBA_Incidental> incidentals = dto.incidentals.ToList();
            if (incidentals != null && incidentals.Count > 0)
            {
                foreach (var item in incidentals)
                {
                    item.OrderId = dto.OrderId;
                    item.Target = FBAIncidentalCalculateTarget.结算价;
                }
                //保存附加费
                await orderRepository.SaveFBA_Incidentals(incidentals, dto.OrderId, true);
            }
            else
            {
                //清空所有附加费
                await orderRepository.DelFBA_Incidentals(dto.OrderId, true);
            }
            //更新订单确认数据
            if (dto.settlementConfirmOrderDtos != null && dto.settlementConfirmOrderDtos.Count() > 0) { await orderRepository.UpdateSettlementOrderConfirm(dto.settlementConfirmOrderDtos, dto.OrderId); }
            //更新箱子信息
            if (dto.mpsOrderBoxes != null && dto.mpsOrderBoxes.Count() > 0) { await orderRepository.UpdateSettlementConfirmBoxs(dto.mpsOrderBoxes); }
            return true;
        }
        public async Task<bool> UpdateSettlementConfirmForTable(MpsSettlementConfirmTableData dto)
        {
            //处理附加费
            List<FBA_Incidental> incidentals = dto.incidentals.ToList();
            if (incidentals != null && incidentals.Count > 0)
            {
                foreach (var item in incidentals)
                {
                    item.OrderId = dto.OrderId;
                    item.Target = FBAIncidentalCalculateTarget.结算价;
                }
                //保存附加费
                await orderRepository.SaveFBA_Incidentals(incidentals, dto.OrderId, true);
            }
            else
            {
                //清空所有附加费
                await orderRepository.DelFBA_Incidentals(dto.OrderId, true);
            }
            //更新订单确认数据
            if (dto != null) { await orderRepository.UpdateSettlementConfirmForTable(dto); }
            return true;
        }
        public async Task<bool> SettlementConfirmOperation(int orderId, string NiceName)
        {
            return await orderRepository.SettlementConfirmOperation(orderId, NiceName);
        }



        public async Task SaveCustomerConfirm(View_Order_CustomerConfirm order)
        {
            await this.orderRepository.SaveCustomerConfirm(order);
        }

        //public async Task SaveOrderRceiveingInfo(View_Order_ReceivingInfo order)
        //{
        //    await this.orderRepository.SaveOrderRceiveingInfo(order);
        //}

        public async Task SavePrintInfos(View_Order_Print order)
        {
            await this.orderRepository.SavePrintInfos(order);
        }

        public async Task SaveSettlementConfirm(View_Order_SettlementConfirm order)
        {
            await this.orderRepository.SaveSettlementConfirm(order);
        }
        #region 报表数据
        public async Task<PageResult<GrossProfitByCustomer>> GetGrossProfitByCustomer(QueryModel queryModel)
        {
            return await this.orderRepository.GetGrossProfitByCustomer(queryModel);
        }
        public async Task<PageResult<GrossProfitByOrder>> GetGrossProfitByOrder(QueryModel qm)
        {
            return await this.orderRepository.GetGrossProfitByOrder(qm);
        }
        #endregion
    }
}
