
using Mall.CacheManager.AppletWeChat;
using Mall.Common;
using Mall.Common.Enum.Goods;
using Mall.Common.Enum.User;
using Mall.Common.Plugin;
using Mall.Model.Entity.BaseSetUp;
using Mall.Model.Entity.Finance;
using Mall.Model.Entity.Product;
using Mall.Model.Entity.User;
using Mall.Model.Extend.Education;
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.Education;
using Mall.Repository.Finance;
using Mall.Repository.Product;
using Mall.Repository.User;
using Mall.WindowsService.Helper;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VT.FW.DB;

namespace Mall.WindowsService.Module
{
    public class FinanceModule
    {
        /// <summary>
        /// 财务单据规则
        /// </summary>
        private static RB_Finance_ConfigurineRepository financeConfigurineRepository = new RB_Finance_ConfigurineRepository();

        /// <summary>
        /// 财务生成记录
        /// </summary>
        private static RB_Finance_RecordRepository financeRecordRepository = new RB_Finance_RecordRepository();
        /// <summary>
        /// 财务生成记录详情
        /// </summary>
        private static RB_Finance_RecordDetailRepository financeRecordDetailRepository = new RB_Finance_RecordDetailRepository();

        /// <summary>
        /// 订单详情
        /// </summary>
        private static RB_Goods_OrderDetailRepository goodsOrderDetailRepository = new RB_Goods_OrderDetailRepository();
        /// <summary>
        /// 订单
        /// </summary>
        private static RB_Goods_OrderRepository goods_OrderRepository = new RB_Goods_OrderRepository();
        /// <summary>
        /// 基础配置
        /// </summary>
        private static RB_MallBaseRepository mallBaseRepository = new RB_MallBaseRepository();
        /// <summary>
        /// 订单日志
        /// </summary>
        private static RB_Goods_LogRepository goods_LogRepository = new RB_Goods_LogRepository();
        /// <summary>
        /// 商品
        /// </summary>
        private static RB_GoodsRepository goodsRepository = new RB_GoodsRepository();
        /// <summary>
        /// 商品规格价格
        /// </summary>
        private static RB_Goods_SpecificationPriceRepository goods_SpecificationPriceRepository = new RB_Goods_SpecificationPriceRepository();
        /// <summary>
        /// 会员
        /// </summary>
        private static RB_Member_UserRepository member_UserRepository = new RB_Member_UserRepository();
        /// <summary>
        /// 用户积分
        /// </summary>
        private static RB_Member_IntegralRepository member_IntegralRepository = new RB_Member_IntegralRepository();
        /// <summary>
        /// 优惠卷
        /// </summary>
        private static RB_Member_CouponRepository member_CouponRepository = new RB_Member_CouponRepository();
        /// <summary>
        /// 返佣
        /// </summary>
        private static RB_Goods_OrderCommissionRepository goods_OrderCommissionRepository = new RB_Goods_OrderCommissionRepository();
        /// <summary>
        /// 售后订单列表
        /// </summary>
        private static RB_Goods_OrderAfterSaleRepository goods_OrderAfterSaleRepository = new RB_Goods_OrderAfterSaleRepository();
        /// <summary>
        /// 分销商
        /// </summary>
        private static RB_Distributor_InfoRepository distributor_InfoRepository = new RB_Distributor_InfoRepository();
        /// <summary>
        /// 订单明细
        /// </summary>
        private static RB_Goods_OrderDetailRepository goods_OrderDetailRepository = new RB_Goods_OrderDetailRepository();
        /// <summary>
        /// 售后订单流程
        /// </summary>
        private static RB_Goods_OrderAfterSaleLogRepository goods_OrderAfterSaleLogRepository = new RB_Goods_OrderAfterSaleLogRepository();
        /// <summary>
        /// 分销基础配置
        /// </summary>
        private static RB_Distributor_BasicsRepository distributor_BasicsRepository = new RB_Distributor_BasicsRepository();
        private static RB_Distributor_FXGradeRepository distributor_FXGradeRepository = new RB_Distributor_FXGradeRepository();
        private static RB_Vip_BuyRepository vip_BuyRepository = new RB_Vip_BuyRepository();
        /// <summary>
        /// 推荐返佣
        /// </summary>
        private static RB_Goods_OrderIntroductionRepository goods_OrderIntroductionRepository = new RB_Goods_OrderIntroductionRepository();
        /// <summary>
        /// 微店
        /// </summary>
        private static RB_SmallShops_InfoRepository smallShops_InfoRepository = new RB_SmallShops_InfoRepository();
        /// <summary>
        /// 微店佣金
        /// </summary>
        private static RB_SmallShops_CommissionRepository smallShops_CommissionRepository = new RB_SmallShops_CommissionRepository();
        /// <summary>
        /// 微店基础
        /// </summary>
        private static RB_MicroShop_BasicsRepository microShop_BasicsRepository = new RB_MicroShop_BasicsRepository();
        /// <summary>
        /// 小程序
        /// </summary>
        private static RB_MiniProgramRepository miniProgramRepository = new RB_MiniProgramRepository();
        /// <summary>
        /// 微店提现
        /// </summary>
        private static RB_SmallShops_RemitRepository smallShops_RemitRepository = new RB_SmallShops_RemitRepository();
        /// <summary>
        /// vip购买仓储层
        /// </summary>
        private static readonly RB_Vip_BuyRepository vipBuyRepository = new RB_Vip_BuyRepository();
        /// <summary>
        /// 商品可预定日期
        /// </summary>
        private static readonly RB_Goods_TargetDateRepository goods_TargetDateRepository = new RB_Goods_TargetDateRepository();
        /// <summary>
        /// 用户课程卡
        /// </summary>
        private static readonly RB_Education_MemberCouponRepository education_MemberCouponRepository = new RB_Education_MemberCouponRepository();
        /// <summary>
        /// 课程卡使用
        /// </summary>
        private static readonly RB_Education_MemberUseCouponRepository education_MemberUseCouponRepository = new RB_Education_MemberUseCouponRepository();
        /// <summary>
        /// 活动
        /// </summary>
        private static readonly RB_Goods_ActivityRepository goods_ActivityRepository = new RB_Goods_ActivityRepository();
        /// <summary>
        /// 活动完成名单
        /// </summary>
        private static readonly RB_Goods_Activity_GetRepository goods_Activity_GetRepository = new RB_Goods_Activity_GetRepository();
        /// <summary>
        /// 储值卡
        /// </summary>
        private static readonly RB_Member_DepositBuyRepository member_DepositBuyRepository = new RB_Member_DepositBuyRepository();
        /// <summary>
        /// 储值卡流水
        /// </summary>
        private static readonly RB_Member_DepositBalanceRepository member_DepositBalanceRepository = new RB_Member_DepositBalanceRepository();



        #region 收入

        /// <summary>
        /// 商品订单收入单据
        /// </summary>
        /// <returns></returns>
        public static bool OrderIncomeFinanceModule()
        {
            var flag = false;

            try
            {
                //先查询规则
                var financeConfigurineList = financeConfigurineRepository.GetList(new RB_Finance_Configurine_Extend { Type = 1 });

                //根据规则中的小程序，查询订单详情信息
                if (financeConfigurineList != null && financeConfigurineList.Any())
                {
                    foreach (var item in financeConfigurineList)
                    {
                        if (item.StartTime.HasValue && item.StartTime < System.DateTime.Now)//判断开始时间是否大于当前时间
                        {
                            //查询今天是否已经生成了财务单据
                            var addFinance = false;

                            DateTime startDate = System.DateTime.Now.AddDays(-1);
                            var recordModel = financeRecordRepository.GetList(new RB_Finance_Record_Extend { TenantId = item.TenantId, MallBaseId = item.MallBaseId, Type = 1 }).OrderByDescending(x => x.CreateDate).FirstOrDefault();
                            if (recordModel == null)//今天没生成单据
                            {
                                if (Convert.ToDateTime(item.StartTime.Value.AddDays(item.IntervalDay ?? 0).ToString("yyyy-MM-dd 00:00:00")) <= Convert.ToDateTime(System.DateTime.Now.ToString("yyyy-MM-dd 00:00:00")))//判断开始时间加上执行周期是否等于当前日期
                                {
                                    startDate = item.StartTime.Value;
                                    addFinance = true;
                                }
                            }
                            else
                            {
                                if (Convert.ToDateTime(recordModel.CreateDate.Value.AddDays(item.IntervalDay ?? 0).ToString("yyyy-MM-dd 00:00:00")) <= Convert.ToDateTime(System.DateTime.Now.ToString("yyyy-MM-dd 00:00:00")))//判断最近一次执行的时间加上执行周期是否等于当前日期
                                {
                                    startDate = recordModel.CreateDate.Value;
                                    addFinance = true;
                                }
                            }
                            // Helper.LogHelper.Write("addFinance：" + addFinance.ToString());
                            DateTime endDate = startDate.AddDays(item.IntervalDay ?? 0);//结束时间
                            if (addFinance)//满足今天执行的条件查询间隔周期的订单
                            {
                                StringBuilder builder = new StringBuilder();
                                //                                builder.AppendFormat($@" SELECT a.*,b.OrderNo,b.OrderClassify from rb_goods_orderdetail as a LEFT JOIN rb_goods_order as b on a.OrderId=b.OrderId
                                //where b.TenantId={item.TenantId} and b.MallBaseId={item.MallBaseId} and b.OrderSource!=6  and  DATE_FORMAT(b.PaymentTime,'%y-%m-%d')>= DATE_FORMAT('{startDate}','%y-%m-%d') 
                                //and  DATE_FORMAT(b.PaymentTime,'%y-%m-%d')<DATE_FORMAT('{endDate}','%y-%m-%d') AND b.OrderStatus IN (2, 3, 4, 5, 6) ");
                                builder.AppendFormat($@" SELECT a.*,b.OrderNo,b.OrderClassify from rb_goods_orderdetail as a LEFT JOIN rb_goods_order as b on a.OrderId=b.OrderId
where b.TenantId={item.TenantId} and b.MallBaseId={item.MallBaseId} and b.OrderSource!=6  and  DATE_FORMAT(b.PaymentTime,'%y-%m-%d')>= DATE_FORMAT('{startDate}','%y-%m-%d') 
and  DATE_FORMAT(b.PaymentTime,'%y-%m-%d')<DATE_FORMAT('{endDate}','%y-%m-%d') AND (b.OrderStatus IN (2, 3, 4, 5, 6) or (b.OrderStatus=7 and DATE_FORMAT(b.PaymentTime,'%y-%m-%d')< DATE_FORMAT(b.CancelTime,'%y-%m-%d')))");
                                //                                builder.AppendFormat($@" SELECT a.*,b.OrderNo from rb_goods_orderdetail as a LEFT JOIN rb_goods_order as b on a.OrderId=b.OrderId
                                //where b.TenantId={item.TenantId} and b.MallBaseId={item.MallBaseId}  and  DATE_FORMAT(b.PaymentTime,'%y-%m-%d')>= DATE_FORMAT('{startDate}','%y-%m-%d') 
                                //and  DATE_FORMAT(b.PaymentTime,'%y-%m-%d')<DATE_FORMAT('{endDate}','%y-%m-%d') AND (
                                //	b.OrderStatus IN (2, 3, 4, 5, 6) OR ( b.OrderStatus = 7  AND DATE_FORMAT(b.PaymentTime, '%y-%m-%d') >= DATE_FORMAT('{startDate}', '%y-%m-%d')
                                //		AND DATE_FORMAT(b.PaymentTime, '%y-%m-%d') < DATE_FORMAT('{endDate}', '%y-%m-%d')))");

                                //Helper.LogHelper.Write("sql语句：" + builder.ToString());
                                var goodsDetailList = goodsOrderDetailRepository.Get<RB_Goods_OrderDetail_Extend>(builder.ToString()).ToList();

                                var result = new List<RB_Goods_OrderDetail_Extend>();

                                RB_Finance_Record_Extend record = new RB_Finance_Record_Extend();
                                record.MallBaseId = item.MallBaseId;
                                record.TenantId = item.TenantId;
                                record.Type = 1;
                                record.CreateDate = System.DateTime.Now;
                                record.RecordDetailList = new List<RB_Finance_RecordDetail_Extend>();


                                List<RB_Finance_RecordDetail_Extend> orderGoodsList = new List<RB_Finance_RecordDetail_Extend>();
                                if (goodsDetailList != null && goodsDetailList.Any())//获取当前需要生成入款单的订单是否已经生成财务单据
                                {
                                    string orderIds = string.Join(",", goodsDetailList.Select(x => x.OrderId));
                                    orderGoodsList = financeRecordDetailRepository.GetListByOrderIds(orderIds, new RB_Finance_RecordDetail_Extend { TenantId = item.TenantId, MallBaseId = item.MallBaseId, Type = 1 });
                                }
                                else
                                {
                                    record.FinanceId = 0;
                                    record.IsFinanceAll = 0;
                                    financeRecordRepository.Insert(record);
                                    Helper.LogHelper.Write("暂无数据");
                                    return false;
                                }

                                #region 查询所有的订单
                                List<RB_ECFinanceId_Relation> ECList = new List<RB_ECFinanceId_Relation>();
                                #endregion
                                foreach (var orderGoodsItem in goodsDetailList)
                                {
                                    bool isAdd = true;
                                    if (orderGoodsList != null && orderGoodsList.Any())
                                    {
                                        if (orderGoodsList.Where(x => x.OrderDetailId == orderGoodsItem.Id).Count() > 0)//判断订单是否已经有入款单据生成
                                        {
                                            isAdd = false;
                                        }
                                    }
                                    if (isAdd)
                                    {
                                        if ((orderGoodsItem.Final_Price - orderGoodsItem.DepositMoney) > 0)
                                        {
                                            if (orderGoodsItem.OrderClassify == 1 && orderGoodsItem.CarType != GuideCarGoodsTypeEnum.Line)
                                            {
                                                var newOrderGoods = new RB_Goods_OrderDetail_Extend
                                                {
                                                    FinanceType = 1,
                                                    Final_Price = orderGoodsItem.Final_Price - orderGoodsItem.DepositMoney,
                                                    Number = 1,
                                                    FreightMoney = orderGoodsItem.FreightMoney - orderGoodsItem.DepositFreightMoney,
                                                    GoodsName = orderGoodsItem.GoodsName,
                                                    OrderNo = orderGoodsItem.OrderNo,
                                                    Id = orderGoodsItem.Id,
                                                    InsuranceMoney = orderGoodsItem.InsuranceMoney
                                                };
                                                result.Add(newOrderGoods);
                                            }
                                            else
                                            {
                                                var newOrderGoods = new RB_Goods_OrderDetail_Extend
                                                {
                                                    FinanceType = 1,
                                                    Final_Price = orderGoodsItem.Final_Price - orderGoodsItem.DepositMoney,
                                                    Number = orderGoodsItem.Number,
                                                    FreightMoney = orderGoodsItem.FreightMoney - orderGoodsItem.DepositFreightMoney,
                                                    GoodsName = orderGoodsItem.GoodsName,
                                                    OrderNo = orderGoodsItem.OrderNo,
                                                    Id = orderGoodsItem.Id,
                                                    InsuranceMoney = orderGoodsItem.InsuranceMoney
                                                };
                                                result.Add(newOrderGoods);
                                            }

                                            //newOrderGoods = orderGoodsItem;
                                            //newOrderGoods.FinanceType = 1;


                                        }
                                        if (orderGoodsItem.FreightMoney.HasValue && orderGoodsItem.FreightMoney.Value > 0)
                                        {
                                            //var newOrderGoods = new RB_Goods_OrderDetail_Extend();
                                            //newOrderGoods = orderGoodsItem;
                                            //newOrderGoods.FinanceType = 2;
                                            var newOrderGoods = new RB_Goods_OrderDetail_Extend
                                            {
                                                FinanceType = 2,
                                                Final_Price = orderGoodsItem.Final_Price - orderGoodsItem.DepositMoney,
                                                Number = 1,
                                                FreightMoney = orderGoodsItem.FreightMoney - orderGoodsItem.DepositFreightMoney,
                                                GoodsName = orderGoodsItem.GoodsName,
                                                OrderNo = orderGoodsItem.OrderNo,
                                                Id = orderGoodsItem.Id,
                                                InsuranceMoney = orderGoodsItem.InsuranceMoney
                                            };
                                            result.Add(newOrderGoods);
                                        }

                                        if (orderGoodsItem.InsuranceMoney.HasValue && orderGoodsItem.InsuranceMoney.Value > 0)
                                        {
                                            //var newOrderGoods = new RB_Goods_OrderDetail_Extend();
                                            //newOrderGoods = orderGoodsItem;
                                            //newOrderGoods.FinanceType = 2;
                                            var newOrderGoods = new RB_Goods_OrderDetail_Extend
                                            {
                                                FinanceType = 3,
                                                Final_Price = orderGoodsItem.Final_Price - orderGoodsItem.DepositMoney,
                                                Number = 1,
                                                FreightMoney = orderGoodsItem.FreightMoney - orderGoodsItem.DepositFreightMoney,
                                                GoodsName = orderGoodsItem.GoodsName,
                                                OrderNo = orderGoodsItem.OrderNo,
                                                Id = orderGoodsItem.Id,
                                                InsuranceMoney = orderGoodsItem.InsuranceMoney
                                            };
                                            result.Add(newOrderGoods);
                                        }
                                        RB_Finance_RecordDetail_Extend financeRecordDetail = new RB_Finance_RecordDetail_Extend
                                        {

                                            ID = 0,
                                            RecordId = 0,
                                            Type = record.Type,
                                            TenantId = record.TenantId,
                                            MallBaseId = record.MallBaseId,
                                            FinanceId = 0,
                                            CreateDate = record.CreateDate,
                                            Name = orderGoodsItem.GoodsName,
                                            OrderId = orderGoodsItem.OrderId ?? 0,
                                            OrderDetailId = orderGoodsItem.Id,
                                            GoodsPrice = ((orderGoodsItem.Final_Price ?? 0) - (orderGoodsItem.FreightMoney ?? 0)),
                                            FreightMoney = orderGoodsItem.FreightMoney,
                                            Unit_Price = orderGoodsItem.Unit_Price,
                                            Number = orderGoodsItem.Number,
                                            InsuranceCostMoney = orderGoodsItem.InsuranceCostMoney
                                        };
                                        record.RecordDetailList.Add(financeRecordDetail);
                                        ECList.Add(new RB_ECFinanceId_Relation()
                                        {
                                            ECOrderId = orderGoodsItem.OrderId,
                                            ECOrderDetailId = orderGoodsItem.Id
                                        });
                                    }
                                }

                                if (result != null && result.Any())
                                {
                                    decimal OriginalFee = 0;
                                    var goodsDetailGroupList = goodsDetailList.GroupBy(x => x.OrderId);
                                    foreach (var goodsDetailGroupItem in goodsDetailGroupList)
                                    {
                                        decimal totalPrice = goodsDetailList.Where(x => x.OrderId == goodsDetailGroupItem.Key).Sum(x => (x.FreightMoney ?? 0) + (x.Final_Price ?? 0) + (x.InsuranceMoney ?? 0)) * (Convert.ToDecimal(Config.SettlementRate) / 100);

                                        OriginalFee += Math.Round(totalPrice, 2, MidpointRounding.AwayFromZero);
                                    }
                                    var detailList = result.Select(x => new
                                    {
                                        CostTypeId = x.FinanceType == 1 ? item.IncomeCostTypeId : (x.FinanceType == 2 ? item.FreightCostTypeId : item.InsuranceTypeId),
                                        Number = x.FinanceType == 1 ? x.Number : 1,
                                        OriginalMoney = x.FinanceType == 1 ? (x.Final_Price ?? 0) : (x.FinanceType == 2 ? (x.FreightMoney ?? 0) : (x.InsuranceMoney ?? 0)),
                                        UnitPrice = x.FinanceType == 1 ? ((x.Final_Price ?? 0) / (x.Number ?? 0)) : (x.FinanceType == 2 ? (x.FreightMoney ?? 0) : (x.InsuranceMoney ?? 0)),
                                        Remark = x.GoodsName + x.OrderNo
                                    });
                                    var financeObj = new
                                    {
                                        CreateBy = Config.IncomeDirector,
                                        item.IsPublic,
                                        BType = item.AccountType,
                                        AccountId = item.AccountId,
                                        WBMoney = (result.Sum(x => x.FinanceType == 1 ? (x.Final_Price ?? 0) : (x.FreightMoney ?? 0))) - OriginalFee,
                                        RB_Branch_Id = Config.IncomeBranchId,
                                        RemitterName = item.RemitterName,
                                        TradeDate = System.DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"),
                                        AccountNumber = System.DateTime.Now.AddDays(-1).ToString("yyyyMMdd"),
                                        TemplateId = item.WorkFlowId,
                                        OrderSource = 16,
                                        Remark = System.DateTime.Now.ToString("yyyy年MM月dd日") + "自动生成财务单据",
                                        detailList,
                                        OriginalFee,
                                        RB_Depart_Id = Config.IncomeDepartment,
                                        ECOrderList = ECList
                                    };
                                    string sign = EncryptionHelper.AesEncrypt(JsonHelper.Serialize(financeObj), Config.FinanceKey);
                                    var resultInfo = new
                                    {
                                        msg = sign,
                                    };
                                    string apiResult = Mall.Common.Plugin.HttpHelper.HttpPost(Config.IncomeFinanceApi, JsonHelper.Serialize(resultInfo), "");
                                    JObject parmsJob = JObject.Parse(apiResult);
                                    string resultCode = parmsJob.GetStringValue("resultCode");
                                    int frid = parmsJob.GetInt("data", 0);
                                    if (resultCode == "1" && frid > 0)//新增记录
                                    {
                                        record.FinanceId = frid;
                                        int recordId = financeRecordRepository.Insert(record);
                                        Helper.LogHelper.Write("财务单据ID：" + frid + ",记录id：" + recordId + "订单数量：" + record.RecordDetailList.Count());
                                        record.RecordDetailList.ForEach(x => x.RecordId = recordId);
                                        record.RecordDetailList.ForEach(x => x.FinanceId = frid);
                                        flag = financeRecordDetailRepository.InsertBatch(record.RecordDetailList);
                                    }

                                    Helper.LogHelper.Write(apiResult);
                                }
                            }


                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string str = financeConfigurineRepository.ConnectionStr;
                Helper.LogHelper.Write("数据库连接1：" + str + "错误日志" + ex.Message);
            }

            return flag;
        }


        /// <summary>
        /// 储值卡订单收入单据
        /// </summary>
        /// <returns></returns>
        public static bool DepositIncomeFinanceModule()
        {
            var flag = false;

            try
            {
                //先查询规则
                var financeConfigurineList = financeConfigurineRepository.GetList(new RB_Finance_Configurine_Extend { Type = 1 });

                //根据规则中的小程序，查询订单详情信息
                if (financeConfigurineList != null && financeConfigurineList.Any())
                {
                    foreach (var item in financeConfigurineList)
                    {
                        if (item.StartTime.HasValue && item.StartTime < System.DateTime.Now)//判断开始时间是否大于当前时间
                        {
                            //查询今天是否已经生成了财务单据
                            var addFinance = false;

                            DateTime startDate = System.DateTime.Now.AddDays(-1);
                            var recordModel = financeRecordRepository.GetList(new RB_Finance_Record_Extend { TenantId = item.TenantId, MallBaseId = item.MallBaseId, Type = 5 }).OrderByDescending(x => x.CreateDate).FirstOrDefault();
                            if (recordModel == null)//今天没生成单据
                            {
                                if (Convert.ToDateTime(item.StartTime.Value.AddDays(item.IntervalDay ?? 0).ToString("yyyy-MM-dd 00:00:00")) <= Convert.ToDateTime(System.DateTime.Now.ToString("yyyy-MM-dd 00:00:00")))//判断开始时间加上执行周期是否等于当前日期
                                {
                                    startDate = item.StartTime.Value;
                                    addFinance = true;
                                }
                            }
                            else
                            {
                                if (Convert.ToDateTime(recordModel.CreateDate.Value.AddDays(item.IntervalDay ?? 0).ToString("yyyy-MM-dd 00:00:00")) <= Convert.ToDateTime(System.DateTime.Now.ToString("yyyy-MM-dd 00:00:00")))//判断最近一次执行的时间加上执行周期是否等于当前日期
                                {
                                    startDate = recordModel.CreateDate.Value;
                                    addFinance = true;
                                }
                            }
                            // Helper.LogHelper.Write("addFinance：" + addFinance.ToString());
                            DateTime endDate = startDate.AddDays(item.IntervalDay ?? 0);//结束时间
                            if (addFinance)//满足今天执行的条件查询间隔周期的订单
                            {
                                StringBuilder builder = new StringBuilder();
                                //                                builder.AppendFormat($@" SELECT a.*,b.OrderNo,b.OrderClassify from rb_goods_orderdetail as a LEFT JOIN rb_goods_order as b on a.OrderId=b.OrderId
                                //where b.TenantId={item.TenantId} and b.MallBaseId={item.MallBaseId} and b.OrderSource!=6  and  DATE_FORMAT(b.PaymentTime,'%y-%m-%d')>= DATE_FORMAT('{startDate}','%y-%m-%d') 
                                //and  DATE_FORMAT(b.PaymentTime,'%y-%m-%d')<DATE_FORMAT('{endDate}','%y-%m-%d') AND b.OrderStatus IN (2, 3, 4, 5, 6) ");
                                builder.AppendFormat($@"SELECT a.* from rb_member_depositbuy as a 
where a.TenantId={item.TenantId} and a.MallBaseId={item.MallBaseId}  and  DATE_FORMAT(a.PayTime,'%y-%m-%d')>= DATE_FORMAT('{startDate}','%y-%m-%d') 
and  DATE_FORMAT(a.PayTime,'%y-%m-%d')<DATE_FORMAT('{endDate}','%y-%m-%d') AND a.`Status`=1 and a.RechargeType=1");

                                var goodsDetailList = member_DepositBuyRepository.Get<RB_Member_DepositBuy_Extend>(builder.ToString()).ToList();

                                // var result = new List<RB_Goods_OrderDetail_Extend>();

                                RB_Finance_Record_Extend record = new RB_Finance_Record_Extend();
                                record.MallBaseId = item.MallBaseId;
                                record.TenantId = item.TenantId;
                                record.Type = 5;
                                record.CreateDate = System.DateTime.Now;
                                record.RecordDetailList = new List<RB_Finance_RecordDetail_Extend>();


                                List<RB_Finance_RecordDetail_Extend> orderGoodsList = new List<RB_Finance_RecordDetail_Extend>();
                                if (goodsDetailList != null && goodsDetailList.Any())//获取当前需要生成入款单的订单是否已经生成财务单据
                                {
                                    string orderIds = string.Join(",", goodsDetailList.Select(x => x.Id));
                                    orderGoodsList = financeRecordDetailRepository.GetListByOrderIds(orderIds, new RB_Finance_RecordDetail_Extend { TenantId = item.TenantId, MallBaseId = item.MallBaseId, Type = 5 });
                                }
                                else
                                {
                                    record.FinanceId = 0;
                                    record.IsFinanceAll = 0;
                                    financeRecordRepository.Insert(record);
                                    Helper.LogHelper.Write("暂无数据");
                                    return false;
                                }

                                #region 查询所有的订单
                                List<RB_ECFinanceId_Relation> ECList = new List<RB_ECFinanceId_Relation>();
                                #endregion
                                foreach (var orderGoodsItem in goodsDetailList)
                                {
                                    bool isAdd = true;
                                    if (orderGoodsList != null && orderGoodsList.Any())
                                    {
                                        if (orderGoodsList.Where(x => x.OrderDetailId == orderGoodsItem.Id).Count() > 0)//判断订单是否已经有入款单据生成
                                        {
                                            isAdd = false;
                                        }
                                    }
                                    if (isAdd && orderGoodsItem.SalePrice > 0)
                                    {

                                        RB_Finance_RecordDetail_Extend financeRecordDetail = new RB_Finance_RecordDetail_Extend
                                        {

                                            ID = 0,
                                            RecordId = 0,
                                            Type = record.Type,
                                            TenantId = record.TenantId,
                                            MallBaseId = record.MallBaseId,
                                            FinanceId = 0,
                                            CreateDate = record.CreateDate,
                                            Name = orderGoodsItem.Name,
                                            OrderId = orderGoodsItem.Id,
                                            OrderDetailId = orderGoodsItem.Id,
                                            GoodsPrice = orderGoodsItem.SalePrice,
                                            FreightMoney = 0,
                                            Unit_Price = orderGoodsItem.SalePrice,
                                            Number = 1,
                                            InsuranceCostMoney = 0
                                        };
                                        record.RecordDetailList.Add(financeRecordDetail);
                                        ECList.Add(new RB_ECFinanceId_Relation()
                                        {
                                            ECOrderId = orderGoodsItem.Id,
                                            ECOrderDetailId = orderGoodsItem.Id
                                        });
                                    }
                                }

                                if (goodsDetailList != null && goodsDetailList.Any())
                                {
                                    decimal OriginalFee = 0;

                                    foreach (var goodsDetailGroupItem in goodsDetailList)
                                    {
                                        decimal totalPrice = goodsDetailGroupItem.SalePrice * (Convert.ToDecimal(Config.SettlementRate) / 100);

                                        OriginalFee += Math.Round(totalPrice, 2, MidpointRounding.AwayFromZero);
                                    }
                                    var detailList = goodsDetailList.Select(x => new
                                    {
                                        CostTypeId = item.DepositIncomeTypeId,
                                        Number = 1,
                                        OriginalMoney = x.SalePrice,
                                        UnitPrice = x.SalePrice,
                                        Remark = x.Name + x.OrderNo
                                    });
                                    var financeObj = new
                                    {
                                        CreateBy = Config.IncomeDirector,
                                        item.IsPublic,
                                        BType = item.AccountType,
                                        AccountId = item.AccountId,
                                        WBMoney = goodsDetailList.Sum(x => x.SalePrice) - OriginalFee,
                                        RB_Branch_Id = Config.IncomeBranchId,
                                        RemitterName = item.RemitterName,
                                        TradeDate = System.DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"),
                                        AccountNumber = System.DateTime.Now.AddDays(-1).ToString("yyyyMMdd"),
                                        TemplateId = item.WorkFlowId,
                                        OrderSource = 16,
                                        Remark = System.DateTime.Now.ToString("yyyy年MM月dd日") + "自动生成财务单据",
                                        detailList,
                                        OriginalFee,
                                        RB_Depart_Id = Config.IncomeDepartment,
                                        ECOrderList = ECList
                                    };
                                    string sign = EncryptionHelper.AesEncrypt(JsonHelper.Serialize(financeObj), Config.FinanceKey);
                                    var resultInfo = new
                                    {
                                        msg = sign,
                                    };

                                    string apiResult = Mall.Common.Plugin.HttpHelper.HttpPost(Config.IncomeFinanceApi, JsonHelper.Serialize(resultInfo), "");
                                    JObject parmsJob = JObject.Parse(apiResult);
                                    string resultCode = parmsJob.GetStringValue("resultCode");
                                    int frid = parmsJob.GetInt("data", 0);
                                    if (resultCode == "1" && frid > 0)//新增记录
                                    {
                                        record.FinanceId = frid;
                                        int recordId = financeRecordRepository.Insert(record);
                                        Helper.LogHelper.Write("财务单据ID：" + frid + ",记录id：" + recordId + "订单数量：" + record.RecordDetailList.Count());
                                        record.RecordDetailList.ForEach(x => x.RecordId = recordId);
                                        record.RecordDetailList.ForEach(x => x.FinanceId = frid);
                                        flag = financeRecordDetailRepository.InsertBatch(record.RecordDetailList);
                                    }

                                    Helper.LogHelper.Write(apiResult);
                                }
                            }


                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string str = financeConfigurineRepository.ConnectionStr;
                Helper.LogHelper.Write("数据库连接1：" + str + "错误日志" + ex.Message);
            }

            return flag;
        }
        #endregion

        #region 成本

        #endregion

        #region 订单取消

        /// <summary>
        /// 自动取消订单
        /// </summary>
        /// <returns></returns>
        public static bool AutoCancelOrder()
        {
            try
            {
                var list = mallBaseRepository.GetListRepository(new Mall.Model.Extend.BaseSetUp.RB_MallBase_Extend() { });
                foreach (var item in list)
                {
                    if (item.CancelTime > 0)
                    {
                        //查询未付款的所有订单
                        var olist = goods_OrderRepository.GetCanCancelOrderList(item.CancelTime, item.TenantId, item.MallBaseId);
                        List<int> classIdList = new List<int>();
                        foreach (var qitem in olist)
                        {
                            try
                            {
                                string cacheOrderId = OrderPayReidsCache.Get(qitem.OrderId.ToString());
                                if (string.IsNullOrWhiteSpace(cacheOrderId))
                                {
                                    Dictionary<string, object> keyValues = new Dictionary<string, object>() { };
                                    keyValues.Add(nameof(RB_Goods_Order_Extend.OrderStatus), OrderStatusEnum.Cancel);
                                    keyValues.Add(nameof(RB_Goods_Order_Extend.CancelTime), DateTime.Now);

                                    List<WhereHelper> wheres = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName=nameof(RB_Goods_Order_Extend.OrderId),
                                      FiledValue=qitem.OrderId,
                                       OperatorEnum=OperatorEnum.Equal
                                },
                                new WhereHelper(){
                                     FiledName=nameof(RB_Goods_Order_Extend.UserId),
                                      FiledValue=qitem.UserId,
                                       OperatorEnum=OperatorEnum.Equal
                                },
                                new WhereHelper(){
                                     FiledName=nameof(RB_Goods_Order_Extend.TenantId),
                                      FiledValue=item.TenantId,
                                       OperatorEnum=OperatorEnum.Equal
                                },
                                new WhereHelper(){
                                     FiledName=nameof(RB_Goods_Order_Extend.MallBaseId),
                                      FiledValue=item.MallBaseId,
                                       OperatorEnum=OperatorEnum.Equal
                                }
                            };
                                    bool flag = goods_OrderRepository.Update(keyValues, wheres);
                                    if (flag)
                                    {
                                        //回滚商品库存
                                        if (true)
                                        {
                                            int tenantId = item.TenantId;
                                            int mallBaseId = item.MallBaseId;
                                            int TotalIntegralNumber = 0;
                                            var detailList = goodsOrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { OrderId = qitem.OrderId, TenantId = tenantId, MallBaseId = mallBaseId });
                                            if (detailList.Any())
                                            {
                                                string goodsIds = string.Join(",", detailList.Select(x => x.GoodsId ?? 0).Distinct());
                                                var goodsList = goodsRepository.GetSingleList(new RB_Goods_Extend() { GoodsIds = goodsIds, TenantId = tenantId, MallBaseId = mallBaseId }, true);
                                                var speciPList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsIds = goodsIds, TenantId = tenantId, MallBaseId = mallBaseId });

                                                foreach (var ditem in detailList)
                                                {
                                                    var gmodel = goodsList.Where(x => x.Id == ditem.GoodsId).FirstOrDefault();
                                                    if (gmodel == null)
                                                    {
                                                        continue;
                                                    }
                                                    if (string.IsNullOrEmpty(ditem.SpecificationSort) || ditem.OrderType == OrderTypeEnum.SDGoods)
                                                    {
                                                        if (gmodel.IsCustomSpecification == 1)
                                                        {
                                                            continue;
                                                        }
                                                    }
                                                    else
                                                    {
                                                        if (gmodel.IsCustomSpecification != 1)
                                                        {
                                                            continue;
                                                        }
                                                        var speciPModel = speciPList.Where(x => x.GoodsId == ditem.GoodsId && x.SpecificationSort == ditem.SpecificationSort).FirstOrDefault();
                                                        if (speciPModel == null)
                                                        {
                                                            continue;
                                                        }
                                                        //更新商品规格表库存 + 商品表总库存
                                                        Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                                    { nameof(RB_Goods_SpecificationPrice_Extend.InventoryNum), (speciPModel.InventoryNum??0)+(ditem.Number??0)}
                                                };
                                                        List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                                    new WhereHelper(){
                                                            FiledName=nameof(RB_Goods_SpecificationPrice_Extend.Id),
                                                            FiledValue=speciPModel.Id,
                                                            OperatorEnum=OperatorEnum.Equal
                                                    }
                                                };
                                                        goods_SpecificationPriceRepository.Update(keyValues2, wheres2);
                                                    }

                                                    if (ditem.OrderType == OrderTypeEnum.SDGoods)
                                                    {
                                                        //更新商品可预定日期
                                                        var tdlist = goods_TargetDateRepository.GetList(new RB_Goods_TargetDate_Extend() { GoodsId = ditem.GoodsId ?? 0, StartTime = ditem.TripSTime.Value.ToString("yyyy-MM-dd"), EndTime = ditem.TripETime.Value.ToString("yyyy-MM-dd") });
                                                        if (ditem.CarType == GuideCarGoodsTypeEnum.Line && ditem.IsSpell == 1)
                                                        {
                                                            //只调整第一天的   其他天 直接表示已预订了
                                                            var fristModel = tdlist.Where(x => x.Date == Convert.ToDateTime(ditem.TripSTime.Value.ToString("yyyy-MM-dd"))).FirstOrDefault();
                                                            //第一条更新数量  如果OK咯  更新已预定
                                                            if (fristModel != null)
                                                            {
                                                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>
                                                                {
                                                                    { nameof(RB_Goods_TargetDate.IsReserve), 1 },
                                                                    { nameof(RB_Goods_TargetDate.ReserveNum), (fristModel.ReserveNum) - (ditem.Number ?? 0) }
                                                                };

                                                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                                                    new WhereHelper(){
                                                                            FiledName=nameof(RB_Goods_TargetDate.Id),
                                                                            FiledValue=fristModel.Id,
                                                                            OperatorEnum=OperatorEnum.Equal
                                                                    }
                                                                };
                                                                goods_TargetDateRepository.Update(keyValues1, wheres1);
                                                                if ((fristModel.ReserveNum) - (ditem.Number ?? 0) <= 0)
                                                                {
                                                                    //其他的直接改未预定
                                                                    foreach (var q1item in tdlist.Where(x => x.Date != Convert.ToDateTime(ditem.TripSTime.Value.ToString("yyyy-MM-dd")) && x.IsReserve == 2))
                                                                    {
                                                                        Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                                                            { nameof(RB_Goods_TargetDate.IsReserve),1},
                                                                            { nameof(RB_Goods_TargetDate.ReserveNum),0},
                                                                        };
                                                                        List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                                                            new WhereHelper(){
                                                                                    FiledName=nameof(RB_Goods_TargetDate.Id),
                                                                                    FiledValue=q1item.Id,
                                                                                    OperatorEnum=OperatorEnum.Equal
                                                                            }
                                                                        };
                                                                        goods_TargetDateRepository.Update(keyValues2, wheres2);
                                                                    }
                                                                }
                                                            }
                                                        }
                                                        else
                                                        {
                                                            //直接回滚所有的日期 为可预定
                                                            foreach (var q1item in tdlist)
                                                            {
                                                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                                                    { nameof(RB_Goods_TargetDate.IsReserve),1},
                                                                    { nameof(RB_Goods_TargetDate.ReserveNum),0},
                                                                };
                                                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                                                    new WhereHelper(){
                                                                         FiledName=nameof(RB_Goods_TargetDate.Id),
                                                                          FiledValue=q1item.Id,
                                                                           OperatorEnum=OperatorEnum.Equal
                                                                    }
                                                                };
                                                                goods_TargetDateRepository.Update(keyValues1, wheres1);
                                                            }
                                                        }
                                                    }
                                                    else
                                                    {
                                                        if (qitem.OrderClassify != 2)
                                                        {
                                                            //更新商品表库存
                                                            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                                                { nameof(RB_Goods_Extend.InventoryNum), (gmodel.InventoryNum??0)+(ditem.Number??0)}
                                                            };
                                                            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                                                new WhereHelper(){
                                                                        FiledName=nameof(RB_Goods_Extend.Id),
                                                                        FiledValue=gmodel.Id,
                                                                        OperatorEnum=OperatorEnum.Equal
                                                                }
                                                            };
                                                            goodsRepository.Update(keyValues1, wheres1);
                                                        }
                                                    }
                                                    if (qitem.DepositId > 0)
                                                    {
                                                        Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                                            { nameof(RB_Goods_OrderDetail_Extend.DepositRefundMoney),ditem.DepositMoney + ditem.DepositFreightMoney}
                                                        };
                                                        List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                                            new WhereHelper(){
                                                                 FiledName=nameof(RB_Goods_OrderDetail_Extend.Id),
                                                                  FiledValue=ditem.Id,
                                                                   OperatorEnum=OperatorEnum.Equal
                                                            }
                                                        };
                                                        goods_OrderDetailRepository.Update(keyValues1, wheres1);
                                                    }
                                                    goods_LogRepository.Insert(new Mall.Model.Entity.Product.RB_Goods_Log()
                                                    {
                                                        Id = 0,
                                                        Type = 2,
                                                        SourceId = ditem.GoodsId,
                                                        Content = $"取消订单{qitem.OrderId}，还原商品库存:" + ditem.Number,
                                                        CreateDate = DateTime.Now,
                                                        MallBaseId = mallBaseId,
                                                        TenantId = tenantId
                                                    });

                                                    if (ditem.IntegralNumber > 0)
                                                    {
                                                        TotalIntegralNumber += (ditem.IntegralNumber ?? 0);
                                                    }
                                                    if (ditem.ClassId > 0)
                                                    {
                                                        classIdList.Add(ditem.ClassId);
                                                    }
                                                }
                                            }
                                            var umodel = member_UserRepository.GetEntity(qitem.UserId);
                                            //积分抵扣回滚
                                            if (TotalIntegralNumber > 0)
                                            {
                                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                            { nameof(RB_Member_User_Extend.Integral),umodel.Integral + TotalIntegralNumber}
                                        };
                                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                            new WhereHelper(){
                                                 FiledName=nameof(RB_Member_User_Extend.Id),
                                                  FiledValue=umodel.Id,
                                                   OperatorEnum=OperatorEnum.Equal
                                            }
                                        };
                                                bool flag2 = member_UserRepository.Update(keyValues1, wheres1);
                                                if (flag2)
                                                {
                                                    member_IntegralRepository.Insert(new Mall.Model.Entity.User.RB_Member_Integral()
                                                    {
                                                        Id = 0,
                                                        CreateDate = DateTime.Now,
                                                        Description = "订单取消返回积分抵扣，订单号：" + qitem.OrderNo,
                                                        Image = 0,
                                                        Integral = TotalIntegralNumber,
                                                        MallBaseId = item.MallBaseId,
                                                        PlatformType = qitem.OrderSource,
                                                        Remarks = "",
                                                        TenantId = item.TenantId,
                                                        Type = Common.Enum.MarketingCenter.RecordTypeEnum.Income,
                                                        UserId = qitem.UserId,
                                                        OrderId = qitem.OrderId
                                                    });
                                                }
                                            }
                                            //优惠券回滚
                                            if (!string.IsNullOrEmpty(qitem.CouponsIds))
                                            {
                                                var cList = member_CouponRepository.GetList(new RB_Member_DiscountCoupon_Extend() { UseState = 1, Ids = qitem.CouponsIds, UserId = qitem.UserId, TenantId = item.TenantId, MallBaseId = item.MallBaseId });
                                                foreach (var citem in cList)
                                                {
                                                    Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                                { nameof(RB_Member_DiscountCoupon_Extend.UseState),0}
                                            };
                                                    List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                                new WhereHelper(){
                                                     FiledName=nameof(RB_Member_DiscountCoupon_Extend.Id),
                                                      FiledValue=citem.Id,
                                                       OperatorEnum=OperatorEnum.Equal
                                                }
                                            };
                                                    member_CouponRepository.Update(keyValues1, wheres1);
                                                }
                                            }
                                            //储值卡回滚
                                            if (qitem.DepositId > 0)
                                            {
                                                var depositModel = member_DepositBuyRepository.GetEntity(qitem.DepositId);
                                                if (depositModel != null)
                                                {
                                                    Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                                        { nameof(RB_Member_DepositBuy_Extend.SurplusPrice),depositModel.SurplusPrice + qitem.DepositMoney}
                                                    };
                                                    List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                                        new WhereHelper(){
                                                             FiledName=nameof(RB_Member_DepositBuy_Extend.Id),
                                                              FiledValue=depositModel.Id,
                                                               OperatorEnum=OperatorEnum.Equal
                                                        }
                                                    };
                                                    member_DepositBuyRepository.Update(keyValues1, wheres1);
                                                    member_DepositBalanceRepository.Insert(new RB_Member_DepositBalance()
                                                    {
                                                        Id = 0,
                                                        UserId = umodel.Id,
                                                        Balance = depositModel.SurplusPrice,
                                                        CouponIco = depositModel.CouponIco,
                                                        CreateDate = DateTime.Now,
                                                        DepositPrice = depositModel.DepositPrice,
                                                        MallBaseId = umodel.MallBaseId,
                                                        MergeType = 3,
                                                        Name = depositModel.Name,
                                                        NewDepositBuyId = 0,
                                                        OldDepositBuyId = 0,
                                                        Remarks = "订单" + qitem.OrderNo + "取消，退回使用储值卡抵扣" + qitem.DepositMoney + "金额",
                                                        SalePrice = depositModel.SalePrice,
                                                        Status = 0,
                                                        Surplus = depositModel.SurplusPrice + qitem.DepositMoney,
                                                        TenantId = umodel.TenantId,
                                                        Type = Common.Enum.MarketingCenter.RecordTypeEnum.Income
                                                    });
                                                }
                                            }
                                            //余额支付回滚

                                            if (qitem.OrderClassify == 2 && qitem.EducationMoney > 0)
                                            {
                                                var uclist = education_MemberUseCouponRepository.GetList(new Model.Entity.Education.RB_Education_MemberUseCoupon() { OrderId = qitem.OrderId });
                                                var ucModel = uclist.FirstOrDefault();
                                                if (ucModel != null)
                                                {
                                                    Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                                        { nameof(Model.Entity.Education.RB_Education_MemberUseCoupon.Status),1}
                                                    };
                                                    List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                                        new WhereHelper(){
                                                             FiledName=nameof(Model.Entity.Education.RB_Education_MemberUseCoupon.Id),
                                                              FiledValue=ucModel.Id,
                                                               OperatorEnum=OperatorEnum.Equal
                                                        }
                                                    };
                                                    education_MemberUseCouponRepository.Update(keyValues1, wheres1);

                                                    var educationModel = education_MemberCouponRepository.GetEntity(ucModel.MemberCouponId ?? 0);
                                                    if (educationModel != null)
                                                    {
                                                        //更新用户课程卡 已使用数量
                                                        Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                                            { nameof(RB_Education_MemberCoupon_Extend.UseHeXiao),educationModel.UseHeXiao - ucModel.UseHeXiao}
                                                        };
                                                        List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                                            new WhereHelper(){
                                                                 FiledName=nameof(RB_Education_MemberCoupon_Extend.Id),
                                                                  FiledValue=educationModel.Id,
                                                                   OperatorEnum=OperatorEnum.Equal
                                                            }
                                                        };
                                                        education_MemberCouponRepository.Update(keyValues2, wheres2);
                                                    }
                                                }
                                            }

                                        }
                                        goods_LogRepository.Insert(new Mall.Model.Entity.Product.RB_Goods_Log()
                                        {
                                            Id = 0,
                                            Type = 1,
                                            SourceId = qitem.OrderId,
                                            Content = "订单超时，自动取消订单",
                                            CreateDate = DateTime.Now,
                                            MallBaseId = item.MallBaseId,
                                            TenantId = item.TenantId
                                        });
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                Helper.LogHelper.Write("AutoCancelOrder:" + ex.Message);
                                continue;
                            }
                        }

                        if (classIdList != null && classIdList.Any())
                        {
                            var resultInfo = new
                            {
                                Msg = new { Order = classIdList },
                            };
                            string apiResult = Common.Plugin.HttpHelper.HttpPost(Config.ReadConfigKey("EduUpdateGoodsSpecification"), JsonHelper.Serialize(resultInfo), "");
                        }

                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                Helper.LogHelper.Write("AutoCancelOrder:" + ex.Message);
                return false;
            }
        }

        #endregion

        #region 自动收货

        /// <summary>
        /// 自动收货
        /// </summary>
        /// <returns></returns>
        public static bool AutoReceivingOrder()
        {
            try
            {
                var list = mallBaseRepository.GetListRepository(new Mall.Model.Extend.BaseSetUp.RB_MallBase_Extend() { });
                foreach (var item in list)
                {
                    if (item.AutoReceiving > 0)
                    {
                        //查询待发货的所有订单
                        var olist = goods_OrderRepository.GetCanReceivingOrderList(item.AutoReceiving, item.TenantId, item.MallBaseId);
                        foreach (var qitem in olist)
                        {
                            Dictionary<string, object> keyValues = new Dictionary<string, object>() { };
                            keyValues.Add(nameof(RB_Goods_Order_Extend.OrderStatus), OrderStatusEnum.Received);
                            keyValues.Add(nameof(RB_Goods_Order_Extend.ReceivingTime), DateTime.Now);

                            List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_Goods_Order_Extend.OrderId),
                                  FiledValue=qitem.OrderId,
                                   OperatorEnum=OperatorEnum.Equal
                            },
                            new WhereHelper(){
                                 FiledName=nameof(RB_Goods_Order_Extend.UserId),
                                  FiledValue=qitem.UserId,
                                   OperatorEnum=OperatorEnum.Equal
                            },
                            new WhereHelper(){
                                 FiledName=nameof(RB_Goods_Order_Extend.TenantId),
                                  FiledValue=item.TenantId,
                                   OperatorEnum=OperatorEnum.Equal
                            },
                            new WhereHelper(){
                                 FiledName=nameof(RB_Goods_Order_Extend.MallBaseId),
                                  FiledValue=item.MallBaseId,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                            bool flag = goods_OrderRepository.Update(keyValues, wheres);
                            if (flag)
                            {
                                goods_LogRepository.Insert(new Mall.Model.Entity.Product.RB_Goods_Log()
                                {
                                    Id = 0,
                                    Type = 1,
                                    SourceId = qitem.OrderId,
                                    Content = "系统自动确认收货",
                                    CreateDate = DateTime.Now,
                                    MallBaseId = item.MallBaseId,
                                    TenantId = item.TenantId
                                });
                                //自动确认订单
                                SetOrderOperation(qitem, 6, "", 0, "", item.TenantId, item.MallBaseId, item.AfterTime);
                            }
                        }
                    }

                    try
                    {
                        //查询所有司导已逾期未完成订单
                        var olist = goods_OrderRepository.GetSDOrderNotFinishList(item.TenantId, item.MallBaseId);
                        foreach (var qitem in olist)
                        {
                            //自动确认订单
                            SetOrderOperation(qitem, 6, "", 0, "", item.TenantId, item.MallBaseId, 0);
                        }
                    }
                    catch (Exception ex)
                    {
                        Helper.LogHelper.Write("AutoSDOrderFinishOrder:" + ex.Message);
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                Helper.LogHelper.Write("AutoReceivingOrder:" + ex.Message);
                return false;
            }
        }

        public static bool TestOrderPay()
        {
            var omodel = goods_OrderRepository.GetEntity<RB_Goods_Order_Extend>(82013);
            Console.WriteLine("进来了1");
            return SetOrderOperation(omodel, 6, "", 0, "", 1, 1, 0);
        }

        /// <summary>
        /// 设置订单操作
        /// </summary>
        /// <param name="orderModel"></param>
        /// <param name="type">类型  1修改备注  2修改金额  3强制取消  4放入回收站  5确认收货  6确认完成  7回收恢复 8回收删除</param>
        /// <param name="remark"></param>
        /// <param name="income"></param>
        /// <param name="address"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <param name="afterTime">售后时间</param>
        /// <returns></returns>
        public static bool SetOrderOperation(RB_Goods_Order_Extend orderModel, int type, string remark, decimal income, string address, int tenantId, int mallBaseId, int afterTime)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() { };
            switch (type)
            {
                case 1:
                    keyValues.Add(nameof(RB_Goods_Order.Remark), remark); break;
                case 2:
                    keyValues.Add(nameof(RB_Goods_Order.Income), income); break;
                case 3:
                    keyValues.Add(nameof(RB_Goods_Order.OrderStatus), OrderStatusEnum.Cancel); break;
                case 4:
                    keyValues.Add(nameof(RB_Goods_Order.Recycled), 1); break;
                case 5://确认收货
                    keyValues.Add(nameof(RB_Goods_Order.OrderStatus), OrderStatusEnum.Received);
                    keyValues.Add(nameof(RB_Goods_Order.ReceivingTime), DateTime.Now);
                    break;
                case 6://确认完成
                    keyValues.Add(nameof(RB_Goods_Order.OrderStatus), OrderStatusEnum.Completed);
                    keyValues.Add(nameof(RB_Goods_Order.FinishTime), DateTime.Now);
                    break;
                case 7:
                    keyValues.Add(nameof(RB_Goods_Order.Recycled), 2); break;
                case 8:
                    keyValues.Add(nameof(RB_Goods_Order.Status), 1); break;
            }

            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Goods_Order.OrderId),
                      FiledValue=orderModel.OrderId,
                       OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName=nameof(RB_Goods_Order.TenantId),
                      FiledValue=tenantId,
                       OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName=nameof(RB_Goods_Order.MallBaseId),
                      FiledValue=mallBaseId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = goods_OrderRepository.Update(keyValues, wheres);
            if (flag)
            {
                //记录日志
                string Content = "";
                switch (type)
                {
                    case 1:
                        Content = "修改备注信息"; break;
                    case 2:
                        Content = "修改付款金额"; break;
                    case 3:
                        Content = "强制取消订单"; break;
                    case 4:
                        Content = "放入回收站"; break;
                    case 5:
                        Content = "确认收货"; break;
                    case 6:
                        Content = "确认完成"; break;
                    case 7:
                        Content = "回收站恢复订单"; break;
                    case 8:
                        Content = "确认删除订单"; break;
                }
                goods_LogRepository.Insert(new RB_Goods_Log()
                {
                    Content = Content,
                    CreateDate = DateTime.Now,
                    Id = 0,
                    MallBaseId = mallBaseId,
                    SourceId = orderModel.OrderId,
                    TenantId = tenantId,
                    Type = 1
                });
                if (type == 6)
                {
                    bool IsUpdateCommission = true;
                    if (afterTime > 0)
                    {
                        var omodel = goods_OrderRepository.GetEntity(orderModel.OrderId);
                        if (omodel != null && omodel.ReceivingTime.HasValue && omodel.ReceivingTime.Value.AddDays(afterTime) > DateTime.Now)
                        {
                            IsUpdateCommission = false;
                        }
                    }
                    if (IsUpdateCommission)
                    {
                        //更新返佣为已返佣
                        var ocList = goods_OrderCommissionRepository.GetList(new RB_Goods_OrderCommission_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderModel.OrderId });
                        if (ocList.Where(x => x.CommissionState == 1).Any())
                        {
                            foreach (var item in ocList.Where(x => x.CommissionState == 1))
                            {
                                //查询是否有申请退款
                                var afterSaleList = goods_OrderAfterSaleRepository.GetList(new RB_Goods_OrderAfterSale_Extend() { OrderDetialId = item.OrderDetailId, Type = 1, MallBaseId = mallBaseId, TenantId = tenantId });
                                if (!afterSaleList.Any())
                                {
                                    //获取分销商信息
                                    var disInfo = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserId = item.UserId, TenantId = tenantId, MallBaseId = mallBaseId }).FirstOrDefault();
                                    if (disInfo != null && disInfo.AuditStatus == DistributorAuditStatusEnum.Audited)
                                    {
                                        //更新分销商佣金
                                        Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                        { nameof(RB_Distributor_Info_Extend.TotalCommission),(disInfo.TotalCommission??0)+(item.Commission??0)},
                                        { nameof(RB_Distributor_Info_Extend.CommissionWithdrawal),(disInfo.CommissionWithdrawal??0)+(item.Commission??0)},
                                    };
                                        List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                        new WhereHelper(){
                                             FiledName=nameof(RB_Distributor_Info_Extend.Id),
                                              FiledValue=disInfo.Id,
                                               OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                                        bool flag1 = distributor_InfoRepository.Update(keyValues2, wheres2);
                                        if (flag1)
                                        {
                                            //更新返佣状态
                                            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                            { nameof(RB_Goods_OrderCommission_Extend.CommissionState),2},
                                            { nameof(RB_Goods_OrderCommission_Extend.UpdateDate),DateTime.Now},
                                        };
                                            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                            new WhereHelper(){
                                                 FiledName=nameof(RB_Goods_OrderCommission_Extend.Id),
                                                  FiledValue=item.Id,
                                                   OperatorEnum=OperatorEnum.Equal
                                            }
                                        };
                                            goods_OrderCommissionRepository.Update(keyValues1, wheres1);
                                        }
                                    }
                                }
                            }
                        }

                        //更新推荐供应商返佣
                        var oiList = goods_OrderIntroductionRepository.GetList(new RB_Goods_OrderIntroduction_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderModel.OrderId });
                        if (oiList.Any())
                        {
                            foreach (var item in oiList)
                            {
                                //查询是否有申请退款
                                var afterSaleList = goods_OrderAfterSaleRepository.GetList(new RB_Goods_OrderAfterSale_Extend() { OrderDetialId = item.OrderDetailId, Type = 1, MallBaseId = mallBaseId, TenantId = tenantId });
                                if (!afterSaleList.Any())
                                {
                                    //更新返佣状态
                                    Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                        { nameof(RB_Goods_OrderIntroduction_Extend.CommissionState),2},
                                        { nameof(RB_Goods_OrderIntroduction_Extend.UpdateDate),DateTime.Now},
                                    };
                                    List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                        new WhereHelper(){
                                                FiledName=nameof(RB_Goods_OrderIntroduction_Extend.Id),
                                                FiledValue=item.Id,
                                                OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                                    goods_OrderIntroductionRepository.Update(keyValues1, wheres1);
                                }
                            }
                        }
                        //更新微店返佣
                        var ssList = smallShops_CommissionRepository.GetList(new RB_SmallShops_Commission_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, OrderId = orderModel.OrderId });
                        if (ssList.Where(x => x.CommissionState == 1).Any())
                        {
                            //验证是否是自动结算
                            var ssbaseModel = microShop_BasicsRepository.GetMicroShopBasicsList(new RB_MicroShop_Basics() { TenantId = tenantId, MallBaseId = mallBaseId }).FirstOrDefault();
                            if (("," + (ssbaseModel?.SettlementType ?? "") + ",").Contains("," + ((int)DistrbutorWithdrawWayEnum.ZDXJ).ToString() + ","))
                            {
                                var ssmodel = ssList.FirstOrDefault();
                                //获取微店信息
                                var smallModel = smallShops_InfoRepository.GetList(new RB_SmallShops_Info_Extend() { UserId = ssmodel.UserId, TenantId = tenantId, MallBaseId = mallBaseId }).FirstOrDefault();
                                if (smallModel != null && smallModel.AuditStatus == DistributorAuditStatusEnum.Audited)
                                {
                                    //总佣金
                                    decimal TotalCommission = 0, OldCommission = 0;
                                    foreach (var item in ssList.Where(x => x.CommissionState == 1))
                                    {
                                        //查询是否有申请退款
                                        var afterSaleList = goods_OrderAfterSaleRepository.GetList(new RB_Goods_OrderAfterSale_Extend() { OrderDetialId = item.OrderDetailId, Type = 1, MallBaseId = mallBaseId, TenantId = tenantId });
                                        if (!afterSaleList.Any())
                                        {
                                            TotalCommission += (item.Commission ?? 0);
                                        }
                                    }
                                    #region 看微店佣金是否是负数  是的话  需要走总佣金里减去
                                    OldCommission = TotalCommission;
                                    if ((smallModel.Commission ?? 0) < 0)
                                    {
                                        TotalCommission += (smallModel?.Commission ?? 0);
                                    }
                                    #endregion
                                    if (TotalCommission > 0)
                                    {
                                        decimal RemitMoney = TotalCommission, fee = 0;
                                        var feeValue = ssbaseModel?.WithdrawalFree ?? 0;
                                        if (feeValue > 0)
                                        {
                                            fee = Math.Round(TotalCommission * (feeValue) / 100, 2, MidpointRounding.AwayFromZero);
                                            RemitMoney = TotalCommission - fee;
                                        }
                                        var minModel = miniProgramRepository.GetEntity<RB_MiniProgram_Extend>(mallBaseId);
                                        var umodel = member_UserRepository.GetEntity(ssmodel.UserId);
                                        //打款
                                        Random R = new Random();
                                        int Rstr = R.Next(111, 999);
                                        string OrderNum = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr;
                                        int IsNormalServer = Convert.ToInt32(Config.IsNormalServer);
                                        var flagpay = false;
                                        if (IsNormalServer == 1)
                                        {
                                            flagpay = PayUtil.GetTransfersOrder(OrderNum, RemitMoney, (ssmodel.UserId ?? 0).ToString(), umodel.OpenId, minModel, "赞羊微店佣金打款");
                                        }
                                        if (flagpay)
                                        {
                                            //更新状态
                                            foreach (var item in ssList.Where(x => x.CommissionState == 1))
                                            {
                                                if (smallModel != null && smallModel.AuditStatus == DistributorAuditStatusEnum.Audited)
                                                {
                                                    //更新返佣状态
                                                    Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                                        { nameof(RB_SmallShops_Commission_Extend.CommissionState),2},
                                                        { nameof(RB_SmallShops_Commission_Extend.IsRemit),1},
                                                        { nameof(RB_SmallShops_Commission_Extend.UpdateDate),DateTime.Now},
                                                    };
                                                    List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                                        new WhereHelper(){
                                                                FiledName=nameof(RB_SmallShops_Commission_Extend.Id),
                                                                FiledValue=item.Id,
                                                                OperatorEnum=OperatorEnum.Equal
                                                        }
                                                    };
                                                    smallShops_CommissionRepository.Update(keyValues1, wheres1);
                                                }
                                            }
                                            //写入已提现数据
                                            smallShops_RemitRepository.Insert(new RB_SmallShops_Remit()
                                            {
                                                Id = 0,
                                                AccountName = "",
                                                AccountNumber = "",
                                                AppliedMoney = TotalCommission,
                                                AuditDate = DateTime.Now,
                                                AuditRemark = "",
                                                AuditStatus = DistributorRemitAuditStatusEnum.HaveMoney,
                                                BankName = "",
                                                CreateDate = DateTime.Now,
                                                Fee = fee,
                                                FinanceId = 0,
                                                MallBaseId = mallBaseId,
                                                OrderNum = OrderNum,
                                                RejectDate = null,
                                                RejectRemark = "",
                                                RemitDate = DateTime.Now,
                                                RemitMoney = RemitMoney,
                                                RemitRemark = "自动结算打款",
                                                ReOrderIds = "[" + (orderModel.OrderId).ToString() + "]",
                                                ReOrderNos = "\"" + orderModel.OrderNo + "\"：" + RemitMoney + "元",
                                                TenantId = tenantId,
                                                UserId = ssmodel.UserId,
                                                WithdrawalWay = DistrbutorWithdrawWayEnum.ZDXJ
                                            });
                                        }
                                        else
                                        {
                                            //更新状态
                                            foreach (var item in ssList.Where(x => x.CommissionState == 1))
                                            {
                                                if (smallModel != null && smallModel.AuditStatus == DistributorAuditStatusEnum.Audited)
                                                {
                                                    //更新返佣状态
                                                    Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                                    { nameof(RB_SmallShops_Commission_Extend.CommissionState),2},
                                                    { nameof(RB_SmallShops_Commission_Extend.IsRemit),1},
                                                    { nameof(RB_SmallShops_Commission_Extend.UpdateDate),DateTime.Now},
                                                };
                                                    List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                                    new WhereHelper(){
                                                            FiledName=nameof(RB_SmallShops_Commission_Extend.Id),
                                                            FiledValue=item.Id,
                                                            OperatorEnum=OperatorEnum.Equal
                                                    }
                                                };
                                                    smallShops_CommissionRepository.Update(keyValues1, wheres1);
                                                }
                                            }
                                            //写入已提现数据
                                            smallShops_RemitRepository.Insert(new RB_SmallShops_Remit()
                                            {
                                                Id = 0,
                                                AccountName = "",
                                                AccountNumber = "",
                                                AppliedMoney = TotalCommission,
                                                AuditDate = DateTime.Now,
                                                AuditRemark = "自动现结失败，变更为手动打款",
                                                AuditStatus = DistributorRemitAuditStatusEnum.ToPlayWith,
                                                BankName = "",
                                                CreateDate = DateTime.Now,
                                                Fee = fee,
                                                FinanceId = 0,
                                                MallBaseId = mallBaseId,
                                                OrderNum = OrderNum,
                                                RejectDate = null,
                                                RejectRemark = "",
                                                RemitDate = DateTime.Now,
                                                RemitMoney = RemitMoney,
                                                RemitRemark = "",
                                                ReOrderIds = "[" + (orderModel.OrderId).ToString() + "]",
                                                ReOrderNos = "\"" + orderModel.OrderNo + "\"：" + RemitMoney + "元",
                                                TenantId = tenantId,
                                                UserId = ssmodel.UserId,
                                                WithdrawalWay = DistrbutorWithdrawWayEnum.ZDDK
                                            });
                                        }
                                        //更新微店佣金等于0                                            
                                        Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                            { nameof(RB_SmallShops_Info_Extend.TotalCommission),(smallModel.TotalCommission??0) + OldCommission},
                                            { nameof(RB_SmallShops_Info_Extend.Commission), TotalCommission}
                                        };
                                        List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                            new WhereHelper(){
                                                    FiledName=nameof(RB_SmallShops_Info_Extend.Id),
                                                    FiledValue=smallModel.Id,
                                                    OperatorEnum=OperatorEnum.Equal
                                            }
                                        };
                                        bool flag1 = smallShops_InfoRepository.Update(keyValues2, wheres2);
                                    }
                                    else if (TotalCommission < 0)
                                    {
                                        //存在微店佣金里  继续负数累加                                      
                                        Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                            { nameof(RB_SmallShops_Info_Extend.TotalCommission),(smallModel.TotalCommission??0) + OldCommission},
                                            { nameof(RB_SmallShops_Info_Extend.Commission),TotalCommission},
                                        };
                                        List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                            new WhereHelper(){
                                                    FiledName=nameof(RB_SmallShops_Info_Extend.Id),
                                                    FiledValue=smallModel.Id,
                                                    OperatorEnum=OperatorEnum.Equal
                                            }
                                        };
                                        bool flag1 = smallShops_InfoRepository.Update(keyValues2, wheres2);
                                    }
                                }
                            }
                            else
                            {
                                var ssmodel = ssList.FirstOrDefault();
                                //获取微店信息
                                var smallModel = smallShops_InfoRepository.GetList(new RB_SmallShops_Info_Extend() { UserId = ssmodel.UserId, TenantId = tenantId, MallBaseId = mallBaseId }).FirstOrDefault();
                                foreach (var item in ssList.Where(x => x.CommissionState == 1))
                                {
                                    //查询是否有申请退款
                                    var afterSaleList = goods_OrderAfterSaleRepository.GetList(new RB_Goods_OrderAfterSale_Extend() { OrderDetialId = item.OrderDetailId, Type = 1, MallBaseId = mallBaseId, TenantId = tenantId });
                                    if (!afterSaleList.Any())
                                    {
                                        if (smallModel != null && smallModel.AuditStatus == DistributorAuditStatusEnum.Audited)
                                        {
                                            //更新分销商佣金
                                            Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                        { nameof(RB_SmallShops_Info_Extend.TotalCommission),(smallModel.TotalCommission??0)+(item.Commission??0)},
                                        { nameof(RB_SmallShops_Info_Extend.Commission),(smallModel.Commission??0)+(item.Commission??0)},
                                    };
                                            List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                        new WhereHelper(){
                                                FiledName=nameof(RB_SmallShops_Info_Extend.Id),
                                                FiledValue=smallModel.Id,
                                                OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                                            bool flag1 = smallShops_InfoRepository.Update(keyValues2, wheres2);
                                            if (flag1)
                                            {
                                                //更新返佣状态
                                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                            { nameof(RB_SmallShops_Commission_Extend.CommissionState),2},
                                            { nameof(RB_SmallShops_Commission_Extend.UpdateDate),DateTime.Now},
                                        };
                                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                            new WhereHelper(){
                                                    FiledName=nameof(RB_SmallShops_Commission_Extend.Id),
                                                    FiledValue=item.Id,
                                                    OperatorEnum=OperatorEnum.Equal
                                            }
                                        };
                                                smallShops_CommissionRepository.Update(keyValues1, wheres1);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    //积分赠送
                    var dlist = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { OrderId = orderModel.OrderId, TenantId = tenantId, MallBaseId = mallBaseId });
                    if (dlist.Any())
                    {
                        int IntegralGoodsPresent = 0;
                        foreach (var item in dlist)
                        {
                            if (item.IntegralGoodsPresent > 0)
                            {
                                IntegralGoodsPresent += (item.IntegralGoodsPresent ?? 0);
                            }
                        }
                        if (IntegralGoodsPresent > 0)
                        {
                            //保存积分赠送
                            var umodel = member_UserRepository.GetEntity(orderModel.UserId);
                            //用户订单数增加
                            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                { nameof(RB_Member_User_Extend.Integral), (umodel.Integral ?? 0)+IntegralGoodsPresent }
                            };
                            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);
                            member_IntegralRepository.Insert(new Mall.Model.Entity.User.RB_Member_Integral()
                            {
                                Id = 0,
                                CreateDate = DateTime.Now,
                                Description = "订单购买赠送积分，订单号：" + orderModel.OrderNo,
                                Image = 0,
                                Integral = IntegralGoodsPresent,
                                MallBaseId = orderModel.MallBaseId,
                                PlatformType = orderModel.OrderSource,
                                Remarks = "",
                                TenantId = orderModel.TenantId,
                                Type = Common.Enum.MarketingCenter.RecordTypeEnum.Income,
                                UserId = orderModel.UserId,
                                OrderId = orderModel.OrderId
                            });
                        }
                    }

                    #region 粉象等级赠送  2020-07-21
                    if (dlist.Where(x => x.PresentFXGrade > 0).Any())
                    {
                        var demodel = new RB_Goods_Order_Extend
                        {
                            TenantId = tenantId,
                            MallBaseId = mallBaseId,
                            DetailList = dlist,
                            OrderNo = orderModel.OrderNo
                        };
                        //InsertPresentFXGrade(demodel, orderModel.UserId ?? 0, orderModel.OrderId);  2020-08-03 ld 赠送设置为 订单付款后了
                    }
                    #endregion
                }
                else if (type == 3)
                {
                    //强制取消 (作废  使用新方法)

                }
            }
            return flag;
        }

        /// <summary>
        /// 赠送粉象等级
        /// </summary>
        /// <param name="demodel"></param>
        /// <param name="umodel"></param>
        /// <param name="OrderId"></param>
        private static void InsertPresentFXGrade(RB_Goods_Order_Extend demodel, int UserId, int OrderId)
        {
            var basicModel = distributor_BasicsRepository.GetList(new RB_Distributor_Basics_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
            if ((basicModel?.IsEnableFXGrade ?? 2) == 1)
            {
                var disModel = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserId = UserId, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
                if (disModel == null)
                {
                    Helper.LogHelper.Write("该用户分销商等级不存在，UserId:" + UserId);
                }
                if (demodel.DetailList.Where(x => x.PresentFXGrade > 0).Any() && disModel != null)
                {
                    var FXList = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                    var VIPModel = FXList.Where(x => x.IsGuest == 3).FirstOrDefault();
                    List<int> GradeList = new List<int>();//等级列表
                    int VIPMonths = 0;//vip赠送月份
                    foreach (var item in demodel.DetailList)
                    {
                        if (item.PresentFXGrade > 0)
                        {
                            //查询是否有申请退款
                            var afterSaleList = goods_OrderAfterSaleRepository.GetList(new RB_Goods_OrderAfterSale_Extend() { OrderDetialId = item.Id, Type = 1, MallBaseId = demodel.MallBaseId, TenantId = demodel.TenantId });
                            if (!afterSaleList.Any())
                            {
                                //有赠送粉象等级
                                GradeList.Add(item.PresentFXGrade ?? 0);
                                if (item.PresentFXGrade == (VIPModel?.Id ?? 0))
                                {
                                    VIPMonths += (item.PresentFXMonth ?? 0) * (item.Number ?? 0);
                                }
                            }
                        }
                    }
                    if (GradeList.Any())
                    {
                        //判断等级 取最高级别
                        int MaxGradeId = 0;
                        int MaxGrade = 0;
                        if (GradeList.Distinct().Count() > 1)
                        {
                            //说明有两种级别  取最高的
                            foreach (var item in GradeList.Distinct())
                            {
                                var fxmodel = FXList.Where(x => x.Id == item).FirstOrDefault();
                                MaxGrade = (fxmodel.Grade ?? 0) > MaxGrade ? (fxmodel.Grade ?? 0) : MaxGrade;
                            }
                            MaxGradeId = FXList.Where(x => x.Grade == MaxGrade).FirstOrDefault()?.Id ?? 0;
                        }
                        else
                        {
                            MaxGradeId = GradeList.FirstOrDefault();
                            var fxmodel = FXList.Where(x => x.Id == MaxGradeId).FirstOrDefault();
                            MaxGrade = (fxmodel.Grade ?? 0) > MaxGrade ? (fxmodel.Grade ?? 0) : MaxGrade;
                        }
                        var oldGrade = FXList.Where(x => x.Id == disModel.FXGradeId).FirstOrDefault()?.Grade ?? 0;

                        try
                        {
                            bool UpdateGrade = false;
                            if (MaxGradeId > 0 && MaxGrade >= oldGrade && MaxGradeId == (VIPModel?.Id ?? 0))
                            {
                                UpdateGrade = true;
                                string MaxGradeName = FXList.Where(x => x.Id == MaxGradeId).FirstOrDefault()?.GradeName ?? "";
                                //vip 
                                var VipExpiryDate = DateTime.Now.AddMonths(VIPMonths);
                                if (VIPMonths >= 1)
                                {
                                    VipExpiryDate = Convert.ToDateTime(VipExpiryDate.AddDays(-1).ToString("yyyy-MM-dd 23:59:59"));
                                }
                                if (MaxGrade == oldGrade && disModel.VipExpiryDate.HasValue)
                                {
                                    if (disModel.VipExpiryDate > DateTime.Now)
                                    {
                                        VipExpiryDate = disModel.VipExpiryDate.Value.AddMonths(VIPMonths);
                                    }
                                }
                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>
                                    {
                                        { nameof(RB_Distributor_Info_Extend.FXGradeId), MaxGradeId },
                                        { nameof(RB_Distributor_Info_Extend.VipExpiryDate), VipExpiryDate }
                                    };
                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                        new WhereHelper(){
                                             FiledName=nameof(RB_Distributor_Info_Extend.Id),
                                              FiledValue=disModel.Id,
                                               OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                                bool gflag = distributor_InfoRepository.Update(keyValues1, wheres1);
                                if (gflag)
                                {
                                    //新增vip赠送记录表
                                    Random R1 = new Random();
                                    int Rstr1 = R1.Next(111, 999);
                                    string OrderNo1 = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr1;
                                    vip_BuyRepository.Insert(new Mall.Model.Entity.User.RB_Vip_Buy()
                                    {
                                        CreateDate = DateTime.Now,
                                        ExpiryDate = VipExpiryDate,
                                        GradeId = MaxGradeId,
                                        GradeName = MaxGradeName,
                                        Id = 0,
                                        MallBaseId = demodel.MallBaseId,
                                        MerchantsNo = "",
                                        Money = 0,
                                        OrderNo = OrderNo1,
                                        PayState = 1,
                                        PayTime = null,
                                        PayWay = 1,
                                        Remark = "下单赠送，订单号：" + demodel.OrderNo + "(" + OrderId + ")",
                                        Status = 0,
                                        TenantId = demodel.TenantId,
                                        UserId = UserId
                                    });
                                }
                            }
                            else if (MaxGradeId > 0 && MaxGrade > oldGrade)
                            {
                                UpdateGrade = true;
                                string MaxGradeName = FXList.Where(x => x.Id == MaxGradeId).FirstOrDefault()?.GradeName ?? "";
                                //比vip高级
                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>
                                    {
                                        { nameof(RB_Distributor_Info_Extend.FXGradeId), MaxGradeId }
                                    };
                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                        new WhereHelper(){
                                             FiledName=nameof(RB_Distributor_Info_Extend.Id),
                                              FiledValue=disModel.Id,
                                               OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                                bool gflag = distributor_InfoRepository.Update(keyValues1, wheres1);
                                if (gflag)
                                {
                                    //新增vip赠送记录表
                                    Random R1 = new Random();
                                    int Rstr1 = R1.Next(111, 999);
                                    string OrderNo1 = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr1;
                                    vip_BuyRepository.Insert(new Mall.Model.Entity.User.RB_Vip_Buy()
                                    {
                                        CreateDate = DateTime.Now,
                                        ExpiryDate = null,
                                        GradeId = MaxGradeId,
                                        GradeName = MaxGradeName,
                                        Id = 0,
                                        MallBaseId = demodel.MallBaseId,
                                        MerchantsNo = "",
                                        Money = 0,
                                        OrderNo = OrderNo1,
                                        PayState = 1,
                                        PayTime = null,
                                        PayWay = 1,
                                        Remark = "下单赠送，订单号：" + demodel.OrderNo + "(" + OrderId + ")",
                                        Status = 0,
                                        TenantId = demodel.TenantId,
                                        UserId = UserId
                                    });
                                }
                            }
                            if (UpdateGrade)
                            {
                                new UserCommonModule().FXAutoUpgradeUserDistributorGrade(UserId, demodel.TenantId, demodel.MallBaseId);
                            }
                        }
                        catch (Exception ex)
                        {
                            Helper.LogHelper.Write("InsertPresentFXGrade赠送粉象分销等级失败，OrderId：" + OrderId + "     Msg:" + ex.Message);
                        }
                    }
                }
            }
        }

        #endregion

        #region 售后时间到了发放佣金

        /// <summary>
        /// 售后时间到了发放佣金
        /// </summary>
        /// <returns></returns>
        public static bool AutoAfterSaleOrderSendCommission()
        {
            try
            {
                var list = mallBaseRepository.GetListRepository(new Mall.Model.Extend.BaseSetUp.RB_MallBase_Extend() { });
                foreach (var item in list)
                {
                    //查询该商户下 所有已完成  未发放佣金的单子
                    var OrderList = goods_OrderCommissionRepository.GetAllOrderCompletedNoCommissionForOrder(item.TenantId, item.MallBaseId);
                    var CommList = goods_OrderCommissionRepository.GetAllOrderCompletedNoCommissionList(item.TenantId, item.MallBaseId);
                    foreach (var Order in OrderList)
                    {
                        var omodel = goods_OrderRepository.GetEntity(Order.OrderId);
                        if (omodel.ReceivingTime.HasValue)
                        {
                            if (item.AfterTime > 0)
                            {
                                //判断是否到了时间
                                if (omodel.ReceivingTime.Value.AddDays(item.AfterTime) < DateTime.Now)
                                {
                                    //结算佣金
                                    //更新返佣为已返佣
                                    var ocList = CommList.Where(x => x.OrderId == Order.OrderId).ToList();
                                    if (ocList.Any())
                                    {
                                        foreach (var qitem in ocList)
                                        {
                                            try
                                            {
                                                //查询是否有申请退款
                                                var afterSaleList = goods_OrderAfterSaleRepository.GetList(new RB_Goods_OrderAfterSale_Extend() { OrderDetialId = qitem.OrderDetailId, Type = 1, MallBaseId = item.MallBaseId, TenantId = item.TenantId });
                                                if (!afterSaleList.Any())
                                                {
                                                    //获取分销商信息
                                                    var disInfo = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserId = qitem.UserId, TenantId = item.TenantId, MallBaseId = item.MallBaseId }).FirstOrDefault();
                                                    if (disInfo != null && disInfo.AuditStatus == DistributorAuditStatusEnum.Audited)
                                                    {
                                                        //更新分销商佣金
                                                        Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                                            { nameof(RB_Distributor_Info_Extend.TotalCommission),(disInfo.TotalCommission ?? 0) + (qitem.Commission ?? 0)},
                                                            { nameof(RB_Distributor_Info_Extend.CommissionWithdrawal),(disInfo.CommissionWithdrawal ?? 0) + (qitem.Commission ?? 0)},
                                                        };
                                                        List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                                            new WhereHelper(){
                                                                 FiledName=nameof(RB_Distributor_Info_Extend.Id),
                                                                  FiledValue=disInfo.Id,
                                                                   OperatorEnum=OperatorEnum.Equal
                                                            }
                                                        };
                                                        bool flag1 = distributor_InfoRepository.Update(keyValues2, wheres2);
                                                        if (flag1)
                                                        {
                                                            //更新返佣状态
                                                            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                                                { nameof(RB_Goods_OrderCommission_Extend.CommissionState),2},
                                                                { nameof(RB_Goods_OrderCommission_Extend.UpdateDate),DateTime.Now},
                                                            };
                                                            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                                                new WhereHelper(){
                                                                     FiledName=nameof(RB_Goods_OrderCommission_Extend.Id),
                                                                      FiledValue=qitem.Id,
                                                                       OperatorEnum=OperatorEnum.Equal
                                                                }
                                                            };
                                                            goods_OrderCommissionRepository.Update(keyValues1, wheres1);
                                                        }
                                                    }
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                Helper.LogHelper.Write("AutoAfterSaleOrderSendCommission: OrderId=" + Order.OrderId + "  错误：" + ex.Message);
                                            }
                                        }
                                    }

                                    //更新推荐供应商返佣
                                    try
                                    {
                                        var oiList = goods_OrderIntroductionRepository.GetList(new RB_Goods_OrderIntroduction_Extend() { TenantId = item.TenantId, MallBaseId = item.MallBaseId, OrderId = Order.OrderId });
                                        if (oiList.Any())
                                        {
                                            foreach (var qitem in oiList)
                                            {
                                                //查询是否有申请退款
                                                var afterSaleList = goods_OrderAfterSaleRepository.GetList(new RB_Goods_OrderAfterSale_Extend() { OrderDetialId = qitem.OrderDetailId, Type = 1, MallBaseId = item.MallBaseId, TenantId = item.TenantId });
                                                if (!afterSaleList.Any())
                                                {
                                                    //更新返佣状态
                                                    Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                                        { nameof(RB_Goods_OrderIntroduction_Extend.CommissionState),2},
                                                        { nameof(RB_Goods_OrderIntroduction_Extend.UpdateDate),DateTime.Now},
                                                    };
                                                    List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                                        new WhereHelper(){
                                                                FiledName=nameof(RB_Goods_OrderIntroduction_Extend.Id),
                                                                FiledValue=qitem.Id,
                                                                OperatorEnum=OperatorEnum.Equal
                                                        }
                                                    };
                                                    goods_OrderIntroductionRepository.Update(keyValues1, wheres1);
                                                }
                                            }
                                        }
                                    }
                                    catch (Exception)
                                    {
                                        Helper.LogHelper.Write("AutoAfterSaleOrderSendCommission:更新推荐供应商返佣失败");
                                    }

                                    try
                                    {
                                        //更新微店返佣
                                        var ssList = smallShops_CommissionRepository.GetList(new RB_SmallShops_Commission_Extend() { TenantId = item.TenantId, MallBaseId = item.MallBaseId, OrderId = Order.OrderId });
                                        if (ssList.Where(x => x.CommissionState == 1).Any())
                                        {
                                            //验证是否是自动结算
                                            var ssbaseModel = microShop_BasicsRepository.GetMicroShopBasicsList(new RB_MicroShop_Basics() { TenantId = item.TenantId, MallBaseId = item.MallBaseId }).FirstOrDefault();
                                            if (("," + (ssbaseModel?.SettlementType ?? "") + ",").Contains("," + ((int)DistrbutorWithdrawWayEnum.ZDXJ).ToString() + ","))
                                            {
                                                var ssmodel = ssList.FirstOrDefault();
                                                //获取微店信息
                                                var smallModel = smallShops_InfoRepository.GetList(new RB_SmallShops_Info_Extend() { UserId = ssmodel.UserId, TenantId = item.TenantId, MallBaseId = item.MallBaseId }).FirstOrDefault();
                                                if (smallModel != null && smallModel.AuditStatus == DistributorAuditStatusEnum.Audited)
                                                {
                                                    //总佣金
                                                    decimal TotalCommission = 0, OldCommission = 0;
                                                    foreach (var qcitem in ssList.Where(x => x.CommissionState == 1))
                                                    {
                                                        //查询是否有申请退款
                                                        var afterSaleList = goods_OrderAfterSaleRepository.GetList(new RB_Goods_OrderAfterSale_Extend() { OrderDetialId = qcitem.OrderDetailId, Type = 1, MallBaseId = item.MallBaseId, TenantId = item.TenantId });
                                                        if (!afterSaleList.Any())
                                                        {
                                                            TotalCommission += (qcitem.Commission ?? 0);
                                                        }
                                                    }
                                                    #region 看微店佣金是否是负数  是的话  需要走总佣金里减去
                                                    OldCommission = TotalCommission;
                                                    if ((smallModel.Commission ?? 0) < 0)
                                                    {
                                                        TotalCommission += (smallModel?.Commission ?? 0);
                                                    }
                                                    #endregion
                                                    if (TotalCommission > 0)
                                                    {
                                                        decimal RemitMoney = TotalCommission, fee = 0;
                                                        var feeValue = ssbaseModel?.WithdrawalFree ?? 0;
                                                        if (feeValue > 0)
                                                        {
                                                            fee = Math.Round(TotalCommission * (feeValue) / 100, 2, MidpointRounding.AwayFromZero);
                                                            RemitMoney = TotalCommission - fee;
                                                        }
                                                        var minModel = miniProgramRepository.GetEntity<RB_MiniProgram_Extend>(item.MallBaseId);
                                                        var umodel = member_UserRepository.GetEntity(ssmodel.UserId);
                                                        //打款
                                                        Random R = new Random();
                                                        int Rstr = R.Next(111, 999);
                                                        string OrderNum = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr;
                                                        int IsNormalServer = Convert.ToInt32(Config.IsNormalServer);
                                                        var flagpay = false;
                                                        if (IsNormalServer == 1)
                                                        {
                                                            flagpay = PayUtil.GetTransfersOrder(OrderNum, RemitMoney, (ssmodel.UserId ?? 0).ToString(), umodel.OpenId, minModel, "赞羊微店佣金打款");
                                                        }
                                                        if (flagpay)
                                                        {
                                                            //更新状态
                                                            foreach (var qcitem in ssList.Where(x => x.CommissionState == 1))
                                                            {
                                                                if (smallModel != null && smallModel.AuditStatus == DistributorAuditStatusEnum.Audited)
                                                                {
                                                                    //更新返佣状态
                                                                    Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                                                        { nameof(RB_SmallShops_Commission_Extend.CommissionState),2},
                                                                        { nameof(RB_SmallShops_Commission_Extend.IsRemit),1},
                                                                        { nameof(RB_SmallShops_Commission_Extend.UpdateDate),DateTime.Now},
                                                                    };
                                                                    List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                                                        new WhereHelper(){
                                                                                FiledName=nameof(RB_SmallShops_Commission_Extend.Id),
                                                                                FiledValue=qcitem.Id,
                                                                                OperatorEnum=OperatorEnum.Equal
                                                                        }
                                                                    };
                                                                    smallShops_CommissionRepository.Update(keyValues1, wheres1);
                                                                }
                                                            }
                                                            //写入已提现数据
                                                            smallShops_RemitRepository.Insert(new RB_SmallShops_Remit()
                                                            {
                                                                Id = 0,
                                                                AccountName = "",
                                                                AccountNumber = "",
                                                                AppliedMoney = TotalCommission,
                                                                AuditDate = DateTime.Now,
                                                                AuditRemark = "",
                                                                AuditStatus = DistributorRemitAuditStatusEnum.HaveMoney,
                                                                BankName = "",
                                                                CreateDate = DateTime.Now,
                                                                Fee = fee,
                                                                FinanceId = 0,
                                                                MallBaseId = item.MallBaseId,
                                                                OrderNum = OrderNum,
                                                                RejectDate = null,
                                                                RejectRemark = "",
                                                                RemitDate = DateTime.Now,
                                                                RemitMoney = RemitMoney,
                                                                RemitRemark = "自动结算打款",
                                                                ReOrderIds = "[" + (omodel.OrderId).ToString() + "]",
                                                                ReOrderNos = "\"" + omodel.OrderNo + "\"：" + RemitMoney + "元",
                                                                TenantId = item.TenantId,
                                                                UserId = ssmodel.UserId,
                                                                WithdrawalWay = DistrbutorWithdrawWayEnum.ZDXJ
                                                            });
                                                        }
                                                        else
                                                        {
                                                            //更新状态
                                                            foreach (var qcitem in ssList.Where(x => x.CommissionState == 1))
                                                            {
                                                                if (smallModel != null && smallModel.AuditStatus == DistributorAuditStatusEnum.Audited)
                                                                {
                                                                    //更新返佣状态
                                                                    Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                                                        { nameof(RB_SmallShops_Commission_Extend.CommissionState),2},
                                                                        { nameof(RB_SmallShops_Commission_Extend.IsRemit),1},
                                                                        { nameof(RB_SmallShops_Commission_Extend.UpdateDate),DateTime.Now},
                                                                    };
                                                                    List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                                                        new WhereHelper(){
                                                                                FiledName=nameof(RB_SmallShops_Commission_Extend.Id),
                                                                                FiledValue=qcitem.Id,
                                                                                OperatorEnum=OperatorEnum.Equal
                                                                        }
                                                                    };
                                                                    smallShops_CommissionRepository.Update(keyValues1, wheres1);
                                                                }
                                                            }
                                                            //写入已提现数据
                                                            smallShops_RemitRepository.Insert(new RB_SmallShops_Remit()
                                                            {
                                                                Id = 0,
                                                                AccountName = "",
                                                                AccountNumber = "",
                                                                AppliedMoney = TotalCommission,
                                                                AuditDate = DateTime.Now,
                                                                AuditRemark = "自动现结失败，变更为手动打款",
                                                                AuditStatus = DistributorRemitAuditStatusEnum.ToPlayWith,
                                                                BankName = "",
                                                                CreateDate = DateTime.Now,
                                                                Fee = fee,
                                                                FinanceId = 0,
                                                                MallBaseId = item.MallBaseId,
                                                                OrderNum = OrderNum,
                                                                RejectDate = null,
                                                                RejectRemark = "",
                                                                RemitDate = DateTime.Now,
                                                                RemitMoney = RemitMoney,
                                                                RemitRemark = "",
                                                                ReOrderIds = "[" + (omodel.OrderId).ToString() + "]",
                                                                ReOrderNos = "\"" + omodel.OrderNo + "\"：" + RemitMoney + "元",
                                                                TenantId = item.TenantId,
                                                                UserId = ssmodel.UserId,
                                                                WithdrawalWay = DistrbutorWithdrawWayEnum.ZDDK
                                                            });
                                                        }
                                                        //更新微店佣金等于0                                            
                                                        Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                                            { nameof(RB_SmallShops_Info_Extend.TotalCommission),(smallModel.TotalCommission??0) + OldCommission},
                                                            { nameof(RB_SmallShops_Info_Extend.Commission), TotalCommission}
                                                        };
                                                        List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                                            new WhereHelper(){
                                                                    FiledName=nameof(RB_SmallShops_Info_Extend.Id),
                                                                    FiledValue=smallModel.Id,
                                                                    OperatorEnum=OperatorEnum.Equal
                                                            }
                                                        };
                                                        bool flag1 = smallShops_InfoRepository.Update(keyValues2, wheres2);
                                                    }
                                                    else if (TotalCommission < 0)
                                                    {
                                                        //存在微店佣金里  继续负数累加                                      
                                                        Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                                            { nameof(RB_SmallShops_Info_Extend.TotalCommission),(smallModel.TotalCommission??0) + OldCommission},
                                                            { nameof(RB_SmallShops_Info_Extend.Commission),TotalCommission},
                                                        };
                                                        List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                                            new WhereHelper(){
                                                                    FiledName=nameof(RB_SmallShops_Info_Extend.Id),
                                                                    FiledValue=smallModel.Id,
                                                                    OperatorEnum=OperatorEnum.Equal
                                                            }
                                                        };
                                                        bool flag1 = smallShops_InfoRepository.Update(keyValues2, wheres2);
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                foreach (var qitem in ssList.Where(x => x.CommissionState == 1))
                                                {
                                                    //查询是否有申请退款
                                                    var afterSaleList = goods_OrderAfterSaleRepository.GetList(new RB_Goods_OrderAfterSale_Extend() { OrderDetialId = qitem.OrderDetailId, Type = 1, MallBaseId = item.MallBaseId, TenantId = item.TenantId });
                                                    if (!afterSaleList.Any())
                                                    {
                                                        //获取微店信息
                                                        var smallModel = smallShops_InfoRepository.GetList(new RB_SmallShops_Info_Extend() { UserId = qitem.UserId, TenantId = item.TenantId, MallBaseId = item.MallBaseId }).FirstOrDefault();
                                                        if (smallModel != null && smallModel.AuditStatus == DistributorAuditStatusEnum.Audited)
                                                        {
                                                            //更新分销商佣金
                                                            Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                                            { nameof(RB_SmallShops_Info_Extend.TotalCommission),(smallModel.TotalCommission??0)+(qitem.Commission??0)},
                                                            { nameof(RB_SmallShops_Info_Extend.Commission),(smallModel.Commission??0)+(qitem.Commission??0)},
                                                        };
                                                            List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                                            new WhereHelper(){
                                                                    FiledName=nameof(RB_SmallShops_Info_Extend.Id),
                                                                    FiledValue=smallModel.Id,
                                                                    OperatorEnum=OperatorEnum.Equal
                                                            }
                                                        };
                                                            bool flag1 = smallShops_InfoRepository.Update(keyValues2, wheres2);
                                                            if (flag1)
                                                            {
                                                                //更新返佣状态
                                                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                                                { nameof(RB_SmallShops_Commission_Extend.CommissionState),2},
                                                                { nameof(RB_SmallShops_Commission_Extend.UpdateDate),DateTime.Now},
                                                            };
                                                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                                                new WhereHelper(){
                                                                        FiledName=nameof(RB_SmallShops_Commission_Extend.Id),
                                                                        FiledValue=qitem.Id,
                                                                        OperatorEnum=OperatorEnum.Equal
                                                                }
                                                            };
                                                                smallShops_CommissionRepository.Update(keyValues1, wheres1);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    catch (Exception)
                                    {
                                        Helper.LogHelper.Write("AutoAfterSaleOrderSendCommission:更新微店返佣失败");
                                    }
                                }
                            }
                            else
                            {
                                //直接结算佣金
                                //更新返佣为已返佣
                                var ocList = CommList.Where(x => x.OrderId == Order.OrderId).ToList();
                                if (ocList.Any())
                                {
                                    foreach (var qitem in ocList)
                                    {
                                        try
                                        {
                                            //查询是否有申请退款
                                            var afterSaleList = goods_OrderAfterSaleRepository.GetList(new RB_Goods_OrderAfterSale_Extend() { OrderDetialId = qitem.OrderDetailId, Type = 1, MallBaseId = item.MallBaseId, TenantId = item.TenantId });
                                            if (!afterSaleList.Any())
                                            {
                                                //获取分销商信息
                                                var disInfo = distributor_InfoRepository.GetList(new RB_Distributor_Info_Extend() { UserId = qitem.UserId, TenantId = item.TenantId, MallBaseId = item.MallBaseId }).FirstOrDefault();
                                                if (disInfo != null && disInfo.AuditStatus == DistributorAuditStatusEnum.Audited)
                                                {
                                                    //更新分销商佣金
                                                    Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                                        { nameof(RB_Distributor_Info_Extend.TotalCommission),(disInfo.TotalCommission ?? 0) + (qitem.Commission ?? 0)},
                                                        { nameof(RB_Distributor_Info_Extend.CommissionWithdrawal),(disInfo.CommissionWithdrawal ?? 0) + (qitem.Commission ?? 0)},
                                                    };
                                                    List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                                        new WhereHelper(){
                                                             FiledName=nameof(RB_Distributor_Info_Extend.Id),
                                                              FiledValue=disInfo.Id,
                                                               OperatorEnum=OperatorEnum.Equal
                                                        }
                                                    };
                                                    bool flag1 = distributor_InfoRepository.Update(keyValues2, wheres2);
                                                    if (flag1)
                                                    {
                                                        //更新返佣状态
                                                        Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                                            { nameof(RB_Goods_OrderCommission_Extend.CommissionState),2},
                                                            { nameof(RB_Goods_OrderCommission_Extend.UpdateDate),DateTime.Now},
                                                        };
                                                        List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                                            new WhereHelper(){
                                                                 FiledName=nameof(RB_Goods_OrderCommission_Extend.Id),
                                                                  FiledValue=qitem.Id,
                                                                   OperatorEnum=OperatorEnum.Equal
                                                            }
                                                        };
                                                        goods_OrderCommissionRepository.Update(keyValues1, wheres1);
                                                    }
                                                }
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            Helper.LogHelper.Write("AutoAfterSaleOrderSendCommission: OrderId=" + Order.OrderId + "  错误：" + ex.Message);
                                        }
                                    }
                                }

                                //更新推荐供应商返佣
                                try
                                {
                                    var oiList = goods_OrderIntroductionRepository.GetList(new RB_Goods_OrderIntroduction_Extend() { TenantId = item.TenantId, MallBaseId = item.MallBaseId, OrderId = Order.OrderId });
                                    if (oiList.Any())
                                    {
                                        foreach (var qitem in oiList)
                                        {
                                            //查询是否有申请退款
                                            var afterSaleList = goods_OrderAfterSaleRepository.GetList(new RB_Goods_OrderAfterSale_Extend() { OrderDetialId = qitem.OrderDetailId, Type = 1, MallBaseId = item.MallBaseId, TenantId = item.TenantId });
                                            if (!afterSaleList.Any())
                                            {
                                                //更新返佣状态
                                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                                        { nameof(RB_Goods_OrderIntroduction_Extend.CommissionState),2},
                                                        { nameof(RB_Goods_OrderIntroduction_Extend.UpdateDate),DateTime.Now},
                                                    };
                                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                                        new WhereHelper(){
                                                                FiledName=nameof(RB_Goods_OrderIntroduction_Extend.Id),
                                                                FiledValue=qitem.Id,
                                                                OperatorEnum=OperatorEnum.Equal
                                                        }
                                                    };
                                                goods_OrderIntroductionRepository.Update(keyValues1, wheres1);
                                            }
                                        }
                                    }
                                }
                                catch (Exception)
                                {
                                    Helper.LogHelper.Write("AutoAfterSaleOrderSendCommission:更新推荐供应商返佣失败");
                                }

                                try
                                {
                                    //更新微店返佣
                                    var ssList = smallShops_CommissionRepository.GetList(new RB_SmallShops_Commission_Extend() { TenantId = item.TenantId, MallBaseId = item.MallBaseId, OrderId = Order.OrderId });
                                    if (ssList.Where(x => x.CommissionState == 1).Any())
                                    {
                                        //验证是否是自动结算
                                        var ssbaseModel = microShop_BasicsRepository.GetMicroShopBasicsList(new RB_MicroShop_Basics() { TenantId = item.TenantId, MallBaseId = item.MallBaseId }).FirstOrDefault();
                                        if (("," + (ssbaseModel?.SettlementType ?? "") + ",").Contains("," + ((int)DistrbutorWithdrawWayEnum.ZDXJ).ToString() + ","))
                                        {
                                            var ssmodel = ssList.FirstOrDefault();
                                            //获取微店信息
                                            var smallModel = smallShops_InfoRepository.GetList(new RB_SmallShops_Info_Extend() { UserId = ssmodel.UserId, TenantId = item.TenantId, MallBaseId = item.MallBaseId }).FirstOrDefault();
                                            if (smallModel != null && smallModel.AuditStatus == DistributorAuditStatusEnum.Audited)
                                            {
                                                //总佣金
                                                decimal TotalCommission = 0, OldCommission = 0;
                                                foreach (var qcitem in ssList.Where(x => x.CommissionState == 1))
                                                {
                                                    //查询是否有申请退款
                                                    var afterSaleList = goods_OrderAfterSaleRepository.GetList(new RB_Goods_OrderAfterSale_Extend() { OrderDetialId = qcitem.OrderDetailId, Type = 1, MallBaseId = item.MallBaseId, TenantId = item.TenantId });
                                                    if (!afterSaleList.Any())
                                                    {
                                                        TotalCommission += (qcitem.Commission ?? 0);
                                                    }
                                                }
                                                #region 看微店佣金是否是负数  是的话  需要走总佣金里减去
                                                OldCommission = TotalCommission;
                                                if ((smallModel.Commission ?? 0) < 0)
                                                {
                                                    TotalCommission += (smallModel?.Commission ?? 0);
                                                }
                                                #endregion
                                                if (TotalCommission > 0)
                                                {
                                                    decimal RemitMoney = TotalCommission, fee = 0;
                                                    var feeValue = ssbaseModel?.WithdrawalFree ?? 0;
                                                    if (feeValue > 0)
                                                    {
                                                        fee = Math.Round(TotalCommission * (feeValue) / 100, 2, MidpointRounding.AwayFromZero);
                                                        RemitMoney = TotalCommission - fee;
                                                    }
                                                    var minModel = miniProgramRepository.GetEntity<RB_MiniProgram_Extend>(item.MallBaseId);
                                                    var umodel = member_UserRepository.GetEntity(ssmodel.UserId);
                                                    //打款
                                                    Random R = new Random();
                                                    int Rstr = R.Next(111, 999);
                                                    string OrderNum = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr;
                                                    int IsNormalServer = Convert.ToInt32(Config.IsNormalServer);
                                                    var flagpay = false;
                                                    if (IsNormalServer == 1)
                                                    {
                                                        flagpay = PayUtil.GetTransfersOrder(OrderNum, RemitMoney, (ssmodel.UserId ?? 0).ToString(), umodel.OpenId, minModel, "赞羊微店佣金打款");
                                                    }
                                                    if (flagpay)
                                                    {
                                                        //更新状态
                                                        foreach (var qcitem in ssList.Where(x => x.CommissionState == 1))
                                                        {
                                                            if (smallModel != null && smallModel.AuditStatus == DistributorAuditStatusEnum.Audited)
                                                            {
                                                                //更新返佣状态
                                                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                                                        { nameof(RB_SmallShops_Commission_Extend.CommissionState),2},
                                                                        { nameof(RB_SmallShops_Commission_Extend.IsRemit),1},
                                                                        { nameof(RB_SmallShops_Commission_Extend.UpdateDate),DateTime.Now},
                                                                    };
                                                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                                                        new WhereHelper(){
                                                                                FiledName=nameof(RB_SmallShops_Commission_Extend.Id),
                                                                                FiledValue=qcitem.Id,
                                                                                OperatorEnum=OperatorEnum.Equal
                                                                        }
                                                                    };
                                                                smallShops_CommissionRepository.Update(keyValues1, wheres1);
                                                            }
                                                        }
                                                        //写入已提现数据
                                                        smallShops_RemitRepository.Insert(new RB_SmallShops_Remit()
                                                        {
                                                            Id = 0,
                                                            AccountName = "",
                                                            AccountNumber = "",
                                                            AppliedMoney = TotalCommission,
                                                            AuditDate = DateTime.Now,
                                                            AuditRemark = "",
                                                            AuditStatus = DistributorRemitAuditStatusEnum.HaveMoney,
                                                            BankName = "",
                                                            CreateDate = DateTime.Now,
                                                            Fee = fee,
                                                            FinanceId = 0,
                                                            MallBaseId = item.MallBaseId,
                                                            OrderNum = OrderNum,
                                                            RejectDate = null,
                                                            RejectRemark = "",
                                                            RemitDate = DateTime.Now,
                                                            RemitMoney = RemitMoney,
                                                            RemitRemark = "自动结算打款",
                                                            ReOrderIds = "[" + (omodel.OrderId).ToString() + "]",
                                                            ReOrderNos = "\"" + omodel.OrderNo + "\"：" + RemitMoney + "元",
                                                            TenantId = item.TenantId,
                                                            UserId = ssmodel.UserId,
                                                            WithdrawalWay = DistrbutorWithdrawWayEnum.ZDXJ
                                                        });
                                                    }
                                                    else
                                                    {
                                                        //更新状态
                                                        foreach (var qcitem in ssList.Where(x => x.CommissionState == 1))
                                                        {
                                                            if (smallModel != null && smallModel.AuditStatus == DistributorAuditStatusEnum.Audited)
                                                            {
                                                                //更新返佣状态
                                                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                                                        { nameof(RB_SmallShops_Commission_Extend.CommissionState),2},
                                                                        { nameof(RB_SmallShops_Commission_Extend.IsRemit),1},
                                                                        { nameof(RB_SmallShops_Commission_Extend.UpdateDate),DateTime.Now},
                                                                    };
                                                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                                                        new WhereHelper(){
                                                                                FiledName=nameof(RB_SmallShops_Commission_Extend.Id),
                                                                                FiledValue=qcitem.Id,
                                                                                OperatorEnum=OperatorEnum.Equal
                                                                        }
                                                                    };
                                                                smallShops_CommissionRepository.Update(keyValues1, wheres1);
                                                            }
                                                        }
                                                        //写入已提现数据
                                                        smallShops_RemitRepository.Insert(new RB_SmallShops_Remit()
                                                        {
                                                            Id = 0,
                                                            AccountName = "",
                                                            AccountNumber = "",
                                                            AppliedMoney = TotalCommission,
                                                            AuditDate = DateTime.Now,
                                                            AuditRemark = "自动现结失败，变更为手动打款",
                                                            AuditStatus = DistributorRemitAuditStatusEnum.ToPlayWith,
                                                            BankName = "",
                                                            CreateDate = DateTime.Now,
                                                            Fee = fee,
                                                            FinanceId = 0,
                                                            MallBaseId = item.MallBaseId,
                                                            OrderNum = OrderNum,
                                                            RejectDate = null,
                                                            RejectRemark = "",
                                                            RemitDate = DateTime.Now,
                                                            RemitMoney = RemitMoney,
                                                            RemitRemark = "",
                                                            ReOrderIds = "[" + (omodel.OrderId).ToString() + "]",
                                                            ReOrderNos = "\"" + omodel.OrderNo + "\"：" + RemitMoney + "元",
                                                            TenantId = item.TenantId,
                                                            UserId = ssmodel.UserId,
                                                            WithdrawalWay = DistrbutorWithdrawWayEnum.ZDDK
                                                        });
                                                    }
                                                    //更新微店佣金等于0                                            
                                                    Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                                            { nameof(RB_SmallShops_Info_Extend.TotalCommission),(smallModel.TotalCommission??0) + OldCommission},
                                                            { nameof(RB_SmallShops_Info_Extend.Commission), TotalCommission}
                                                        };
                                                    List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                                            new WhereHelper(){
                                                                    FiledName=nameof(RB_SmallShops_Info_Extend.Id),
                                                                    FiledValue=smallModel.Id,
                                                                    OperatorEnum=OperatorEnum.Equal
                                                            }
                                                        };
                                                    bool flag1 = smallShops_InfoRepository.Update(keyValues2, wheres2);
                                                }
                                                else if (TotalCommission < 0)
                                                {
                                                    //存在微店佣金里  继续负数累加                                      
                                                    Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                                            { nameof(RB_SmallShops_Info_Extend.TotalCommission),(smallModel.TotalCommission??0) + OldCommission},
                                                            { nameof(RB_SmallShops_Info_Extend.Commission),TotalCommission},
                                                        };
                                                    List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                                            new WhereHelper(){
                                                                    FiledName=nameof(RB_SmallShops_Info_Extend.Id),
                                                                    FiledValue=smallModel.Id,
                                                                    OperatorEnum=OperatorEnum.Equal
                                                            }
                                                        };
                                                    bool flag1 = smallShops_InfoRepository.Update(keyValues2, wheres2);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            foreach (var qitem in ssList.Where(x => x.CommissionState == 1))
                                            {
                                                //查询是否有申请退款
                                                var afterSaleList = goods_OrderAfterSaleRepository.GetList(new RB_Goods_OrderAfterSale_Extend() { OrderDetialId = qitem.OrderDetailId, Type = 1, MallBaseId = item.MallBaseId, TenantId = item.TenantId });
                                                if (!afterSaleList.Any())
                                                {
                                                    //获取微店信息
                                                    var smallModel = smallShops_InfoRepository.GetList(new RB_SmallShops_Info_Extend() { UserId = qitem.UserId, TenantId = item.TenantId, MallBaseId = item.MallBaseId }).FirstOrDefault();
                                                    if (smallModel != null && smallModel.AuditStatus == DistributorAuditStatusEnum.Audited)
                                                    {
                                                        //更新分销商佣金
                                                        Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                                        { nameof(RB_SmallShops_Info_Extend.TotalCommission),(smallModel.TotalCommission??0)+(qitem.Commission??0)},
                                                        { nameof(RB_SmallShops_Info_Extend.Commission),(smallModel.Commission??0)+(qitem.Commission??0)},
                                                    };
                                                        List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                                        new WhereHelper(){
                                                                FiledName=nameof(RB_SmallShops_Info_Extend.Id),
                                                                FiledValue=smallModel.Id,
                                                                OperatorEnum=OperatorEnum.Equal
                                                        }
                                                    };
                                                        bool flag1 = smallShops_InfoRepository.Update(keyValues2, wheres2);
                                                        if (flag1)
                                                        {
                                                            //更新返佣状态
                                                            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                                            { nameof(RB_SmallShops_Commission_Extend.CommissionState),2},
                                                            { nameof(RB_SmallShops_Commission_Extend.UpdateDate),DateTime.Now},
                                                        };
                                                            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                                            new WhereHelper(){
                                                                    FiledName=nameof(RB_SmallShops_Commission_Extend.Id),
                                                                    FiledValue=qitem.Id,
                                                                    OperatorEnum=OperatorEnum.Equal
                                                            }
                                                        };
                                                            smallShops_CommissionRepository.Update(keyValues1, wheres1);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                catch (Exception)
                                {
                                    Helper.LogHelper.Write("AutoAfterSaleOrderSendCommission:更新微店返佣失败");
                                }
                            }
                        }
                    }

                    //发放活动中奖名单
                    try
                    {
                        var alist = goods_ActivityRepository.GetCanReceiveList(new RB_Goods_Activity_Extend() { TenantId = item.TenantId, MallBaseId = item.MallBaseId });
                        foreach (var qitem in alist)
                        {
                            //查询活动下所有满足的订单
                            var orderList = goods_OrderRepository.GetGoodsNumForCategoryOrGoods(qitem, 0, item.AfterTime);
                            if (orderList.Any())
                            {
                                List<int> AllUserIdList = new List<int>();
                                if (qitem.Tier == 1 || qitem.Tier == 2 || qitem.Tier == 3)
                                {
                                    //如果属于有限定层级  需要先遍历 查询出对应的层级人员
                                    foreach (var q2item in orderList)
                                    {
                                        List<int> UserIdList = JsonConvert.DeserializeObject<List<int>>("[" + q2item.UserTree + "]");
                                        q2item.OneUserId = UserIdList[0];
                                        if (UserIdList.Count() > 1)
                                        {
                                            q2item.TwoUserId = UserIdList[1];
                                        }
                                        if (UserIdList.Count() > 2)
                                        {
                                            q2item.TwoUserId = UserIdList[2];
                                        }
                                    }
                                    if (qitem.Tier == 1)
                                    {
                                        AllUserIdList.AddRange(orderList.Select(x => x.OneUserId).Distinct().ToList());
                                    }
                                    else if (qitem.Tier == 2)
                                    {
                                        AllUserIdList.AddRange(orderList.Select(x => x.OneUserId).Distinct().ToList());
                                        AllUserIdList.AddRange(orderList.Select(x => x.TwoUserId).Distinct().ToList());
                                    }
                                    else if (qitem.Tier == 3)
                                    {
                                        AllUserIdList.AddRange(orderList.Select(x => x.OneUserId).Distinct().ToList());
                                        AllUserIdList.AddRange(orderList.Select(x => x.TwoUserId).Distinct().ToList());
                                        AllUserIdList.AddRange(orderList.Select(x => x.ThreeUserId).Distinct().ToList());
                                    }
                                }
                                else
                                {
                                    string UserTree = string.Join(",", orderList.Select(x => x.UserTree));
                                    AllUserIdList = JsonConvert.DeserializeObject<List<int>>("[" + UserTree + "]");
                                }
                                AllUserIdList = AllUserIdList.Where(x => x > 10000).Distinct().ToList();//去除重复数据  表示这么多用户在参加活动
                                //查询已拿到活动名单的用户
                                var myPrizeList = goods_Activity_GetRepository.GetList(new RB_Goods_Activity_Get_Extend() { TenantId = item.TenantId, MallBaseId = item.MallBaseId, ActivityId = qitem.Id, UserIds = string.Join(",", AllUserIdList) });
                                foreach (var UserId in AllUserIdList)
                                {
                                    var prizeModel = myPrizeList.Where(x => x.UserId == UserId && x.ActivityId == qitem.Id).FirstOrDefault();
                                    if (prizeModel == null)
                                    {
                                        List<RB_Goods_Activity_Extend> MyOrderList = new List<RB_Goods_Activity_Extend>();
                                        if (qitem.Tier == 1)
                                        {
                                            MyOrderList = orderList.Where(x => x.OneUserId == UserId).ToList();
                                        }
                                        else if (qitem.Tier == 2)
                                        {
                                            MyOrderList = orderList.Where(x => x.OneUserId == UserId || x.TwoUserId == UserId).ToList();
                                        }
                                        else if (qitem.Tier == 3)
                                        {
                                            MyOrderList = orderList.Where(x => x.OneUserId == UserId || x.TwoUserId == UserId || x.ThreeUserId == UserId).ToList();
                                        }
                                        else
                                        {
                                            MyOrderList = orderList.Where(x => ("," + x.UserTree + ",").Contains("," + UserId + ",")).ToList();
                                        }
                                        //验证是否已满足活动
                                        bool ActivityOk = false;
                                        if (qitem.Type == 1)
                                        {
                                            //订单数量
                                            var OrderNum = MyOrderList.Select(x => x.OrderId).Distinct().Count();
                                            if (OrderNum >= qitem.OrderNum)
                                            {
                                                ActivityOk = true;
                                            }
                                        }
                                        else if (qitem.Type == 2)
                                        {
                                            //订单金额
                                            var OrderMoney = MyOrderList.Sum(x => x.Final_Price);
                                            if (OrderMoney >= qitem.OrderMoney)
                                            {
                                                ActivityOk = true;
                                            }
                                        }
                                        else
                                        {
                                            //商品数量
                                            var GoodsNum = MyOrderList.Sum(x => x.Number);
                                            if (GoodsNum >= qitem.GoodsNum)
                                            {
                                                ActivityOk = true;
                                            }
                                        }
                                        if (ActivityOk)
                                        {
                                            string code = GetActivityCode(qitem);
                                            //验证code是否重复
                                            while (true)
                                            {
                                                var vlist = goods_Activity_GetRepository.GetList(new RB_Goods_Activity_Get_Extend() { TenantId = item.TenantId, MallBaseId = item.MallBaseId, Code = code });
                                                if (vlist.Any())
                                                {
                                                    code = GetActivityCode(qitem);
                                                }
                                                else
                                                {
                                                    break;
                                                }
                                            }
                                            //新增中奖名单
                                            goods_Activity_GetRepository.Insert(new RB_Goods_Activity_Get()
                                            {
                                                ActivityId = qitem.Id,
                                                Id = 0,
                                                Code = code,
                                                State = 1,
                                                UserId = UserId,
                                                OrderIds = string.Join(",", MyOrderList.Select(x => x.OrderId).Distinct()),
                                                TenantId = item.TenantId,
                                                MallBaseId = item.MallBaseId,
                                                CreateDate = DateTime.Now,
                                                UpdateDate = DateTime.Now
                                            });
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Helper.LogHelper.Write("发放活动中奖名单失败:" + ex.Message);
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                Helper.LogHelper.Write("AutoAfterSaleOrderSendCommission:" + ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 获取活动验证码
        /// </summary>
        /// <param name="qitem"></param>
        /// <returns></returns>
        private static string GetActivityCode(RB_Goods_Activity_Extend qitem)
        {
            int min = Convert.ToInt32("1111111111".Substring(0, qitem.CodeLength));
            int max = Convert.ToInt32("9999999999".Substring(0, qitem.CodeLength));
            Random rd = new Random();
            string code = rd.Next(min, max).ToString();
            return code;
        }

        #endregion

        #region 退款批量制单
        /// <summary>
        /// 批量制退款单
        /// </summary>
        /// <returns></returns>
        public static bool AutoCreateFinanceRefund()
        {
            try
            {
                //先查询规则
                var financeConfigurineList = financeConfigurineRepository.GetList(new RB_Finance_Configurine_Extend { Type = 1 });

                //根据规则中的小程序，查询订单详情信息
                if (financeConfigurineList != null && financeConfigurineList.Any())
                {
                    foreach (var item in financeConfigurineList)
                    {
                        if (item.StartTime.HasValue && item.StartTime < System.DateTime.Now)//判断开始时间是否大于当前时间
                        {
                            //查询最近是否已经生成了财务单据
                            var addFinance = false;

                            DateTime startDate = System.DateTime.Now.AddDays(-1);
                            var recordModel = financeRecordRepository.GetList(new RB_Finance_Record_Extend { TenantId = item.TenantId, MallBaseId = item.MallBaseId, Type = 3 }).OrderByDescending(x => x.CreateDate).FirstOrDefault();
                            if (recordModel == null)//没生成单据
                            {
                                if (Convert.ToDateTime(item.StartTime.Value.AddDays(item.IntervalDay ?? 0).ToString("yyyy-MM-dd 00:00:00")) <= Convert.ToDateTime(System.DateTime.Now.ToString("yyyy-MM-dd 00:00:00")))//判断开始时间加上执行周期是否等于当前日期
                                {
                                    //startDate = item.StartTime.Value;
                                    startDate = Convert.ToDateTime("2020-07-03");
                                    addFinance = true;
                                }
                            }
                            else
                            {
                                if (Convert.ToDateTime(recordModel.CreateDate.Value.AddDays(item.IntervalDay ?? 0).ToString("yyyy-MM-dd 00:00:00")) <= Convert.ToDateTime(System.DateTime.Now.ToString("yyyy-MM-dd 00:00:00")))//判断最近一次执行的时间加上执行周期是否等于当前日期
                                {
                                    startDate = recordModel.CreateDate.Value;
                                    addFinance = true;
                                }
                            }
                            DateTime endDate = startDate.AddDays(item.IntervalDay ?? 0);//结束时间
                            if (addFinance)//满足今天执行的条件查询间隔周期的订单
                            {
                                //查询所有的退款
                                var olist = goods_OrderRepository.GetOrderRefunedCreateList(item.TenantId, item.MallBaseId, startDate.ToString("yyyy-MM-dd"), endDate.ToString("yyyy-MM-dd"));
                                //查询所有的售后退款
                                var afterlist = goods_OrderAfterSaleRepository.GetList_V2(new RB_Goods_OrderAfterSale_Extend() { FStartTime = startDate.ToString("yyyy-MM-dd"), FEndTime = endDate.AddDays(-1).ToString("yyyy-MM-dd"), TenantId = item.TenantId, MallBaseId = item.MallBaseId, Type = 1, ReOrderStatus = OrderAfterSaleStatusEnum.Completed });
                                if (olist.Any() || afterlist.Any())
                                {
                                    OrderRefundFinanceModule(olist, afterlist);
                                }
                                else
                                {
                                    //没有  创建一条记录 财务单据为0的记录
                                    RB_Finance_Record_Extend record = new RB_Finance_Record_Extend();
                                    record.MallBaseId = item.MallBaseId;
                                    record.TenantId = item.TenantId;
                                    record.Type = 3;
                                    record.CreateDate = System.DateTime.Now;
                                    record.FinanceId = 0;
                                    record.RecordDetailList = new List<RB_Finance_RecordDetail_Extend>();
                                    int recordId = financeRecordRepository.Insert(record);
                                }
                            }
                        }
                    }
                }

                return true;
            }
            catch (Exception ex)
            {
                Helper.LogHelper.Write("AutoCreateFinanceRefund:" + ex.Message);
                return false;
            }
        }


        /// <summary>
        /// 生成退款单据
        /// </summary>
        /// <param name="omodel"></param>
        /// <returns></returns>
        public static bool OrderRefundFinanceModule(List<RB_Goods_Order_Extend> oList, List<RB_Goods_OrderAfterSale_Extend> afterList)
        {
            var flag = false;
            try
            {
                //先查询规则
                var financeConfigurineList = financeConfigurineRepository.GetList(new RB_Finance_Configurine_Extend { Type = 3 });
                if (financeConfigurineList != null && financeConfigurineList.Any())
                {
                    var item = financeConfigurineList.FirstOrDefault();

                    RB_Finance_Record_Extend record = new RB_Finance_Record_Extend();
                    record.MallBaseId = item.MallBaseId;
                    record.TenantId = item.TenantId;
                    record.Type = 3;
                    record.CreateDate = System.DateTime.Now;
                    record.RecordDetailList = new List<RB_Finance_RecordDetail_Extend>();

                    decimal TotalMoney = 0;
                    var detailList = new List<object>();
                    #region 查询所有的订单
                    List<RB_ECFinanceId_Relation> ECList = new List<RB_ECFinanceId_Relation>();
                    if (oList.Any())
                    {
                        string orderids = string.Join(",", oList.Select(x => x.OrderId));
                        var dlist = goodsOrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { OrderIds = orderids });
                        foreach (var qitem in dlist)
                        {
                            ECList.Add(new RB_ECFinanceId_Relation()
                            {
                                ECOrderId = qitem.OrderId,
                                ECOrderDetailId = qitem.Id
                            });
                        }
                    }
                    #endregion
                    //订单退款
                    foreach (var omodel in oList)
                    {
                        decimal Money = omodel.Income ?? 0;
                        TotalMoney += Money;
                        //查询用户
                        var umodel = member_UserRepository.GetEntity(omodel.UserId);
                        if (umodel == null) { return false; }

                        detailList.Add(
                            new
                            {
                                CostTypeId = item.RefundCostTypeId,
                                Number = 1,
                                OriginalMoney = Money,
                                UnitPrice = Money,
                                Remark = omodel.OrderNo
                            }
                        );

                        RB_Finance_RecordDetail_Extend financeRecordDetail = new RB_Finance_RecordDetail_Extend
                        {

                            ID = 0,
                            RecordId = 0,
                            Type = record.Type,
                            TenantId = record.TenantId,
                            MallBaseId = record.MallBaseId,
                            FinanceId = 0,
                            CreateDate = record.CreateDate,
                            Name = "订单取消退款",
                            OrderId = omodel.OrderId,
                            OrderDetailId = 0,
                            GoodsPrice = 0,
                            FreightMoney = 0,
                            Unit_Price = Money,
                            Number = 1
                        };
                        record.RecordDetailList.Add(financeRecordDetail);
                    }
                    //售后退款
                    foreach (var dmodel in afterList)
                    {
                        decimal Money = dmodel.RefundActual ?? 0;
                        TotalMoney += Money;
                        //查询用户
                        var umodel = member_UserRepository.GetEntity(dmodel.UserId);
                        if (umodel == null) { return false; }
                        var omodel = goods_OrderRepository.GetEntity(dmodel.OrderId);
                        if (omodel == null) { return false; }

                        string dstr = "客人付款:" + (dmodel.Income ?? 0) + "，退款:" + (dmodel.RefundActual ?? 0);

                        detailList.Add(
                            new
                            {
                                CostTypeId = item.RefundCostTypeId,
                                Number = 1,
                                OriginalMoney = Money,
                                UnitPrice = Money,
                                Remark = "订单号：" + omodel.OrderNo + "  售后单号：" + (dmodel.ReOrderNo ?? "暂无") + "   " + dstr
                            }
                        );

                        RB_Finance_RecordDetail_Extend financeRecordDetail = new RB_Finance_RecordDetail_Extend
                        {

                            ID = 0,
                            RecordId = 0,
                            Type = record.Type,
                            TenantId = record.TenantId,
                            MallBaseId = record.MallBaseId,
                            FinanceId = 0,
                            CreateDate = record.CreateDate,
                            Name = "售后退款",
                            OrderId = omodel.OrderId,
                            OrderDetailId = dmodel.OrderDetialId ?? 0,
                            GoodsPrice = 0,
                            FreightMoney = 0,
                            Unit_Price = Money,
                            Number = 1
                        };
                        record.RecordDetailList.Add(financeRecordDetail);

                        ECList.Add(new RB_ECFinanceId_Relation()
                        {
                            ECOrderId = dmodel.OrderId,
                            ECOrderDetailId = dmodel.OrderDetialId
                        });
                    }

                    item.IsPublic = 8;//默认原路退款
                    string Remark = System.DateTime.Now.ToString("yyyy年MM月dd日") + " 自动生成财务单据";

                    var financeObj = new
                    {
                        CreateBy = Config.ExpendDirector,
                        item.IsPublic,
                        ClientType = 0,
                        ClientID = 0,
                        item.CurrencyId,
                        WBMoney = TotalMoney,
                        PayDate = DateTime.Now.ToString("yyyy-MM-dd"),
                        RB_Branch_Id = Config.ExpendBranchId,
                        TemplateId = item.WorkFlowId,
                        OrderSource = 16,
                        OtherType = 14,
                        ReFinanceId = 0,
                        Remark,
                        detailList,
                        RB_Depart_Id = Config.ExpendDepartment,
                        ECOrderList = ECList
                    };
                    string sign = EncryptionHelper.AesEncrypt(JsonHelper.Serialize(financeObj), Config.FinanceKey);
                    var resultInfo = new
                    {
                        msg = sign
                    };

                    string apiResult = Mall.Common.Plugin.HttpHelper.HttpPost(Config.PaymentFinanceApi, JsonHelper.Serialize(resultInfo), "");
                    JObject parmsJob = JObject.Parse(apiResult);
                    string resultCode = parmsJob.GetStringValue("resultCode");
                    int frid = parmsJob.GetInt("data", 0);
                    if (resultCode == "1" && frid > 0)//新增记录
                    {
                        record.FinanceId = frid;
                        int recordId = financeRecordRepository.Insert(record);
                        Helper.LogHelper.Write("退款单据ID：" + frid + ",记录id：" + recordId + "订单数量：" + record.RecordDetailList.Count());
                        record.RecordDetailList.ForEach(x => x.RecordId = recordId);
                        record.RecordDetailList.ForEach(x => x.FinanceId = frid);
                        flag = financeRecordDetailRepository.InsertBatch(record.RecordDetailList);

                        foreach (var omodel in oList)
                        {
                            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                { nameof(RB_Goods_Order_Extend.Remark), omodel.Remark +"   自动生成财务退款单据："+ frid}
                            };
                            List<WhereHelper> wheres = new List<WhereHelper>() {
                                new WhereHelper(){
                                 FiledName=nameof(RB_Goods_Order_Extend.OrderId),
                                  FiledValue=omodel.OrderId,
                                   OperatorEnum=OperatorEnum.Equal
                                },
                                new WhereHelper(){
                                 FiledName=nameof(RB_Goods_Order_Extend.TenantId),
                                  FiledValue=omodel.TenantId,
                                   OperatorEnum=OperatorEnum.Equal
                                },
                                new WhereHelper(){
                                 FiledName=nameof(RB_Goods_Order_Extend.MallBaseId),
                                  FiledValue=omodel.MallBaseId,
                                   OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            goods_OrderRepository.Update(keyValues, wheres);
                        }
                        foreach (var dmodel in afterList)
                        {
                            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                { nameof(RB_Goods_OrderAfterSale.ReRemark), dmodel.ReRemark +"   自动生成财务退款单据："+ frid},
                                { nameof(RB_Goods_OrderAfterSale.FinanceId), frid},
                            };
                            List<WhereHelper> wheres = new List<WhereHelper>() {
                                new WhereHelper(){
                                 FiledName=nameof(RB_Goods_OrderAfterSale.ReOrderId),
                                  FiledValue=dmodel.ReOrderId,
                                   OperatorEnum=OperatorEnum.Equal
                                },
                                new WhereHelper(){
                                 FiledName=nameof(RB_Goods_OrderAfterSale.TenantId),
                                  FiledValue=dmodel.TenantId,
                                   OperatorEnum=OperatorEnum.Equal
                                },
                                new WhereHelper(){
                                 FiledName=nameof(RB_Goods_OrderAfterSale.MallBaseId),
                                  FiledValue=dmodel.MallBaseId,
                                   OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            goods_OrderAfterSaleRepository.Update(keyValues, wheres);
                            goods_OrderAfterSaleLogRepository.Insert(new RB_Goods_OrderAfterSaleLog()
                            {
                                Id = 0,
                                Content = "自动生成财务退款单据：" + frid,
                                CreateDate = DateTime.Now,
                                MallBaseId = dmodel.MallBaseId,
                                ReOrderId = dmodel.ReOrderId,
                                TenantId = dmodel.TenantId,
                                Type = 2
                            });
                        }
                    }
                    Helper.LogHelper.Write(apiResult);
                }
            }
            catch (Exception ex)
            {
                Helper.LogHelper.Write(ex.Message);
            }

            return flag;
        }

        #endregion

        #region 七天自动是否下线

        public static bool AutoReleaseTheOffline()
        {
            try
            {
                var list = mallBaseRepository.GetListRepository(new Mall.Model.Extend.BaseSetUp.RB_MallBase_Extend() { });
                foreach (var item in list)
                {
                    var ulist = member_UserRepository.AutoReleaseTheOffline(item.TenantId, item.MallBaseId);
                    foreach (var qitem in ulist)
                    {
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_Member_User_Extend.SuperiorId),0},
                            { nameof(RB_Member_User_Extend.DownlineCondition),DistrbutorReferralsEnum.SCDJ},
                            { nameof(RB_Member_User_Extend.Remark),(qitem.Remark??"") +"  七天自动释放"},
                        };

                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_Member_User_Extend.Id),
                                  FiledValue=qitem.Id,
                                   OperatorEnum=OperatorEnum.Equal
                            },
                            new WhereHelper(){
                                 FiledName=nameof(RB_Goods_Order_Extend.TenantId),
                                  FiledValue=item.TenantId,
                                   OperatorEnum=OperatorEnum.Equal
                            },
                            new WhereHelper(){
                                 FiledName=nameof(RB_Goods_Order_Extend.MallBaseId),
                                  FiledValue=item.MallBaseId,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        member_UserRepository.Update(keyValues, wheres);
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                Helper.LogHelper.Write("AutoReleaseTheOffline:" + ex.Message);
                return false;
            }
        }

        #endregion

        #region 分享商VIP过期
        /// <summary>
        /// 分享商VIP过期
        /// </summary>
        /// <returns></returns>
        public static bool DistributorVipModule()
        {
            var flag = false;

            try
            {
                var baseList = distributor_BasicsRepository.GetList(new RB_Distributor_Basics_Extend());
                foreach (var itemBase in baseList)
                {
                    if ((itemBase?.IsEnableFXGrade ?? 2) == 1)//判断是否开启粉象等级
                    {
                        var fxGradeList = distributor_FXGradeRepository.GetList(new RB_Distributor_FXGrade_Extend { TenantId = itemBase.TenantId, MallBaseId = itemBase.MallBaseId });//获取小程序中的粉象等级
                        if (fxGradeList != null && fxGradeList.Any())
                        {
                            var fxGradeVipModel = fxGradeList.Where(x => x.IsGuest == 3).FirstOrDefault();//vip等级
                            var fxGradeModel = fxGradeList.Where(x => x.IsGuest == 1).FirstOrDefault();//普通会员等级
                            if (fxGradeVipModel != null && fxGradeModel != null)
                            {
                                var financeConfigurineList = distributor_InfoRepository.GetOverTimeVipList(new RB_Distributor_Info_Extend { TenantId = itemBase.TenantId, MallBaseId = itemBase.MallBaseId, IsSelectOverTime = 1, AuditStatus = DistributorAuditStatusEnum.Audited, FXGradeId = fxGradeVipModel.Id });//获取过期的粉象vip
                                if (financeConfigurineList != null && financeConfigurineList.Any())
                                {
                                    foreach (var item in financeConfigurineList)
                                    {
                                        //var list = financeConfigurineList.Where(x => x.MallBaseId == itemBase.MallBaseId & x.TenantId == itemBase.TenantId & x.FXGradeId == fxGradeVipModel.Id);
                                        Dictionary<string, object> keyValues = new Dictionary<string, object>() { };
                                        keyValues.Add(nameof(RB_Distributor_Info.FXGradeId), fxGradeModel.Id);
                                        List<WhereHelper> wheres = new List<WhereHelper>()
                                                {
                                                    new WhereHelper(){
                                                         FiledName=nameof(RB_Distributor_Info.Id),
                                                          FiledValue=item.Id,
                                                           OperatorEnum=OperatorEnum.Equal
                                                    },
                                                    new WhereHelper(){
                                                         FiledName=nameof(RB_Distributor_Info.TenantId),
                                                          FiledValue=item.TenantId,
                                                           OperatorEnum=OperatorEnum.Equal
                                                    },
                                                    new WhereHelper(){
                                                         FiledName=nameof(RB_Distributor_Info.MallBaseId),
                                                          FiledValue=item.MallBaseId,
                                                           OperatorEnum=OperatorEnum.Equal
                                                    }
                                                };
                                        flag = distributor_InfoRepository.Update(keyValues, wheres);

                                    }
                                }
                            }
                        }
                    }
                }

            }
            catch (Exception ex)
            {

                Helper.LogHelper.Write(ex.Message);
            }

            return flag;
        }
        #endregion

    }
}
