using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mall.Common;
using Mall.Common.API;
using Mall.Common.Enum;
using Mall.Common.Enum.Goods;
using Mall.Common.Enum.User;
using Mall.Common.Plugin;
using Mall.Model.Entity.Finance;
using Mall.Model.Entity.Product;
using Mall.Model.Extend.BaseSetUp;
using Mall.Model.Extend.Finance;
using Mall.Model.Extend.Product;
using Mall.Model.Extend.User;
using Mall.Module.User;
using Mall.Repository;
using Mall.Repository.BaseSetUp;
using Mall.Repository.Finance;
using Mall.Repository.GuideCar;
using Mall.Repository.MarketingCenter;
using Mall.Repository.Product;
using Mall.Repository.User;
using Mall.ThirdCore.Message;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using VT.FW.DB;

namespace Mall.Module.Product
{
    /// <summary>
    /// 订单处理层 v2
    /// </summary>
    public class OrderModule_V2
    {
        /// <summary>
        /// 订单商品
        /// </summary>
        private readonly RB_Goods_OrderRepository goods_OrderRepository = new RB_Goods_OrderRepository();
        /// <summary>
        /// 订单明细
        /// </summary>
        private readonly RB_Goods_OrderDetailRepository goods_OrderDetailRepository = new RB_Goods_OrderDetailRepository();
        /// <summary>
        /// 区域
        /// </summary>
        private readonly Rb_destinationRepository destinationRepository = new Rb_destinationRepository();
        /// <summary>
        /// 会员
        /// </summary>
        private readonly RB_Member_UserRepository member_UserRepository = new RB_Member_UserRepository();


        /// <summary>
        /// 找人代付 订单详情
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public ApiResult GetAppletMyOrderAgentInfo(int orderId)
        {
            var model = goods_OrderRepository.GetEntity(orderId).RefMapperTo<RB_Goods_Order_Extend>();
            if (model == null)
            {
                return ApiResult.Failed("订单信息不存在，请核实后再试");
            }
            var umodel = member_UserRepository.GetEntity(model.UserId ?? 0);
            if (umodel == null)
            {
                return ApiResult.Failed("订单用户不存在，请核实后再试");
            }
            //查询订单明细
            var dlist = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { OrderId = orderId });
            if (dlist.Any())
            {
                string orderDetailIds = string.Join(",", dlist.Select(x => x.Id));
                foreach (var item in dlist)
                {
                    item.CoverImagePath = item.CoverImage;
                    item.IsApplyForAfterSale = 2;
                    if (item.PresentFXGrade > 0)
                    {
                        model.PresentFXGrade = 1;
                    }
                }
            }
            model.DetailList = dlist;

            if (model.MallBaseId == 19)
            {
                //620  20元的运费以及其他费用，商品总价600,2个商品，1-全款，1-订金60%；300*(1-(60/100))=120;
                //620-120-0=500
                decimal payIncome = (model.Income.Value) - (model?.PayIncome ?? 0);//实际应付金额-已支付金额
                if ((model?.PayIncome ?? 0) == 0)//支付定金金额
                {
                    decimal depositMoney = Math.Round(dlist.Where(x => x.DepositRatio > 0).Sum(x => (1 - (x.DepositRatio / 100)) * (x.Final_Price ?? 0)), 2);
                    payIncome = payIncome - depositMoney;//最终应付金额-定金-退款
                }
                model.GoodsDepositMoney = Math.Round(dlist.Where(x => x.DepositRatio > 0).Sum(x => ((x.DepositRatio / 100)) * (x.Final_Price ?? 0)), 2);
                model.ResultPayMoney = payIncome;
            }
            else
            {
                model.ResultPayMoney = model.Income ?? 0;
            }
            //地址
            model.DistrictAddress = ((model.Province.HasValue && model.Province.Value > 0) ? (destinationRepository.GetEntity(model.Province)?.Name ?? "") : "") + " " + ((model.City.HasValue && model.City.Value > 0) ? (destinationRepository.GetEntity(model.City)?.Name ?? "") : "") + " " + ((model.District.HasValue && model.District.Value > 0) ? (destinationRepository.GetEntity(model.District)?.Name ?? "") : "");

            model.IsCanApplyForAfterSale = 2;

            return ApiResult.Success("", new
            {
                model.OrderId,
                model.OrderNo,
                model.OrderStatus,
                UserInfo = new
                {
                    UserId = umodel.Id,
                    umodel.Name,
                    umodel.Photo
                },
                PayIncome = model.PayIncome ?? 0,
                model.ResultPayMoney,
                model.GoodsDepositMoney,
                OrderStatusName = model.OrderStatus.GetEnumName(),
                CreateDate = model.CreateDate.HasValue ? model.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                CancelTime = model.CancelTime.HasValue ? model.CancelTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                model.PaymentWay,
                PaymentWayName = model.PaymentWay.GetEnumName(),
                model.DeliveryMethod,
                DeliveryMethodName = model.DeliveryMethod.GetEnumName(),
                model.PreferPrice,
                model.Income,
                model.CouponMoney,
                model.FreightMoney,
                model.Consignee,
                model.Mobile,
                model.DistrictAddress,
                model.ShoppingAddress,
                IsHaveExpress = 2,
                DetailList = model.DetailList.Select(x => new
                {
                    DetailId = x.Id,
                    x.GoodsId,
                    x.GoodsName,
                    x.CoverImagePath,
                    SpecificationList = JsonConvert.DeserializeObject<List<string>>(x.Specification),
                    x.Number,
                    x.Final_Price,
                    x.IsComment,
                    x.IsApplyForAfterSale,
                    x.FreeShippingRemarks
                }),
                model.IsApplyForCancel,
                model.RejectRemark,
                model.IsCanApplyForAfterSale,
                model.PresentFXGrade
            });
        }
    }
}
