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

namespace Mall.Module.User
{
    /// <summary>
    /// 微店处理层
    /// </summary>
    public class SmallShopsModule
    {
        /// <summary>
        /// 用户管理
        /// </summary>
        private readonly RB_Member_UserRepository member_UserRepository = new RB_Member_UserRepository();
        /// <summary>
        /// 用户余额
        /// </summary>
        private readonly RB_Member_BalanceRepository member_BalanceRepository = new RB_Member_BalanceRepository();
        /// <summary>
        /// 小程序
        /// </summary>
        private readonly RB_MiniProgramRepository miniProgramRepository = new RB_MiniProgramRepository();
        /// <summary>
        /// 微店
        /// </summary>
        private readonly RB_SmallShops_InfoRepository smallShops_InfoRepository = new RB_SmallShops_InfoRepository();
        /// <summary>
        /// 微店价格
        /// </summary>
        private readonly RB_SmallShops_PriceRepository smallShops_PriceRepository = new RB_SmallShops_PriceRepository();
        /// <summary>
        /// 微店基础
        /// </summary>
        private readonly RB_MicroShop_BasicsRepository microShop_BasicsRepository = new RB_MicroShop_BasicsRepository();
        /// <summary>
        /// 微店提现
        /// </summary>
        private readonly RB_SmallShops_RemitRepository smallShops_RemitRepository = new RB_SmallShops_RemitRepository();
        /// <summary>
        /// 商品表
        /// </summary>
        private readonly RB_GoodsRepository goodsRepository = new RB_GoodsRepository();
        /// <summary>
        /// 规格价格
        /// </summary>
        private readonly RB_Goods_SpecificationPriceRepository goods_SpecificationPriceRepository = new RB_Goods_SpecificationPriceRepository();
        /// <summary>
        /// 规格
        /// </summary>
        private readonly RB_Goods_SpecificationRepository goods_SpecificationRepository = new RB_Goods_SpecificationRepository();
        /// <summary>
        /// 规格值
        /// </summary>
        private readonly RB_Goods_SpecificationValueRepository goods_SpecificationValueRepository = new RB_Goods_SpecificationValueRepository();

        /// <summary>
        /// 规格值
        /// </summary>
        private readonly RB_SmallShops_CustomRepository smallShopsCustomRepository = new RB_SmallShops_CustomRepository();
        /// <summary>
        /// 订单
        /// </summary>
        private readonly RB_Goods_OrderRepository goods_OrderRepository = new RB_Goods_OrderRepository();
        /// <summary>
        /// 订单明细
        /// </summary>
        private readonly RB_Goods_OrderDetailRepository goods_OrderDetailRepository = new RB_Goods_OrderDetailRepository();
        private readonly RB_SmallShops_CommissionRepository smallShopsCommissionRepository = new RB_SmallShops_CommissionRepository();
        /// <summary>
        /// 财务单据规则
        /// </summary>
        private static RB_Finance_ConfigurineRepository financeConfigurineRepository = new RB_Finance_ConfigurineRepository();

        /// <summary>
        /// 可简化
        /// </summary>
        private readonly RB_SmallShops_RemitRepository smallShopsRemitRepository = new RB_SmallShops_RemitRepository();



        #region 微店管理

        /// <summary>
        /// 获取微店分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_SmallShops_Info_Extend> GetSmallShopsPageList(int pageIndex, int pageSize, out long count, RB_SmallShops_Info_Extend demodel)
        {
            var list = smallShops_InfoRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            return list;
        }
        /// <summary>
        /// 获取下拉
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_SmallShops_Info_Extend> GetSmallShopsDropDownList(int pageIndex, int pageSize, out long count, RB_SmallShops_Info_Extend demodel)
        {
            return smallShops_InfoRepository.GetSmallShopsDropDownList(pageIndex, pageSize, out count, demodel);
        }

        /// <summary>
        /// 获取微店信息
        /// </summary>
        /// <param name="smallShopsId"></param>
        /// <returns></returns>
        public RB_SmallShops_Info_Extend GetSmallShopsInfo(int smallShopsId)
        {
            var model = smallShops_InfoRepository.GetEntity<RB_SmallShops_Info_Extend>(smallShopsId);
            model.NickName = member_UserRepository.GetEntity(model?.UserId ?? 0)?.Name ?? "";
            return model;
        }
        /// <summary>
        /// 根据用户id  获取微店信息
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public RB_SmallShops_Info_Extend GetSmallShopsInfo_V2(int UserId, int tenantId, int mallBaseId)
        {
            var model = smallShops_InfoRepository.GetListForSingle(new RB_SmallShops_Info_Extend() { UserId = UserId, TenantId = tenantId, MallBaseId = mallBaseId }).FirstOrDefault();
            return model;
        }


        /// <summary>
        /// 根据用户id  获取微店信息
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public List<RB_SmallShops_Info_Extend> GetSmallShopsInfoList_V2(RB_SmallShops_Info_Extend model)
        {
            return smallShops_InfoRepository.GetListForSingle(model);
        }



        /// <summary>
        /// 微店审核
        /// </summary>
        /// <param name="ssmodel"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public bool SetSmallShopsAudit(RB_SmallShops_Info_Extend ssmodel, int type)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_SmallShops_Info.UpdateDate),DateTime.Now}
            };
            if (type == 1)
            {
                keyValues.Add(nameof(RB_SmallShops_Info.AuditStatus), DistributorAuditStatusEnum.Audited);
                keyValues.Add(nameof(RB_SmallShops_Info.AuditDate), DateTime.Now);
            }
            else if (type == 2)
            {
                keyValues.Add(nameof(RB_SmallShops_Info.AuditStatus), DistributorAuditStatusEnum.Reject);
            }
            else if (type == 3)
            {
                keyValues.Add(nameof(RB_SmallShops_Info.Remark), ssmodel.Remark);
            }
            else if (type == 4)
            {
                keyValues.Add(nameof(RB_SmallShops_Info.Status), 1);
            }
            else
            {
                return false;
            }

            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_SmallShops_Info.Id),
                      FiledValue=ssmodel.Id,
                       OperatorEnum=OperatorEnum.Equal
                }
            };

            return smallShops_InfoRepository.Update(keyValues, wheres);
        }

        /// <summary>
        /// 修改店铺佣金
        /// </summary>
        /// <param name="smallShopsId"></param>
        /// <param name="commission"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public bool SetSmallShopsCommission(int smallShopsId, decimal commission, int tenantId, int mallBaseId, int empId)
        {
            var model = smallShops_InfoRepository.GetEntity(smallShopsId);
            if (model == null) { return false; }
            if (model.AuditStatus != DistributorAuditStatusEnum.Audited) { return false; }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_SmallShops_Info.UpdateDate),DateTime.Now},
                { nameof(RB_SmallShops_Info.Commission),commission},
                { nameof(RB_SmallShops_Info.Remark),model.Remark +" EmpId:"+empId+"修改佣金：由"+(model.Commission??0)+"=>"+commission},
            };

            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_SmallShops_Info.Id),
                      FiledValue=smallShopsId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };

            return smallShops_InfoRepository.Update(keyValues, wheres);
        }

        /// <summary>
        /// 微店基础表
        /// </summary>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public Model.Entity.BaseSetUp.RB_MicroShop_Basics GetSmallShopsBaseInfo(int tenantId, int mallBaseId)
        {
            return microShop_BasicsRepository.GetMicroShopBasicsList(new Model.Entity.BaseSetUp.RB_MicroShop_Basics() { TenantId = tenantId, MallBaseId = mallBaseId }).FirstOrDefault();
        }

        #endregion

        #region 微店提现
        /// <summary>
        /// 获取提现余额
        /// </summary>
        /// <returns></returns>
        public object GetSmallShopsWithdrawDepositBalance(AppletUserInfo userInfo)
        {
            var basicsModel = microShop_BasicsRepository.GetMicroShopBasicsList(new Model.Entity.BaseSetUp.RB_MicroShop_Basics() { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();
            var disModel = smallShops_InfoRepository.GetList(new RB_SmallShops_Info_Extend() { UserId = userInfo.UserId, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();

            decimal CanRemitMoney = -1;
            if (basicsModel.MaxWithdrawal != -1)
            {
                //获取当日所有用户提现金额
                decimal RemitMoney = smallShops_RemitRepository.GetAllUserToDayRemitMoney(userInfo.TenantId, userInfo.MallBaseId);
                CanRemitMoney = (basicsModel.MaxWithdrawal ?? 0) - RemitMoney;
                CanRemitMoney = CanRemitMoney < 0 ? 0 : CanRemitMoney;
            }
            //提现方式
            List<int> WithdrawWayids = JsonConvert.DeserializeObject<List<int>>("[" + basicsModel.SettlementType + "]");
            var list = EnumHelper.GetEnumList(typeof(DistrbutorWithdrawWayEnum));
            var WayList = list.Where(x => WithdrawWayids.Contains(Convert.ToInt32(x.Value)));

            //获取订阅消息
            var miniModel = miniProgramRepository.GetListRepository(new RB_MiniProgram_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();

            List<string> template_message_list = new List<string>();

            if (miniModel != null)
            {
                if (!string.IsNullOrWhiteSpace(miniModel.ReflectSuccessTpl))
                {
                    template_message_list.Add(miniModel.ReflectSuccessTpl);
                }
                if (!string.IsNullOrWhiteSpace(miniModel.ReflectFailTpl))
                {
                    template_message_list.Add(miniModel.ReflectFailTpl);
                }
                if (!string.IsNullOrWhiteSpace(miniModel.AuditResultTpl))
                {
                    template_message_list.Add(miniModel.AuditResultTpl);
                }
            }

            return new
            {
                template_message_list,
                disModel.Commission,
                CanRemitMoney,
                basicsModel.MaxWithdrawal,
                basicsModel.WithdrawalFree,
                basicsModel.IsAllCommission,
                basicsModel.MinWithdrawal,
                IsWithdrawAll = 1,
                WithdrawWayList = WayList.Select(x => new
                {
                    Id = Convert.ToInt32(x.Value),
                    Name = x.Key
                })
            };
        }

        /// <summary>
        /// 提现
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public string SetSmallShopsWithdrawDeposit(RB_SmallShops_Remit_Extend demodel)
        {
            //验证金额
            var disModel = smallShops_InfoRepository.GetList(new RB_SmallShops_Info_Extend() { UserId = demodel.UserId, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
            if ((disModel.Commission ?? 0) < (demodel.AppliedMoney ?? 0))
            {
                return "微店余额不足，请刷新后再试";
            }
            var basicsModel = microShop_BasicsRepository.GetMicroShopBasicsList(new Model.Entity.BaseSetUp.RB_MicroShop_Basics() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
            //提现方式
            List<int> WithdrawWayids = JsonConvert.DeserializeObject<List<int>>("[" + basicsModel.SettlementType + "]");
            if (!WithdrawWayids.Contains((int)(demodel.WithdrawalWay ?? DistrbutorWithdrawWayEnum.ZDDK)))
            {
                return "提现方式不正确";
            }

            //if (basicsModel.IsWithdrawAll == 1)
            //{
            //    if ((disModel.CommissionWithdrawal ?? 0) != (demodel.AppliedMoney ?? 0))
            //    {
            //        return "提现必须全额提现";
            //    }
            //}
            if (basicsModel.MaxWithdrawal != -1)
            {
                //获取当日所有用户提现金额
                decimal RemitMoney = smallShops_RemitRepository.GetAllUserToDayRemitMoney(demodel.TenantId, demodel.MallBaseId);
                //今日可提
                decimal CanRemitMoney = (basicsModel.MaxWithdrawal ?? 0) - RemitMoney;
                CanRemitMoney = CanRemitMoney < 0 ? 0 : CanRemitMoney;

                if (CanRemitMoney < (demodel.AppliedMoney ?? 0))
                {
                    return "今日可提现余额不足";
                }
            }
            //验证手续费
            if (basicsModel.WithdrawalFree > 0)
            {
                decimal fee = Math.Round((demodel.AppliedMoney ?? 0) * (basicsModel.WithdrawalFree ?? 0) / 100, 2, MidpointRounding.AwayFromZero);
                if (demodel.Fee != fee)
                {
                    return "手续费计算不准确";
                }
                if (demodel.RemitMoney != (demodel.AppliedMoney ?? 0) - fee)
                {
                    return "最终金额不正确";
                }
            }
            else
            {
                demodel.Fee = 0;
                demodel.RemitMoney = demodel.AppliedMoney;
            }
            var trans = smallShops_RemitRepository.DbTransaction;
            try
            {
                int RemitId = smallShops_RemitRepository.Insert(demodel, trans);
                bool flag = RemitId > 0;
                if (flag)
                {
                    //扣除账户可提佣金
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_SmallShops_Info.Commission),(disModel.Commission ?? 0) - (demodel.AppliedMoney ?? 0)}
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName=nameof(RB_Distributor_Info.Id),
                              FiledValue=disModel.Id,
                               OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    smallShops_InfoRepository.Update(keyValues, wheres, trans);

                    #region 写入提现订单

                    if (demodel.TenantId == 1)
                    {
                        //所有未提现的 返佣
                        var clist = smallShopsCommissionRepository.GetUserCommissionRemit(demodel.UserId ?? 0);
                        if (clist.Any())
                        {
                            //获取订单列表
                            string OrderIds = string.Join(",", clist.Select(x => x.OrderId).Distinct());
                            var olist = goods_OrderRepository.GetOrderList(new RB_Goods_Order_Extend() { OrderIds = OrderIds });
                            olist = olist.OrderByDescending(x => x.CreateDate).ToList();
                            List<int> OrderIdList = new List<int>();
                            List<int> VipIdList = new List<int>();
                            string OrderNos = "";
                            decimal TMoney = (demodel.AppliedMoney ?? 0);

                            //开始递减金额   订单不足的  给与提示
                            foreach (var item in olist)
                            {
                                decimal CommMoney = 0;
                                var chlist = clist.Where(x => x.OrderId == item.OrderId).ToList();
                                foreach (var qitem in chlist)
                                {
                                    TMoney -= (qitem.Commission ?? 0);
                                    CommMoney += (qitem.Commission ?? 0);
                                    Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                        { nameof(RB_SmallShops_Commission_Extend.IsRemit),1}
                                    };
                                    List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                        new WhereHelper(){
                                                FiledName=nameof(RB_SmallShops_Commission_Extend.Id),
                                                FiledValue=qitem.Id,
                                                OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                                    smallShopsCommissionRepository.Update(keyValues2, wheres2, trans);
                                }
                                OrderNos += "\"" + item.OrderNo + "\"：" + CommMoney + "元，";
                                OrderIdList.Add(item.OrderId);
                            }
                            if (!string.IsNullOrEmpty(OrderNos))
                            {
                                OrderNos = OrderNos[0..^1];
                            }
                            if (TMoney > 0)
                            {
                                OrderNos += "  余额" + TMoney + "尚未找到相关订单";
                            }
                            else if (TMoney < 0)
                            {
                                OrderNos += "  多出" + (0 - TMoney) + "存在未匹配到正确的订单";
                            }

                            if (!string.IsNullOrEmpty(OrderNos))
                            {
                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                    { nameof(RB_SmallShops_Remit.ReOrderNos),OrderNos},
                                    { nameof(RB_SmallShops_Remit.ReOrderIds),JsonConvert.SerializeObject(OrderIdList)},
                                };
                                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                    new WhereHelper(){
                                         FiledName=nameof(RB_SmallShops_Remit.Id),
                                          FiledValue=RemitId,
                                           OperatorEnum=OperatorEnum.Equal
                                    }
                                };
                                smallShops_RemitRepository.Update(keyValues1, wheres1, trans);
                            }
                        }
                    }
                    #endregion
                }
                smallShops_RemitRepository.DBSession.Commit();
                return "";
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetSmallShopsWithdrawDeposit");
                smallShops_RemitRepository.DBSession.Rollback();
                return "出错了，请联系管理员";
            }
        }

        /// <summary>
        /// 获取提现明细
        /// </summary>
        /// <param name="RemitId"></param>
        /// <returns></returns>
        public RB_SmallShops_Remit_Extend GetSmallShopsRemitInfo(int RemitId)
        {
            return smallShops_RemitRepository.GetEntity<RB_SmallShops_Remit_Extend>(RemitId);
        }


        /// <summary>
        /// 微店提现审核
        /// </summary>
        /// <param name="remitId"></param>
        /// <param name="type"></param>
        /// <param name="remark"></param>
        /// <param name="uid"></param>
        /// <param name="mallBaseId"></param>
        /// <param name="erpEmpId"></param>
        /// <returns></returns>
        public string SetSmallShopsRemitAudit(int remitId, int type, string remark, string uid, int mallBaseId, int erpEmpId)
        {
            if (type == 1)
            {

                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_SmallShops_Remit.AuditStatus), (int)Common.Enum.User.DistributorRemitAuditStatusEnum.ToPlayWith},
                    { nameof(RB_SmallShops_Remit.AuditDate), DateTime.Now},
                    { nameof(RB_SmallShops_Remit.AuditRemark), remark},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                            FiledName=nameof(RB_SmallShops_Remit.Id),
                            FiledValue=remitId,
                            OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = smallShops_RemitRepository.Update(keyValues, wheres);
                if (flag && uid == "1")
                {
                    //提现审核通过  自动生成财务单据
                    OrderIncomeFinanceModule(remitId, Convert.ToInt32(uid), mallBaseId, remark, erpEmpId);
                }
            }
            else if (type == 2)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_SmallShops_Remit.AuditStatus), (int)Common.Enum.User.DistributorRemitAuditStatusEnum.HaveMoney},
                    { nameof(RB_SmallShops_Remit.RemitDate), DateTime.Now},
                    { nameof(RB_SmallShops_Remit.RemitRemark), remark},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                            FiledName=nameof(RB_SmallShops_Remit.Id),
                            FiledValue=remitId,
                            OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = smallShops_RemitRepository.Update(keyValues, wheres);
                if (flag)
                {
                    var remodel = smallShops_RemitRepository.GetEntity<RB_Distributor_Remit_Extend>(remitId);
                    if (remodel.WithdrawalWay == DistrbutorWithdrawWayEnum.YETX)
                    {
                        var umodel = member_UserRepository.GetEntity(remodel.UserId);
                        if (umodel != null)
                        {
                            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                { nameof(RB_Member_User.Balance),(umodel.Balance??0)+(remodel.RemitMoney??0)}
                            };
                            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName=nameof(RB_Member_User.Id),
                                      FiledValue=umodel.Id,
                                       OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            bool flag1 = member_UserRepository.Update(keyValues1, wheres1);
                            if (flag1)
                            {
                                //插入余额明细
                                member_BalanceRepository.Insert(new RB_Member_Balance()
                                {
                                    Id = 0,
                                    Balance = (remodel.RemitMoney ?? 0),
                                    CreateDate = DateTime.Now,
                                    Description = "",
                                    Image = 0,
                                    MallBaseId = umodel.MallBaseId,
                                    PlatformType = umodel.Source,
                                    Remarks = "微店佣金提现转入余额,RemitId:" + remodel.Id,
                                    TenantId = umodel.TenantId,
                                    Type = Common.Enum.MarketingCenter.RecordTypeEnum.Income,
                                    UserId = umodel.Id
                                });
                            }
                        }
                    }
                }
            }
            else if (type == 3)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_SmallShops_Remit.AuditStatus), (int)Common.Enum.User.DistributorRemitAuditStatusEnum.Reject},
                    { nameof(RB_SmallShops_Remit.RejectDate), DateTime.Now},
                    { nameof(RB_SmallShops_Remit.RejectRemark), remark},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                            FiledName=nameof(RB_SmallShops_Remit.Id),
                            FiledValue=remitId,
                            OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = smallShops_RemitRepository.Update(keyValues, wheres);
                if (flag)
                {
                    //拒绝之后  需回滚提现佣金
                    var remodel = smallShops_RemitRepository.GetEntity(remitId);
                    var dmodel = smallShops_InfoRepository.GetList(new RB_SmallShops_Info_Extend() { UserId = remodel.UserId, TenantId = Convert.ToInt32(uid), MallBaseId = mallBaseId }).FirstOrDefault();
                    if (dmodel != null)
                    {
                        #region 回滚提现金额
                        Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                            { nameof(RB_SmallShops_Info.Commission), (dmodel.Commission ?? 0) + (remodel.AppliedMoney??0)}
                        };
                        List<WhereHelper> wheres1 = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_SmallShops_Info.Id),
                                  FiledValue=dmodel.Id,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        smallShops_InfoRepository.Update(keyValues1, wheres1);
                        #endregion

                        #region 回滚佣金已提现字段
                        try
                        {
                            if (!string.IsNullOrEmpty(remodel.ReOrderNos) && !string.IsNullOrEmpty(remodel.ReOrderIds))
                            {
                                List<int> OrderIdList = JsonConvert.DeserializeObject<List<int>>(remodel.ReOrderIds);
                                if (OrderIdList.Any())
                                {
                                    var oclist = smallShopsCommissionRepository.GetUserCommissionRemitedList(remodel.UserId ?? 0, string.Join(",", OrderIdList));
                                    foreach (var qitem in oclist)
                                    {
                                        Dictionary<string, object> keyValues2 = new Dictionary<string, object>() {
                                            { nameof(RB_SmallShops_Commission_Extend.IsRemit),0}
                                        };
                                        List<WhereHelper> wheres2 = new List<WhereHelper>() {
                                            new WhereHelper(){
                                                 FiledName=nameof(RB_SmallShops_Commission_Extend.Id),
                                                  FiledValue=qitem.Id,
                                                   OperatorEnum=OperatorEnum.Equal
                                            }
                                        };
                                        smallShopsCommissionRepository.Update(keyValues2, wheres2);
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Write(ex, "SetSmallShopsRemitAudit回滚返佣字段失败");
                        }
                        #endregion
                    }

                }
            }
            else
            {
                return "type有误，请核实后再试";
            }
            return "";
        }

        /// <summary>
        /// 生成提现单据
        /// </summary>
        /// <returns></returns>
        public bool OrderIncomeFinanceModule(int remitId, int TenantId, int MallBaseId, string remark, int erpEmpId)
        {
            var flag = false;
            try
            {
                var remitModel = smallShops_RemitRepository.GetEntity(remitId);
                if (remitModel == null)
                {
                    return false;
                }
                decimal Money = (remitModel.AppliedMoney ?? 0) - (remitModel.Fee ?? 0);
                //查询用户
                var umodel = member_UserRepository.GetEntity(remitModel.UserId);
                if (umodel == null) { return false; }
                //查询分销商
                var DisModel = smallShops_InfoRepository.GetList(new RB_SmallShops_Info_Extend() { UserId = remitModel.UserId, TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();
                if (DisModel == null) { return false; }
                //先查询规则
                var financeConfigurineList = financeConfigurineRepository.GetList(new Model.Extend.Finance.RB_Finance_Configurine_Extend { Type = 4 });

                //根据规则中的小程序，查询订单详情信息
                string dstr = "";
                if (remitModel.Fee > 0)
                {
                    dstr = "申请:" + (remitModel.AppliedMoney ?? 0) + "金额，手续费:" + (remitModel.Fee ?? 0) + "，实际打款:" + Money;
                }
                if (financeConfigurineList != null && financeConfigurineList.Any())
                {
                    var item = financeConfigurineList.FirstOrDefault();
                    var detailList = new List<object>() {
                        new
                        {
                            CostTypeId = item.RemitCostTypeId,
                            Number = 1,
                            OriginalMoney = Money,
                            UnitPrice = Money,
                            Remark = "微店订单："+(remitModel?.ReOrderNos ?? "暂无")+"  " + dstr
                        }
                    };
                    item.IsPublic = 5;//默认平台虚拟账户

                    #region 查询所有的订单
                    List<Model.Entity.Finance.RB_ECFinanceId_Relation> ECList = new List<Model.Entity.Finance.RB_ECFinanceId_Relation>();
                    if (!string.IsNullOrEmpty(remitModel.ReOrderIds))
                    {
                        List<int> reorderIdList = JsonConvert.DeserializeObject<List<int>>(remitModel.ReOrderIds);
                        if (reorderIdList.Any())
                        {
                            reorderIdList = reorderIdList.Distinct().ToList();
                            var orderDetailList = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { TenantId = TenantId, MallBaseId = MallBaseId, OrderIds = string.Join(",", reorderIdList) });
                            foreach (var qitem in orderDetailList)
                            {
                                ECList.Add(new Model.Entity.Finance.RB_ECFinanceId_Relation()
                                {
                                    ECOrderId = qitem.OrderId,
                                    ECOrderDetailId = qitem.Id
                                });
                            }
                        }
                    }
                    #endregion
                    var financeObj = new
                    {
                        CreateBy = erpEmpId > 0 ? erpEmpId.ToString() : Config.ExpendDirector,
                        item.IsPublic,
                        ClientType = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("FinanceSetting")["RemitTypeId"]),
                        ClientID = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("FinanceSetting")["RemitAccountId"]),
                        item.CurrencyId,
                        WBMoney = Money,
                        PayDate = DateTime.Now.ToString("yyyy-MM-dd"),
                        RB_Branch_Id = Config.ExpendBranchId,
                        TemplateId = item.WorkFlowId,
                        OrderSource = 16,
                        OtherType = 19,
                        ReFinanceId = remitId,
                        Remark = "名称:" + umodel.Name + "（" + umodel.Id + "）" + "  微店:" + DisModel.Name + "   " + System.DateTime.Now.ToString("yyyy年MM月dd日") + "自动生成财务单据(微店提现)",
                        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), "");
                    var apir = JsonConvert.DeserializeObject<ApiResult>(apiResult);
                    if (apir.resultCode == 1)
                    {
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_SmallShops_Remit.FinanceId), Convert.ToInt32(apir.data.ToString())},
                            { nameof(RB_SmallShops_Remit.AuditRemark), remark+"  自动生成财务单据:"+apir.data.ToString()},
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                    FiledName=nameof(RB_SmallShops_Remit.Id),
                                    FiledValue=remitId,
                                    OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        smallShops_RemitRepository.Update(keyValues, wheres);
                    }
                    else
                    {
                        //记录自动生成失败，需手动新增财务单据
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_SmallShops_Remit.AuditRemark), remark+"  自动生成财务单据失败，请手动添加财务单据！"},
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                    FiledName=nameof(RB_SmallShops_Remit.Id),
                                    FiledValue=remitId,
                                    OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        smallShops_RemitRepository.Update(keyValues, wheres);
                    }
                }
            }
            catch (Exception ex)
            {

                LogHelper.Write(ex);
            }

            return flag;
        }

        /// <summary>
        /// 设置打款备注
        /// </summary>
        /// <param name="remitId"></param>
        /// <param name="remark"></param>        
        /// <returns></returns>
        public bool SetSmallShopsRemitRemark(int remitId, string remark)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_SmallShops_Remit.RemitRemark),remark},
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_SmallShops_Remit.Id),
                        FiledValue=remitId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            return smallShops_RemitRepository.Update(keyValues, wheres);
        }




        /// <summary>
        /// 分销提现列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_SmallShops_Remit_Extend> GetSmallShopsRemitList(RB_SmallShops_Remit_Extend demodel)
        {
            return smallShops_RemitRepository.GetSmallShopsRemitList(demodel);
        }
        #endregion

        #region 微店小程序

        /// <summary>
        /// 设置全局价格
        /// </summary>
        /// <param name="upPrice"></param>
        /// <param name="priceType"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetSmallShopsGlobalPrice(decimal upPrice, int priceType, RB_SmallShops_Info_Extend model)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_SmallShops_Info_Extend.UpPrice),upPrice},
                { nameof(RB_SmallShops_Info_Extend.PriceType),priceType},
                { nameof(RB_SmallShops_Info_Extend.UpdateDate),DateTime.Now},
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_SmallShops_Info_Extend.Id),
                      FiledValue=model.Id,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            return smallShops_InfoRepository.Update(keyValues, wheres);
        }

        /// <summary>
        /// 获取微店商品价格设置列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public object GetSmallShopsGoodsPricePageList(int pageIndex, int pageSize, out long count, RB_SmallShops_Price_Extend demodel)
        {
            var goodsList = smallShops_PriceRepository.GetSmallShopsGoodsPricePageList(pageIndex, pageSize, out count, demodel);
            List<object> RList = new List<object>();
            if (goodsList.Any())
            {
                //查询出所有商品id
                string goodsIds = string.Join(",", goodsList.Select(x => x.GoodsId ?? 0).Distinct());

                var glist = goodsRepository.GetSingleList(new RB_Goods_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                foreach (var item in glist)
                {
                    item.CoverImage = "";
                    if (!string.IsNullOrEmpty(item.CarouselImage) && item.CarouselImage != "[]")
                    {
                        List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(item.CarouselImage);
                        //封面图
                        item.CoverImage = CarouselIdList[0];
                    }
                }
                var splist = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                var slist = goods_SpecificationRepository.GetList(new RB_Goods_Specification_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                var svlist = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });

                var sslist = smallShops_PriceRepository.GetList(new RB_SmallShops_Price_Extend() { GoodsIds = goodsIds, SmallShopsId = demodel.SmallShopsId, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });

                foreach (var item in goodsList)
                {
                    var model = glist.Where(x => x.Id == item.GoodsId).FirstOrDefault();
                    if (model != null)
                    {
                        model.SpecificationList = new List<RB_Goods_Specification_Extend>();
                        model.SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
                        if (model.IsCustomSpecification == 1)
                        {
                            model.SpecificationList = slist.Where(x => x.GoodsId == model.Id).ToList();
                            if (model.SpecificationList.Any())
                            {
                                foreach (var qitem in model.SpecificationList)
                                {
                                    qitem.SpecificationValueList = svlist.Where(x => x.GoodsId == item.GoodsId && x.SpecificationId == qitem.Id).ToList();
                                }
                            }
                            model.SpecificationPriceList = splist.Where(x => x.GoodsId == item.GoodsId).ToList();
                        }

                        #region 组装价格
                        List<object> priceList = new List<object>();
                        if (model.IsCustomSpecification == 1)
                        {
                            if (model.SpecificationPriceList.Any() && model.SpecificationList.Any())
                            {
                                foreach (var qitem in model.SpecificationPriceList)
                                {
                                    var ssarr = qitem.SpecificationSort.Split(':');
                                    int Sort = Convert.ToInt32(ssarr[0]);
                                    List<object> attr_list = new List<object>();
                                    for (int i = 0; i < ssarr.Length; i++)
                                    {
                                        var smodel = model.SpecificationList[i];
                                        var svmodel = smodel.SpecificationValueList.Where(x => x.Sort == Convert.ToInt32(ssarr[i])).FirstOrDefault();

                                        attr_list.Add(new
                                        {
                                            attr_group_name = smodel.Name,
                                            attr_group_id = smodel.Sort,
                                            attr_id = svmodel.Id,
                                            attr_name = svmodel.Name
                                        });
                                    }
                                    //查找 设置的店铺价格
                                    var ssmodel = sslist.Where(x => x.GoodsId == item.GoodsId && x.SpecificationKey == qitem.SpecificationSort).FirstOrDefault();
                                    var ssPrice = qitem.SellingPrice ?? 0;
                                    if (ssmodel != null)
                                    {
                                        if (ssmodel.PriceType == 1)
                                        {
                                            ssPrice += Math.Ceiling(ssPrice * (ssmodel.UpPrice ?? 0) / 100);
                                        }
                                        else {
                                            ssPrice += (ssmodel.UpPrice ?? 0);
                                        }
                                    }
                                    priceList.Add(new
                                    {
                                        GoodsId = model.Id,
                                        SpecificationKey = qitem.SpecificationSort,
                                        qitem.SellingPrice,
                                        AttrList = attr_list,
                                        SmallShopsPrice = ssPrice,
                                        SmallShopsPriceId = ssmodel?.Id ?? 0,
                                        UpPrice = ssmodel?.UpPrice ?? 0,
                                        PriceType = ssmodel?.PriceType ?? 0,
                                    });
                                }
                            }
                            RList.Add(new
                            {
                                GoodsId = model.Id,
                                model.Name,
                                model.CoverImage,
                                SpecificationList = priceList
                            });
                        }
                        else
                        {
                            //查找 设置的店铺价格
                            var ssmodel = sslist.Where(x => x.GoodsId == item.GoodsId && x.SpecificationKey == "").FirstOrDefault();
                            var ssPrice = model.SellingPrice ?? 0;
                            if (ssmodel != null)
                            {
                                if (ssmodel.PriceType == 1)
                                {
                                    ssPrice += Math.Ceiling(ssPrice * (ssmodel.UpPrice ?? 0) / 100);
                                }
                                else {
                                    ssPrice += (ssmodel.UpPrice ?? 0);
                                }
                            }
                            priceList.Add(new
                            {
                                GoodsId = model.Id,
                                SpecificationKey = "",
                                model.SellingPrice,
                                AttrList = new List<object>(){ new
                                {
                                    attr_group_name = "规格",
                                    attr_group_id = 0,
                                    attr_id = 0,
                                    attr_name = model.DefaultSpecificationName
                                } },
                                SmallShopsPrice = ssPrice,
                                SmallShopsPriceId = ssmodel?.Id ?? 0,
                                UpPrice = ssmodel?.UpPrice ?? 0,
                                PriceType = ssmodel?.PriceType ?? 0,
                            });
                            RList.Add(new
                            {
                                GoodsId = model.Id,
                                model.Name,
                                model.CoverImage,
                                SpecificationList = priceList
                            });
                        }
                        #endregion
                    }
                }
            }

            return RList;
        }

        /// <summary>
        /// 获取商品分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public object GetSmallShopsChooseGoodsPageList(int pageIndex, int pageSize, out long count, RB_SmallShops_Price_Extend demodel)
        {
            List<object> RList = new List<object>();
            var glist = goodsRepository.GetPageList(pageIndex, pageSize, out count, new RB_Goods_Extend() { Id = demodel.GoodsId ?? 0, Name = demodel.GoodsName, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
            if (glist.Any())
            {
                //查询出所有商品id
                string goodsIds = string.Join(",", glist.Select(x => x.Id).Distinct());
                foreach (var item in glist)
                {
                    item.CoverImage = "";
                    if (!string.IsNullOrEmpty(item.CarouselImage) && item.CarouselImage != "[]")
                    {
                        List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(item.CarouselImage);
                        //封面图
                        item.CoverImage = CarouselIdList[0];
                    }
                }
                var splist = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                var slist = goods_SpecificationRepository.GetList(new RB_Goods_Specification_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                var svlist = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsIds = goodsIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                foreach (var model in glist)
                {
                    if (model != null)
                    {
                        model.SpecificationList = new List<RB_Goods_Specification_Extend>();
                        model.SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
                        if (model.IsCustomSpecification == 1)
                        {
                            model.SpecificationList = slist.Where(x => x.GoodsId == model.Id).ToList();
                            if (model.SpecificationList.Any())
                            {
                                foreach (var qitem in model.SpecificationList)
                                {
                                    qitem.SpecificationValueList = svlist.Where(x => x.GoodsId == model.Id && x.SpecificationId == qitem.Id).ToList();
                                }
                            }
                            model.SpecificationPriceList = splist.Where(x => x.GoodsId == model.Id).ToList();
                        }

                        #region 组装价格
                        List<object> priceList = new List<object>();
                        if (model.IsCustomSpecification == 1)
                        {
                            if (model.SpecificationPriceList.Any() && model.SpecificationList.Any())
                            {
                                foreach (var qitem in model.SpecificationPriceList)
                                {
                                    var ssarr = qitem.SpecificationSort.Split(':');
                                    int Sort = Convert.ToInt32(ssarr[0]);
                                    List<object> attr_list = new List<object>();
                                    for (int i = 0; i < ssarr.Length; i++)
                                    {
                                        var smodel = model.SpecificationList[i];
                                        var svmodel = smodel.SpecificationValueList.Where(x => x.Sort == Convert.ToInt32(ssarr[i])).FirstOrDefault();

                                        attr_list.Add(new
                                        {
                                            attr_group_name = smodel.Name,
                                            attr_group_id = smodel.Sort,
                                            attr_id = svmodel.Id,
                                            attr_name = svmodel.Name
                                        });
                                    }
                                    priceList.Add(new
                                    {
                                        GoodsId = model.Id,
                                        SpecificationKey = qitem.SpecificationSort,
                                        qitem.SellingPrice,
                                        AttrList = attr_list,
                                    });
                                }
                            }
                            RList.Add(new
                            {
                                GoodsId = model.Id,
                                model.Name,
                                model.CoverImage,
                                SpecificationList = priceList
                            });
                        }
                        else
                        {
                            priceList.Add(new
                            {
                                GoodsId = model.Id,
                                SpecificationKey = "",
                                model.SellingPrice,
                                AttrList = new List<object>(){ new
                                {
                                    attr_group_name = "规格",
                                    attr_group_id = 0,
                                    attr_id = 0,
                                    attr_name = model.DefaultSpecificationName
                                } }
                            });
                            RList.Add(new
                            {
                                GoodsId = model.Id,
                                model.Name,
                                model.CoverImage,
                                SpecificationList = priceList
                            });
                        }
                        #endregion
                    }
                }
            }

            return RList;
        }

        /// <summary>
        /// 保存微店商品价格
        /// </summary>
        /// <param name="goodsId"></param>
        /// <param name="sSPList"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public bool SetSmallShopsGoodsPrice(int goodsId, List<RB_SmallShops_Price_Extend> sSPList, AppletUserInfo userInfo)
        {
            var model = smallShops_InfoRepository.GetListForSingle(new RB_SmallShops_Info_Extend() { UserId = userInfo.UserId, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();
            if (model == null || model.AuditStatus != DistributorAuditStatusEnum.Audited)
            {
                return false;
            }
            var splist = smallShops_PriceRepository.GetList(new RB_SmallShops_Price_Extend() { SmallShopsId = model.Id, GoodsId = goodsId, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });
            if (splist.Any())
            {
                //修改
                var insertList = sSPList.Where(x => !splist.Select(y => y.SpecificationKey).Contains(x.SpecificationKey)).ToList();
                var updateList = splist.Where(x => sSPList.Select(y => y.SpecificationKey).Contains(x.SpecificationKey)).ToList();
                var deleteList = splist.Where(x => !sSPList.Select(y => y.SpecificationKey).Contains(x.SpecificationKey)).ToList();
                foreach (var item in insertList)
                {
                    if (item.UpPrice > 0)
                    {
                        item.SmallShopsId = model.Id;
                        item.GoodsId = goodsId;
                        item.UpPrice ??= 0;
                        item.PriceType ??= 0;
                        item.Status = 0;
                        item.TenantId = userInfo.TenantId;
                        item.MallBaseId = userInfo.MallBaseId;
                        item.CreateDate = DateTime.Now;
                        item.UpdateDate = DateTime.Now;
                        smallShops_PriceRepository.Insert(item);
                    }
                }
                foreach (var item in updateList)
                {
                    var sspmodel = sSPList.Where(x => x.SpecificationKey == item.SpecificationKey).FirstOrDefault();
                    if (sspmodel.UpPrice > 0)
                    {
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_SmallShops_Price.UpPrice),sspmodel.UpPrice},
                            { nameof(RB_SmallShops_Price.PriceType),sspmodel.PriceType},
                            { nameof(RB_SmallShops_Price.UpdateDate),DateTime.Now}
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_SmallShops_Price.Id),
                                  FiledValue=item.Id,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        smallShops_PriceRepository.Update(keyValues, wheres);
                    }
                    else
                    {
                        smallShops_PriceRepository.Delete(item);
                    }
                }
                foreach (var item in deleteList)
                {
                    smallShops_PriceRepository.Delete(item);
                }
            }
            else
            {
                foreach (var item in sSPList)
                {
                    if (item.UpPrice > 0)
                    {
                        item.SmallShopsId = model.Id;
                        item.GoodsId = goodsId;
                        item.UpPrice ??= 0;
                        item.PriceType ??= 0;
                        item.Status = 0;
                        item.TenantId = userInfo.TenantId;
                        item.MallBaseId = userInfo.MallBaseId;
                        item.CreateDate = DateTime.Now;
                        item.UpdateDate = DateTime.Now;
                        smallShops_PriceRepository.Insert(item);
                    }
                }
            }
            return true;
        }

        #endregion

        #region 微店自定义

        /// <summary>
        /// 微信自定义列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_SmallShops_Custom> GetSmallShopsCustomList(RB_SmallShops_Custom query)
        {
            return smallShopsCustomRepository.GetSmallShopsCustomList(query);
        }


        /// <summary>
        /// 设置分销自定义
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetSmallShopsCustomInfo(RB_SmallShops_Custom demodel)
        {
            var OModel = smallShopsCustomRepository.GetSmallShopsCustomList(new RB_SmallShops_Custom() { TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
            if (OModel != null)
            {

                Dictionary<string, object> keyValuePairs = new Dictionary<string, object>() {
                    { nameof(RB_SmallShops_Custom.HeadBackImage),demodel.HeadBackImage},
                    { nameof(RB_SmallShops_Custom.WithdrawalFilletPX),demodel.WithdrawalFilletPX},
                    { nameof(RB_SmallShops_Custom.WithdrawalText),demodel.WithdrawalText},
                    { nameof(RB_SmallShops_Custom.WithdrawalColor),demodel.WithdrawalColor},
                    { nameof(RB_SmallShops_Custom.WithdrawalTextColor),demodel.WithdrawalTextColor},
                    { nameof(RB_SmallShops_Custom.WithdrawalImage),demodel.WithdrawalImage},
                    { nameof(RB_SmallShops_Custom.SmallShopOrderName),demodel.SmallShopOrderName},
                    { nameof(RB_SmallShops_Custom.SmallShopOrderImage),demodel.SmallShopOrderImage},
                    { nameof(RB_SmallShops_Custom.WithdrawalDetailName),demodel.WithdrawalDetailName},
                    { nameof(RB_SmallShops_Custom.WithdrawalDetailImage),demodel.WithdrawalDetailImage},
                    { nameof(RB_SmallShops_Custom.MyCustomerName),demodel.MyCustomerName},
                    { nameof(RB_SmallShops_Custom.MyCustomerImage),demodel.MyCustomerImage},
                    { nameof(RB_SmallShops_Custom.SmallShopQRCodeName),demodel.SmallShopQRCodeName},
                    { nameof(RB_SmallShops_Custom.SmallShopQRCodeImage),demodel.SmallShopQRCodeImage},
                    { nameof(RB_SmallShops_Custom.SmallShopSetUpName),demodel.SmallShopSetUpName},
                    { nameof(RB_SmallShops_Custom.SmallShopSetUpImage),demodel.SmallShopSetUpImage},
                    { nameof(RB_SmallShops_Custom.LiveName),demodel.LiveName},
                    { nameof(RB_SmallShops_Custom.LiveImage),demodel.LiveImage},
                    { nameof(RB_SmallShops_Custom.CommissionWithdrawnName),demodel.CommissionWithdrawnName},
                    { nameof(RB_SmallShops_Custom.OutstandingCommissionName),demodel.OutstandingCommissionName},
                    { nameof(RB_SmallShops_Custom.WithdrawableName),demodel.WithdrawableName},
                    { nameof(RB_SmallShops_Custom.CommissionTobePaidName),demodel.CommissionTobePaidName},
                    { nameof(RB_SmallShops_Custom.UserNotesName),demodel.UserNotesName},
                    { nameof(RB_SmallShops_Custom.UserNotes),demodel.UserNotes},
                    { nameof(RB_SmallShops_Custom.IWantToWithdrawName),demodel.IWantToWithdrawName},
                    { nameof(RB_SmallShops_Custom.WithdrawalAmountName),demodel.WithdrawalAmountName},
                    { nameof(RB_SmallShops_Custom.WithdrawalWayName),demodel.WithdrawalWayName}
            };
                List<WhereHelper> whereHelpers = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_SmallShops_Custom.Id),
                          FiledValue=OModel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    },
                    new WhereHelper(){
                         FiledName=nameof(RB_SmallShops_Custom.TenantId),
                          FiledValue=OModel.TenantId,
                           OperatorEnum=OperatorEnum.Equal
                    },
                    new WhereHelper(){
                         FiledName=nameof(RB_SmallShops_Custom.MallBaseId),
                          FiledValue=OModel.MallBaseId,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                return smallShopsCustomRepository.Update(keyValuePairs, whereHelpers);
            }
            else
            {
                return smallShopsCustomRepository.Insert(demodel) > 0;
            }
        }

        #endregion

        #region 微店订单
        /// <summary>
        /// 获取用户返佣
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_SmallShops_Commission_Extend> GetSmallShopsCommissionPageList(int pageIndex, int pageSize, out long count, RB_SmallShops_Commission_Extend dmodel)
        {
            var oclist = smallShopsCommissionRepository.GetSmallShopsCommissionPageList(pageIndex, pageSize, out count, dmodel);
            if (oclist.Any())
            {
                //获取用户
                var ulist = member_UserRepository.GetList(new RB_Member_User_Extend() { TenantId = dmodel.TenantId, MallBaseId = dmodel.MallBaseId, UserIds = string.Join(",", oclist.Select(x => x.UserId).Distinct()) });

                string orderIds = string.Join(",", oclist.Select(x => x.OrderId).Distinct());
                //查询订单明细
                var dlist = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { TenantId = dmodel.TenantId, MallBaseId = dmodel.MallBaseId, OrderIds = orderIds });
                //查询图片
                List<RB_Material_Info_Extend> Mlist = new List<RB_Material_Info_Extend>();
                if (dlist.Any())
                {
                    foreach (var item in dlist)
                    {
                        item.CoverImagePath = item.CoverImage;
                    }
                }
                foreach (var item in oclist)
                {
                    var umodel = ulist.Where(x => x.Id == item.UserId).FirstOrDefault();
                    item.UserName = umodel?.Name ?? "";
                    item.Mobile = umodel?.Moblie ?? "";
                    item.Photo = umodel?.Photo ?? "";
                    item.OrderDetailList = new List<RB_Goods_OrderDetail_Extend>();
                    if (!string.IsNullOrWhiteSpace(item.OrderDetailIds))
                    {
                        var orderDetailIds = item.OrderDetailIds.Split(",");
                        foreach (var itemOrderDetailId in orderDetailIds)
                        {
                            if (!string.IsNullOrWhiteSpace(itemOrderDetailId))
                            {
                                item.OrderDetailList.AddRange(dlist.Where(x => x.OrderId == item.OrderId && x.Id == Convert.ToInt32(itemOrderDetailId)));
                            }
                        }
                    }
                    // item.OrderDetailList = dlist.Where(x => x.OrderId == item.OrderId).ToList();
                }
            }

            return oclist;
            // return smallShopsCommissionRepository.GetSmallShopsCommissionPageList(pageIndex, pageSize, out count, dmodel);
        }
        #endregion

        #region 微店提现

        /// <summary>
        /// 获取分销提现分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_SmallShops_Remit_Extend> GetSmallShopsRemitPageList(int pageIndex, int pageSize, out long count, RB_SmallShops_Remit_Extend demodel)
        {
            return smallShopsRemitRepository.GetPageList(pageIndex, pageSize, out count, demodel);
        }

        #endregion
    }
}
