using DapperExtensions.Lambda;
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.Finance;
using Mall.Model.Entity.Product;
using Mall.Model.Extend.Finance;
using Mall.Model.Extend.Product;
using Mall.Model.Extend.User;
using Mall.Repository;
using Mall.Repository.BaseSetUp;
using Mall.Repository.Finance;
using Mall.Repository.Product;
using Mall.Repository.User;
using Mall.WindowsService.Helper;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

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();


        #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;
                                }
                            }
                            DateTime endDate = startDate.AddDays(item.IntervalDay ?? 0);//结束时间
                            if (addFinance)//满足今天执行的条件查询间隔周期的订单
                            {
                                StringBuilder builder = new StringBuilder();
                                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) ");
                                //                                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>();


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


                                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 > 0)
                                        {
                                            var newOrderGoods = new RB_Goods_OrderDetail_Extend();
                                            newOrderGoods = orderGoodsItem;
                                            newOrderGoods.FinanceType = 1;
                                            result.Add(newOrderGoods);

                                        }
                                        if (orderGoodsItem.FreightMoney.HasValue && orderGoodsItem.FreightMoney.Value > 0)
                                        {
                                            var newOrderGoods = new RB_Goods_OrderDetail_Extend();
                                            newOrderGoods = orderGoodsItem;
                                            newOrderGoods.FinanceType = 2;
                                            result.Add(newOrderGoods);
                                        }
                                        RB_Finance_RecordDetail financeRecordDetail = new RB_Finance_RecordDetail
                                        {

                                            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
                                        };
                                        record.RecordDetailList.Add(financeRecordDetail);
                                    }
                                }

                                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)) * (Convert.ToDecimal(Config.SettlementRate) / 100);

                                        OriginalFee += Math.Round(totalPrice, 2, MidpointRounding.AwayFromZero);
                                    }
                                    var detailList = result.Select(x => new
                                    {
                                        CostTypeId = x.FinanceType == 1 ? item.IncomeCostTypeId : item.FreightCostTypeId,
                                        Number = x.FinanceType == 1 ? x.Number : 1,
                                        OriginalMoney = x.FinanceType == 1 ? (x.Final_Price ?? 0) : (x.FreightMoney ?? 0),
                                        //  OriginalMoney = x.FinanceType == 1 ? ((x.Unit_Price ?? 0) * (x.Number ?? 0)) : x.FreightMoney,
                                        UnitPrice = x.FinanceType == 1 ? ((x.Final_Price ?? 0) / (x.Number ?? 0)) : x.FreightMoney,
                                        // UnitPrice = x.FinanceType == 1 ? (((x.Final_Price ?? 0) - (x.FreightMoney ?? 0)) / (x.Number ?? 0)) : x.FreightMoney,
                                        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
                                    };
                                    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)
            {

                Helper.LogHelper.Write(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);
                        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.GetList(new RB_Goods_Extend() { GoodsIds = goodsIds, TenantId = tenantId, MallBaseId = mallBaseId });
                                                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))
                                                    {
                                                        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);
                                                    }
                                                    //更新商品表库存
                                                    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);
                                                    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);
                                                    }
                                                }
                                            }
                                            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);
                                                }
                                            }
                                            //余额支付回滚

                                        }
                                        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;
                            }
                        }
                    }
                }
                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.CancelTime, 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);
                            }
                        }
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                Helper.LogHelper.Write("AutoCancelOrder:" + ex.Message);
                return false;
            }
        }


        /// <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.Any())
                        {
                            foreach (var item in ocList)
                            {
                                //查询是否有申请退款
                                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 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
                            });
                        }
                    }
                }
                else if (type == 3)
                {
                    //强制取消 (作废  使用新方法)

                }
            }
            return flag;
        }

        #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);
                                            }
                                        }
                                    }
                                }
                            }
                            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);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                Helper.LogHelper.Write("AutoAfterSaleOrderSendCommission:" + ex.Message);
                return false;
            }
        }

        #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(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>();
                                    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>();

                    decimal TotalMoney = 0;
                    var detailList = new List<object>();
                    //订单退款
                    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 financeRecordDetail = new RB_Finance_RecordDetail
                        {

                            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.Refund ?? 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.Refund ?? 0);

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

                        RB_Finance_RecordDetail financeRecordDetail = new RB_Finance_RecordDetail
                        {

                            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);
                    }

                    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
                    };
                    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

    }
}
