using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mall.Common;
using Mall.Common.Plugin;
using Mall.Model.Entity.User;
using Mall.Model.Extend.User;
using Mall.Repository;
using Mall.Repository.User;
using Mall.Repository.Product;
using Mall.Model.Extend.Product;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;

namespace Mall.Module.User
{
    /// <summary>
    /// 商户用户公共处理层
    /// </summary>
    public class UserCommonModule
    {
        /// <summary>
        /// 分销基础配置
        /// </summary>
        private readonly RB_Distributor_BasicsRepository distributor_BasicsRepository = new RB_Distributor_BasicsRepository();
        /// <summary>
        /// 分销自定义设置
        /// </summary>
        private readonly RB_Distributor_CustomRepository distributor_CustomRepository = new RB_Distributor_CustomRepository();
        /// <summary>
        /// 分类样式
        /// </summary>
        private readonly RB_Product_CategoryStyleRepository product_CategoryStyleRepository = new RB_Product_CategoryStyleRepository();
        /// <summary>
        /// 推荐设置
        /// </summary>
        private readonly RB_Product_RecommendRepository product_RecommendRepository = new RB_Product_RecommendRepository();
        /// <summary>
        /// 支付信息
        /// </summary>
        private readonly RB_Goods_Online_TradeRepository goods_Online_TradeRepository = new RB_Goods_Online_TradeRepository();
        /// <summary>
        /// 订单信息
        /// </summary>
        private readonly RB_Goods_OrderRepository goods_OrderRepository = new RB_Goods_OrderRepository();

        /// <summary>
        /// 订单商品信息
        /// </summary>
        private readonly RB_Goods_OrderDetailRepository goodsOrderDetailRepository = new RB_Goods_OrderDetailRepository();
        /// <summary>
        /// 会员信息
        /// </summary>
        private readonly RB_Member_UserRepository member_UserRepository = new RB_Member_UserRepository();


        private readonly MiniProgramMsgModule appletWeChatModule = new MiniProgramMsgModule();


        /// <summary>
        /// 初始化分销基础配置
        /// </summary>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <returns></returns>
        public bool InitializeDistributorBasicsInfo(int TenantId, int MallBaseId)
        {
            var OModel = distributor_BasicsRepository.GetList(new RB_Distributor_Basics_Extend() { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();
            if (OModel == null)
            {
                string GradeEntranceImage = new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("InitializeImages")["GradeEntranceImage"];
                return distributor_BasicsRepository.Insert(new RB_Distributor_Basics()
                {
                    Id = 0,
                    ApplicationProtocol = "",
                    ApplyFor = Common.Enum.User.DistributorApplyForEnum.TX,
                    BackgroundImage = 0,
                    CreateDate = DateTime.Now,
                    DailyWithdrawalLimit = -1,
                    DistributorCommissionType = 1,
                    DistributorCondition = Common.Enum.User.DistributorConditionEnum.WTJ,
                    DistributorTier = 1,
                    GradeEntrance = 1,
                    GradeEntranceImage = GradeEntranceImage,
                    IndexImage = 0,
                    InPurchasing = 1,
                    MallBaseId = MallBaseId,
                    MinimumWithdrawalLimit = 50,
                    OneCommission = 0,
                    ReferralsCondition = Common.Enum.User.DistrbutorReferralsEnum.SCDJ,
                    TenantId = TenantId,
                    ThreeCommission = 0,
                    TwoCommission = 0,
                    UpdateDate = DateTime.Now,
                    UserNotes = "",
                    WithdrawFee = 0,
                    WithdrawWay = "[" + (int)Common.Enum.User.DistrbutorWithdrawWayEnum.ZDDK + "]",
                    IsCommissionResidue = 2,
                    HpReferralsGradeAudit = 2,
                    IsWithdrawAll = 2,
                    IsEnableFXGrade = 2
                }) > 0;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 初始化分销自定义
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool InitializeDistributorCustomInfo(int TenantId, int MallBaseId)
        {
            var OModel = distributor_CustomRepository.GetList(new RB_Distributor_Custom_Extend() { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();
            if (OModel == null)
            {
                return distributor_CustomRepository.Insert(new RB_Distributor_Custom()
                {
                    Id = 0,
                    ApplicationAgreement = "分销申请协议",
                    HeadImage = Common.Config.GetFileUrl("/Upload/Set/1587968479000.png"),
                    BottomImage = Common.Config.GetFileUrl("/Upload/Set/1587968716000.png"),
                    ButtonColor = "#FF4544",
                    ButtonFilletPX = 40,
                    ButtonText = "申请成为分销商",
                    ButtonTextColor = "#FFFFFF",
                    DistributionApplication = "分销申请",
                    DistributionCommissionName = "分销佣金",
                    DistributionCommissionImage = Common.Config.GetFileUrl("/Upload/Set/1587968503000.png"),
                    DistributionOrderName = "分销订单",
                    DistributionOrderImage = Common.Config.GetFileUrl("/Upload/Set/1587968517000.png"),
                    WithdrawDetialsName = "提现明细",
                    WithdrawDetialsImage = Common.Config.GetFileUrl("/Upload/Set/1587968599000.png"),
                    MyTeamName = "我的团队",
                    MyTeamImage = Common.Config.GetFileUrl("/Upload/Set/1587968613000.png"),
                    PromoteQRCodeName = "推广二维码",
                    PromoteQRCodeImage = Common.Config.GetFileUrl("/Upload/Set/1587968626000.png"),
                    ReferrerName = "推荐人",
                    CommissionForWithdrawalName = "可提现佣金",
                    WithdrawDepositName = "提现",
                    CommissionWithdrawnName = "已提现佣金",
                    OutstandingCommissionName = "未结算佣金",
                    DistributorName = "分销商",
                    CommissionTobePaidName = "待打款佣金",
                    UserNotesName = "用户须知",
                    IWantToWithdrawName = "我要提现",
                    WithdrawalAmountName = "提现金额",
                    WithdrawalWayName = "提现方式",
                    OneDistributionName = "一级分销名称",
                    TwoDistributionName = "二级分销名称",
                    ThreeDistributionName = "三级分销名称",
                    CreateDate = DateTime.Now,
                    MallBaseId = MallBaseId,
                    TenantId = TenantId,
                    UpdateDate = DateTime.Now
                }) > 0;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 初始化分类样式
        /// </summary>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <returns></returns>
        public bool InitializeCategoryStyleInfo(int TenantId, int MallBaseId)
        {
            var OModel = product_CategoryStyleRepository.GetList(new RB_Product_CategoryStyle_Extend() { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();
            if (OModel == null)
            {
                return product_CategoryStyleRepository.Insert(new Model.Entity.Product.RB_Product_CategoryStyle()
                {
                    CategoryNum = 1,
                    CreateDate = DateTime.Now,
                    Id = 0,
                    MallBaseId = MallBaseId,
                    RowNum = 1,
                    Style = 1,
                    TenantId = TenantId,
                    Type = 1,
                    UpdateDate = DateTime.Now
                }) > 0;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 初始化商品推荐设置
        /// </summary>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <returns></returns>
        public bool InitializeProductRecommendInfo(int TenantId, int MallBaseId)
        {
            var oModel = product_RecommendRepository.GetList(new RB_Product_Recommend_Extend() { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();
            if (oModel == null)
            {
                return product_RecommendRepository.Insert(new Model.Entity.Product.RB_Product_Recommend()
                {
                    Id = 0,
                    CommentProductIds = "",
                    CommentRecommentStatus = 1,
                    CreateDate = DateTime.Now,
                    DetailRecommendNum = 6,
                    DetailRecommendStatus = 1,
                    IsCommentRecommend = 2,
                    IsOrderRecommend = 2,
                    MallBaseId = MallBaseId,
                    OrderCompleteStatus = 1,
                    OrderProductIds = "",
                    TenantId = TenantId,
                    UpdateDate = DateTime.Now
                }) > 0;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 新增微信支付后增加
        /// </summary>
        /// <param name="UserId">用户id</param>
        /// <param name="OrderId">订单id</param>
        /// <param name="Out_Trade_No">订单号</param>
        /// <param name="Transaction_Id">交易单号</param>
        /// <param name="PayWay">支付方式</param>
        /// <param name="PayType">支付类型</param>
        /// <param name="Money">金额</param>
        /// <param name="Pay_Result">状态</param>
        /// <returns></returns>
        public bool InsertOrderPayInfo(int UserId, int OrderId, string Out_Trade_No, string Transaction_Id, Common.Enum.Goods.OrderPayTypeEnum PayWay, string PayType, decimal Money, DateTime Time_End, int Pay_Result)
        {
            var umodel = member_UserRepository.GetEntity(UserId);
            if (umodel == null)
            {
                return false;
            }

            //判断订单状态是否是待支付  2020-06-16 Add By:W
            var oldOrder = goods_OrderRepository.GetEntity(OrderId);
            if (oldOrder == null)
            {
                return false;
            }
            if (oldOrder.OrderStatus != Common.Enum.Goods.OrderStatusEnum.NonPayment)
            {
                return false;
            }
            if (oldOrder.Income != Money)
            {
                return false;
            }

            //获取订单商品
            var orderGoodsList = goodsOrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend { TenantId = oldOrder.TenantId, MallBaseId = oldOrder.MallBaseId, OrderId = oldOrder.OrderId });

            bool flag = goods_Online_TradeRepository.Insert(new Model.Entity.Product.RB_Goods_Online_Trade()
            {
                Id = 0,
                User_Id = UserId,
                FinanceId = 0,
                CreateDate = DateTime.Now,
                IsRefund = 2,
                MallBaseId = umodel.MallBaseId,
                Money = Money,
                OrderId = OrderId,
                Out_Trade_No = Out_Trade_No,
                PayType = PayType,
                PayWay = PayWay,
                Pay_Date = Time_End,
                Pay_Result = Pay_Result,
                RefundMoney = 0,
                RefundStatus = 0,
                RefundTrade_Order = "",
                Remarks = umodel.Name + "(id:" + UserId + ")",
                TenantId = umodel.TenantId,
                Transaction_Id = Transaction_Id,
                Type = 1
            }) > 0;
            if (flag)
            {
                //更新订单信息
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Goods_Order_Extend.OrderStatus),Common.Enum.Goods.OrderStatusEnum.WaitSendGoods},
                    { nameof(RB_Goods_Order_Extend.MerchantsNo),Out_Trade_No},
                    { nameof(RB_Goods_Order_Extend.PaymentTime),Time_End},
                    { nameof(RB_Goods_Order_Extend.PaymentWay),Common.Enum.Goods.OrderPaymentTypeEnum.OnlinePayment}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Goods_Order_Extend.OrderId),
                          FiledValue=OrderId,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                goods_OrderRepository.Update(keyValues, wheres);
                //下线
                if (umodel.DownlineCondition == Common.Enum.User.DistrbutorReferralsEnum.SCFK && umodel.IsBeDownline == 2)
                {
                    //首次下单成为下线
                    Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                        {nameof(RB_Member_User_Extend.SuperiorId),umodel.WaitSuperiorId },
                        {nameof(RB_Member_User_Extend.IsBeDownline),1 },
                        {nameof(RB_Member_User_Extend.BeDownlineDate),DateTime.Now },
                    };
                    List<WhereHelper> wheres1 = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_Member_User_Extend.Id),
                                  FiledValue=umodel.Id,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                    member_UserRepository.Update(keyValues1, wheres1);
                }



                //发送订阅消息

                string goodsName = orderGoodsList.FirstOrDefault().GoodsName;
                if (orderGoodsList.Count > 1)
                {
                    if (goodsName.Length > 6)
                    {
                        goodsName = goodsName.Substring(0, 6);
                    }
                    goodsName += "等" + orderGoodsList.Count + "件";
                }
                else
                {
                    if (goodsName.Length > 10)
                    {
                        goodsName = goodsName.Substring(0, 10);
                    }
                }
                appletWeChatModule.SendOrderSucceedMsg(oldOrder.TenantId, oldOrder.MallBaseId, umodel.OpenId, oldOrder.OrderNo, oldOrder.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss"),  (oldOrder.Income ?? 0).ToString(), goodsName);
            }
            return flag;
        }
    }
}
