using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Mall.Common;
using Mall.Common.API;
using Mall.Common.Enum.Finance;
using Mall.Common.Enum.Property;
using Mall.Common.Plugin;
using Mall.Model.Entity.Product;
using Mall.Model.Entity.Property;
using Mall.Model.Entity.User;
using Mall.Model.Extend.Finance;
using Mall.Model.Extend.Product;
using Mall.Model.Extend.Property;
using Mall.Model.Extend.User;
using Mall.Model.Query;
using Mall.Repository;
using Mall.Repository.BaseSetUp;
using Mall.Repository.Finance;
using Mall.Repository.Product;
using Mall.Repository.Property;
using Mall.Repository.User;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Newtonsoft.Json;
using VT.FW.DB;

namespace Mall.Module.Property
{
    /// <summary>
    /// 商品处理层
    /// </summary>
    public class PropertyModule
    {

        /// <summary>
        /// 商品分类
        /// </summary>
        private readonly RB_Product_CategoryRepository product_CategoryRepository = new RB_Product_CategoryRepository();
        /// <summary>
        /// 商品
        /// </summary>
        private readonly RB_GoodsRepository goodsRepository = new RB_GoodsRepository();
        /// <summary>
        /// 供应商
        /// </summary>
        private readonly RB_SupplierRepository supplierRepository = new RB_SupplierRepository();
        /// <summary>
        /// 商品分类
        /// </summary>
        private readonly RB_Goods_CategoryRepository goods_CategoryRepository = new RB_Goods_CategoryRepository();
        /// <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_Goods_SpecificationPriceRepository goods_SpecificationPriceRepository = new RB_Goods_SpecificationPriceRepository();
        /// <summary>
        /// 物料档案
        /// </summary>
        private readonly RB_Supplies_MaterialRepository supplies_MaterialRepository = new RB_Supplies_MaterialRepository();
        /// <summary>
        /// 物料库存
        /// </summary>
        private readonly RB_Supplies_InventoryRepository supplies_InventoryRepository = new RB_Supplies_InventoryRepository();
        /// <summary>
        /// 库存明细
        /// </summary>
        private readonly RB_Supplies_InventoryDetailRepository supplies_InventoryDetailRepository = new RB_Supplies_InventoryDetailRepository();
        /// <summary>
        /// 日志
        /// </summary>
        private readonly RB_Property_LogRepository property_LogRepository = new RB_Property_LogRepository();
        /// <summary>
        /// 采购单
        /// </summary>
        private readonly RB_ProcurementRepository procurementRepository = new RB_ProcurementRepository();
        /// <summary>
        /// 采购单明细
        /// </summary>
        private readonly RB_Procurement_DetailRepository procurement_DetailRepository = new RB_Procurement_DetailRepository();
        /// <summary>
        /// 员工
        /// </summary>
        private readonly RB_EmployeeRepository employeeRepository = new RB_EmployeeRepository();
        /// <summary>
        /// 仓库
        /// </summary>
        private readonly RB_Supplies_WareHouseRepository supplies_WareHouseRepository = new RB_Supplies_WareHouseRepository();
        /// <summary>
        /// 入库
        /// </summary>
        private readonly RB_Supplies_StockInRepository supplies_StockInRepository = new RB_Supplies_StockInRepository();
        /// <summary>
        /// 入库明细
        /// </summary>
        private readonly RB_Supplies_StockInDetailRepository supplies_StockInDetailRepository = new RB_Supplies_StockInDetailRepository();
        /// <summary>
        /// erp用户列表
        /// </summary>
        private readonly Rb_employeeRepository erpemployeeRepository = new Rb_employeeRepository();

        /// <summary>
        /// 盘点单
        /// </summary>
        private readonly RB_Supplies_CheckRepository supplies_CheckRepository = new RB_Supplies_CheckRepository();
        /// <summary>
        /// 盘点明细
        /// </summary>
        private readonly RB_Supplies_CheckDetailRepository supplies_CheckDetailRepository = new RB_Supplies_CheckDetailRepository();
        /// <summary>
        /// 资产流程
        /// </summary>
        private readonly RB_Property_AuditRelevanceRepository auditRelevanceRepository = new RB_Property_AuditRelevanceRepository();
        /// <summary>
        /// 财务流程
        /// </summary>
        private readonly Rb_Workflow_TemplateRepository workflow_TemplateRepository = new Rb_Workflow_TemplateRepository();
        /// <summary>
        /// 财务流程配置
        /// </summary>
        private readonly RB_FinanceFlowConnectRepository financeFlowConnectRepository = new RB_FinanceFlowConnectRepository();


        #region 获取采购单

        /// <summary>
        /// 获取采购单分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="demodel"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public List<RB_Procurement_Extend> GetProcurementPageList(int pageIndex, int pageSize, RB_Procurement_Extend demodel, out long count)
        {
            var list = procurementRepository.GetPageList(pageIndex, pageSize, demodel, out count);
            if (list.Any())
            {
                string procurementIds = string.Join(",", list.Select(x => x.Id));
                //查询明细
                var pdList = procurement_DetailRepository.GetList(new RB_Procurement_Detail_Extend() { RB_Group_Id = demodel.RB_Group_Id, ProcurementIds = procurementIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                //查询物料
                if (pdList.Any())
                {
                    string MaterialIds = string.Join(",", pdList.Select(x => x.MaterialId).Distinct());
                    var mList = supplies_MaterialRepository.GetList(new RB_Supplies_Material_Extend() { RB_Group_Id = demodel.RB_Group_Id, SuppliesIdStr = MaterialIds, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                    foreach (var item in pdList)
                    {
                        item.MaterialModel = mList.Where(x => x.Id == item.MaterialId).FirstOrDefault();
                        if (item.MaterialModel != null)
                        {
                            item.MaterialModel.GoodsSpecificationList = new List<string>();
                            item.MaterialModel.GoodsCategoryList = new List<string>();
                            if (!string.IsNullOrEmpty(item.MaterialModel.SpecificationName))
                            {
                                item.MaterialModel.GoodsSpecificationList = JsonConvert.DeserializeObject<List<string>>(item.MaterialModel.SpecificationName);
                            }
                            if (!string.IsNullOrEmpty(item.MaterialModel.GoodsCategoryName))
                            {
                                item.MaterialModel.GoodsCategoryList = JsonConvert.DeserializeObject<List<string>>(item.MaterialModel.GoodsCategoryName);
                            }
                            if (item.MaterialModel.Images == "" || item.MaterialModel.Images == null)
                            {
                                item.MaterialModel.Images = "[]";
                            }
                            item.MaterialModel.ImageList = JsonConvert.DeserializeObject<List<string>>(item.MaterialModel.Images);
                        }
                        else
                        {
                            item.MaterialModel = new RB_Supplies_Material_Extend();
                        }
                    }
                }
                //var elist = employeeRepository.GetEmployeeListRepository(new Model.Entity.User.RB_Employee_Extend() { EmployeeIds = string.Join(",", list.Select(x => x.CreateBy ?? 0).Distinct()) });
                var wlist = supplies_WareHouseRepository.GetList(new RB_Supplies_WareHouse_Extend() { RB_Group_Id = demodel.RB_Group_Id, WareHouseIdStr = string.Join(",", list.Select(x => x.WareHouseId ?? 0).Distinct()) });
                foreach (var item in list)
                {
                    item.DetailList = pdList.Where(x => x.ProcurementId == item.Id).ToList();
                    //item.CreateByName = elist.Where(x => x.EmpId == item.CreateBy).FirstOrDefault()?.EmpName ?? "";
                    item.WareHouseName = wlist.Where(x => x.Id == item.WareHouseId).FirstOrDefault()?.Name ?? "";
                }
            }
            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_Goods_Extend> GetGoodsToProcurementPageList(int pageIndex, int pageSize, out long count, RB_Goods_Extend demodel)
        {
            var GoodsList = goodsRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (GoodsList.Any())
            {
                int tenantId = demodel.TenantId;
                int mallBaseId = demodel.MallBaseId;
                var SpecificationList = new List<RB_Goods_Specification_Extend>();
                var SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
                //查询出商品规格
                if (GoodsList.Where(x => x.IsCustomSpecification == 1).Any())
                {
                    string goodsIds = string.Join(",", GoodsList.Where(x => x.IsCustomSpecification == 1).Select(x => x.Id));
                    SpecificationList = goods_SpecificationRepository.GetList(new RB_Goods_Specification_Extend() { GoodsIds = goodsIds, TenantId = tenantId, MallBaseId = mallBaseId });
                    if (SpecificationList.Any())
                    {
                        var svlist = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsIds = goodsIds, TenantId = tenantId, MallBaseId = mallBaseId });
                        foreach (var item in svlist)
                        {
                            item.ImagePath = item.Image;
                        }
                        foreach (var item in SpecificationList)
                        {
                            item.SpecificationValueList = svlist.Where(x => x.SpecificationId == item.Id).ToList();
                        }
                    }
                    SpecificationPriceList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsIds = goodsIds, TenantId = tenantId, MallBaseId = mallBaseId });
                    foreach (var item in SpecificationPriceList)
                    {
                        if (!string.IsNullOrEmpty(item.SpecificationSort))
                        {
                            var SpList = SpecificationList.Where(x => x.GoodsId == item.GoodsId).ToList();
                            var ssarr = item.SpecificationSort.Split(':');
                            int Sort = Convert.ToInt32(ssarr[0]);
                            List<string> AttrList = new List<string>();
                            for (int i = 0; i < ssarr.Length; i++)
                            {
                                var smodel = SpList[i];
                                var svmodel = smodel.SpecificationValueList.Where(x => x.Sort == Convert.ToInt32(ssarr[i])).FirstOrDefault();
                                AttrList.Add(smodel.Name + "：" + svmodel.Name);
                            }
                            item.AttrList = AttrList;
                        }
                    }
                }

                //查询分类
                string ids = string.Join(",", GoodsList.Select(x => x.Id));
                var clist = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsIds = ids, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId });
                foreach (var item in GoodsList)
                {
                    item.CategoryList = clist.Where(x => x.GoodsId == item.Id).ToList();
                    //轮播图
                    item.CoverImage = "";
                    if (!string.IsNullOrEmpty(item.CarouselImage) && item.CarouselImage != "[]")
                    {
                        List<string> CarouselIdList = JsonConvert.DeserializeObject<List<string>>(item.CarouselImage);
                        //封面图
                        item.CoverImage = CarouselIdList[0];
                    }
                    if (item.IsCustomSpecification == 1)
                    {
                        item.SpecificationPriceList = SpecificationPriceList.Where(x => x.GoodsId == item.Id).ToList();
                    }
                    else
                    {
                        item.SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
                        item.SpecificationPriceList.Add(new RB_Goods_SpecificationPrice_Extend()
                        {
                            Id = item.GoodsId ?? 0,
                            GoodsId = item.GoodsId,
                            GoodsNumbers = item.GoodsNumbers,
                            GoodsWeight = item.GoodsWeight,
                            InventoryNum = item.InventoryNum,
                            SpecificationSort = "",
                            AttrList = new List<string>() { "规格：" + item.DefaultSpecificationName }
                        });
                    }
                }
            }
            return GoodsList;
        }

        /// <summary>
        /// 获取采购单详情
        /// </summary>
        /// <param name="procurementId"></param>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <returns></returns>
        public RB_Procurement_Extend GetProcurementInfo(int procurementId, int TenantId, int MallBaseId, int ERPGroupId)
        {
            var pmodel = procurementRepository.GetEntity<RB_Procurement_Extend>(procurementId);
            //查询明细
            var pdList = procurement_DetailRepository.GetList(new RB_Procurement_Detail_Extend() { RB_Group_Id = ERPGroupId, ProcurementId = procurementId, TenantId = TenantId, MallBaseId = MallBaseId });
            //查询物料
            if (pdList.Any())
            {
                string MaterialIds = string.Join(",", pdList.Select(x => x.MaterialId).Distinct());
                var mList = supplies_MaterialRepository.GetList(new RB_Supplies_Material_Extend() { RB_Group_Id = ERPGroupId, SuppliesIdStr = MaterialIds, TenantId = TenantId, MallBaseId = MallBaseId });
                foreach (var item in pdList)
                {
                    item.MaterialModel = mList.Where(x => x.Id == item.MaterialId).FirstOrDefault();
                    if (item.MaterialModel != null)
                    {
                        item.MaterialModel.GoodsSpecificationList = new List<string>();
                        item.MaterialModel.GoodsCategoryList = new List<string>();
                        if (!string.IsNullOrEmpty(item.MaterialModel.SpecificationName))
                        {
                            item.MaterialModel.GoodsSpecificationList = JsonConvert.DeserializeObject<List<string>>(item.MaterialModel.SpecificationName);
                        }
                        if (!string.IsNullOrEmpty(item.MaterialModel.GoodsCategoryName))
                        {
                            item.MaterialModel.GoodsCategoryList = JsonConvert.DeserializeObject<List<string>>(item.MaterialModel.GoodsCategoryName);
                        }
                        if (item.MaterialModel.Images == "" || item.MaterialModel.Images == null)
                        {
                            item.MaterialModel.Images = "[]";
                        }
                        item.MaterialModel.ImageList = JsonConvert.DeserializeObject<List<string>>(item.MaterialModel.Images);
                    }
                    else
                    {
                        item.MaterialModel = new RB_Supplies_Material_Extend();
                    }
                }
            }
            var wlist = supplies_WareHouseRepository.GetList(new RB_Supplies_WareHouse_Extend() { RB_Group_Id = ERPGroupId, WareHouseIdStr = (pmodel.WareHouseId ?? 0).ToString() });

            pmodel.DetailList = pdList;
            pmodel.WareHouseName = wlist.FirstOrDefault()?.Name ?? "";

            return pmodel;
        }

        /// <summary>
        /// 提交采购单
        /// </summary>
        /// <param name="demodel"></param>
        /// <param name="eRPEmpId"></param>
        /// <param name="eRPBranchId"></param>
        /// <param name="eRPGroupId"></param>
        /// <param name="empId"></param>
        /// <returns></returns>
        public string SetProcurementInfo(RB_Procurement_Extend demodel, int eRPEmpId, int eRPBranchId, int eRPGroupId, int tenantId, int mallBaseId, int empId)
        {
            var sModel = supplierRepository.GetEntity(demodel.SupplierId ?? 0);
            if (sModel == null) { return "供应商不存在"; }
            if (sModel.BankAccountId <= 0) { return "供应商未绑定账户信息"; }
            //核实提交的商品物料里是否存在
            string GoodsIds = string.Join(",", demodel.DetailList.Select(x => x.GoodsId).Distinct());
            var mList = supplies_MaterialRepository.GetList(new RB_Supplies_Material_Extend() { RB_Group_Id = eRPGroupId, GoodsIds = GoodsIds, TenantId = tenantId, MallBaseId = mallBaseId });
            foreach (var item in demodel.DetailList)
            {
                var mModel = mList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationKey == item.SpecificationKey).FirstOrDefault();
                if (mModel == null)
                {
                    return "商品未找到对应的资产物料档案，商品ID：" + item.GoodsId;
                }
                item.MaterialId = mModel.Id;
                item.GoodsRemark = mModel.Name + "(" + item.GoodsId + ")" + "  ";
                if (!string.IsNullOrEmpty(mModel.SpecificationName))
                {
                    var sList = JsonConvert.DeserializeObject<List<string>>(mModel.SpecificationName);
                    item.GoodsRemark += string.Join(",", sList);
                }
            }
            demodel.TotalCostMoney = demodel.DetailList.Sum(x => (x.CostMoney ?? 0) * (x.Number ?? 0));
            demodel.TotalNumber = demodel.DetailList.Sum(x => x.Number ?? 0);
            demodel.Status = 0;
            demodel.RB_Branch_Id = eRPBranchId;
            demodel.RB_Group_Id = eRPGroupId;
            demodel.CreateBy = eRPEmpId;
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateBy = eRPEmpId;
            demodel.UpdateDate = DateTime.Now;
            demodel.TenantId = tenantId;
            demodel.MallBaseId = mallBaseId;
            demodel.FinanceId = 0;
            demodel.SupplierName = sModel.Name ?? "";
            demodel.StockInStatus = 1;

            var trans = procurementRepository.DbTransaction;
            try
            {
                int pid = procurementRepository.Insert(demodel, trans);
                if (pid > 0)
                {
                    //插入明细
                    foreach (var item in demodel.DetailList)
                    {
                        procurement_DetailRepository.Insert(new Model.Entity.Property.RB_Procurement_Detail()
                        {
                            CostMoney = item.CostMoney,
                            CreateBy = eRPEmpId,
                            CreateDate = DateTime.Now,
                            Id = 0,
                            MallBaseId = mallBaseId,
                            MaterialId = item.MaterialId,
                            Number = item.Number,
                            ProcurementId = pid,
                            RB_Branch_Id = eRPBranchId,
                            RB_Group_Id = eRPGroupId,
                            Status = 0,
                            TenantId = tenantId,
                            StockInNum = 0
                        }, trans);
                    }
                    property_LogRepository.Insert(new Model.Entity.Property.RB_Property_Log()
                    {
                        Type = 3,
                        Content = "新增采购单",
                        CreateBy = empId,
                        CreateDate = DateTime.Now,
                        Id = 0,
                        MallBaseId = mallBaseId,
                        SourceId = pid,
                        TenantId = tenantId
                    });
                }
                procurementRepository.DBSession.Commit();
                if (pid > 0)
                {
                    //生成采购财务单
                    OrderProcurementFinanceModule(demodel, sModel.BankAccountId, pid, demodel.Remark, eRPEmpId);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetProcurementInfo");
                procurementRepository.DBSession.Rollback();
                return "出错啦，请联系管理员";
            }
            return "";
        }

        /// <summary>
        /// 生成采购单据
        /// </summary>
        /// <param name="omodel"></param>
        /// <returns></returns>
        public bool OrderProcurementFinanceModule(RB_Procurement_Extend demodel, int BankAccountId, int pid, string pRemark,int eRPEmpId)
        {
            var flag = false;
            try
            {
                int CostTypeId = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("FinanceSetting")["ProcurementCTId"]);
                int CurrencyId = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("FinanceSetting")["ProcurementCurrencyId"]);
                int ProcurementFWId = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("FinanceSetting")["ProcurementFWId"]);
                int ProcurementDirector = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("FinanceSetting")["ProcurementDirector"]);
                int ProcurementBranchId = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("FinanceSetting")["ProcurementBranchId"]);
                int ProcurementDepartment = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("FinanceSetting")["ProcurementDepartment"]);
                decimal TotalMoney = 0;
                var detailList = new List<object>();
                foreach (var item in demodel.DetailList)
                {
                    decimal Money = (item.CostMoney ?? 0) * (item.Number ?? 0);
                    TotalMoney += Money;
                    detailList.Add(
                        new
                        {
                            CostTypeId,
                            Number = (item.Number ?? 0),
                            OriginalMoney = Money,
                            UnitPrice = (item.CostMoney ?? 0),
                            Remark = item.GoodsRemark
                        }
                    );
                }
                string Remark = System.DateTime.Now.ToString("yyyy年MM月dd日") + " 自动生成采购单据";
                var financeObj = new
                {
                    CreateBy = eRPEmpId > 0 ? eRPEmpId : ProcurementDirector,
                    demodel.IsPublic,
                    ClientType = 10,
                    ClientID = BankAccountId,
                    CurrencyId,
                    WBMoney = TotalMoney,
                    PayDate = DateTime.Now.ToString("yyyy-MM-dd"),
                    RB_Branch_Id = ProcurementBranchId,
                    TemplateId = ProcurementFWId,
                    OrderSource = 16,
                    OtherType = 15,
                    ReFinanceId = pid,
                    Remark,
                    detailList,
                    RB_Depart_Id = ProcurementDepartment
                };
                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), "");
                LogHelper.Write(apiResult);
                var apir = JsonConvert.DeserializeObject<ApiResult>(apiResult);
                if (apir.resultCode == 1)
                {
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_Procurement_Extend.Remark), pRemark +"   自动生成采购单据："+ apir.data.ToString()},
                        { nameof(RB_Procurement_Extend.FinanceId), Convert.ToInt32(apir.data.ToString())}
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                            FiledName=nameof(RB_Procurement_Extend.Id),
                            FiledValue=pid,
                            OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    procurementRepository.Update(keyValues, wheres);
                }
                else
                {
                    //记录自动生成失败，需手动新增财务单据
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_Procurement_Extend.Remark), pRemark +"   财务单据新增失败，请手动增加"}
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                            FiledName=nameof(RB_Procurement_Extend.Id),
                            FiledValue=pid,
                            OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    procurementRepository.Update(keyValues, wheres);
                }

            }
            catch (Exception ex)
            {

                LogHelper.Write(ex);
            }

            return flag;
        }

        /// <summary>
        /// 采购单入库
        /// </summary>
        /// <param name="demodel"></param>
        /// <param name="eRPEmpId"></param>
        /// <param name="eRPBranchId"></param>
        /// <param name="eRPGroupId"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <param name="empId"></param>
        /// <returns></returns>
        public string SetProcurementStockIn(RB_Procurement_Extend demodel, int eRPEmpId, int eRPBranchId, int eRPGroupId, int tenantId, int mallBaseId, int empId)
        {
            var pModel = procurementRepository.GetEntity(demodel.Id);
            if (pModel == null)
            {
                return "未能找到采购单";
            }
            if (pModel.StockInStatus == 3)
            {
                return "该采购单已入库完毕";
            }
            var DetailList = procurement_DetailRepository.GetList(new RB_Procurement_Detail_Extend() { RB_Group_Id = eRPGroupId, ProcurementId = demodel.Id });
            if (DetailList.Any())
            {
                string materialIds = string.Join(",", DetailList.Select(x => x.MaterialId ?? 0).Distinct());
                var materialList = supplies_MaterialRepository.GetList(new RB_Supplies_Material_Extend() { RB_Group_Id = eRPGroupId, SuppliesIdStr = materialIds });
                foreach (var item in DetailList)
                {
                    var materialModel = materialList.Where(x => x.Id == item.MaterialId).FirstOrDefault();
                    if (materialModel == null)
                    {
                        return "未能查询到物料信息";
                    }
                    item.GoodsId = materialModel.GoodsId ?? 0;
                    item.SpecificationKey = materialModel.SpecificationKey;
                }
            }
            //验证已入库数量
            foreach (var item in demodel.DetailList)
            {
                var dModel = DetailList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationKey == item.SpecificationKey).FirstOrDefault();
                if (dModel == null)
                {
                    return "未找到相关商品信息，商品ID：" + item.GoodsId;
                }
                if ((dModel.Number ?? 0) - (dModel.StockInNum ?? 0) < item.InStockNum)
                {
                    return "剩余入库数量不足，请核实后再试，商品ID：" + item.GoodsId;
                }

                dModel.StockInNum = (dModel.StockInNum ?? 0) + item.InStockNum;
            }
            bool IsComplete = true;
            foreach (var item in DetailList)
            {
                if ((item.Number ?? 0) > (item.StockInNum ?? 0))
                {
                    IsComplete = false;//部分入库
                }
            }

            try
            {
                var trans = procurementRepository.DbTransaction;
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Procurement_Extend.StockInStatus),IsComplete ? 3 : 2},
                    { nameof(RB_Procurement_Extend.UpdateDate),DateTime.Now}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Procurement_Extend.Id),
                          FiledValue=demodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = procurementRepository.Update(keyValues, wheres, trans);
                if (flag)
                {
                    //增加采购单已入库数量
                    foreach (var item in demodel.DetailList)
                    {
                        var dModel = DetailList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationKey == item.SpecificationKey).FirstOrDefault();
                        Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                            { nameof(RB_Procurement_Detail_Extend.StockInNum),dModel.StockInNum}
                        };
                        List<WhereHelper> wheres1 = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_Procurement_Detail_Extend.Id),
                                  FiledValue=dModel.Id,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        procurement_DetailRepository.Update(keyValues1, wheres1, trans);
                    }

                    #region 生成入库单
                    RB_Supplies_StockIn_Extend stockInModel = new RB_Supplies_StockIn_Extend();
                    stockInModel.ProcurementId = pModel.Id;
                    stockInModel.WarehouseId = pModel.WareHouseId;
                    stockInModel.StockInDate = DateTime.Now;
                    stockInModel.Status = 0;
                    stockInModel.RB_Branch_Id = eRPBranchId;
                    stockInModel.RB_Group_Id = eRPGroupId;
                    stockInModel.CreateBy = eRPEmpId;
                    stockInModel.CreateDate = DateTime.Now;
                    stockInModel.UpdateBy = eRPEmpId;
                    stockInModel.UpdateDate = DateTime.Now;
                    stockInModel.SupplierName = pModel.SupplierName;
                    stockInModel.DetailList = new List<RB_Supplies_StockInDetail_Extend>();
                    stockInModel.Money = 0;
                    foreach (var item in demodel.DetailList)
                    {
                        var dModel = DetailList.Where(x => x.GoodsId == item.GoodsId && x.SpecificationKey == item.SpecificationKey).FirstOrDefault();
                        decimal Money = (dModel.CostMoney ?? 0) * item.InStockNum;
                        stockInModel.Money += Money;
                        stockInModel.DetailList.Add(new RB_Supplies_StockInDetail_Extend()
                        {
                            SuppliesId = dModel.MaterialId,
                            Money = Money,
                            Number = item.InStockNum,
                            CreateBy = eRPEmpId,
                            CreateDate = DateTime.Now,
                            Id = 0,
                            RB_Branch_Id = eRPBranchId,
                            RB_Group_Id = eRPGroupId,
                            Remark = "电商自动生成",
                            Status = 0,
                            StockInId = 0,
                            UnitPrice = (dModel.CostMoney ?? 0),
                            UpdateBy = eRPEmpId,
                            UpdateDate = DateTime.Now
                        });
                    }

                    bool falg2 = SetStockInInfo(stockInModel, null);
                    if (falg2 == false)
                    {
                        procurementRepository.DBSession.Rollback();
                        return "资产入库单生成失败";
                    }
                    #endregion

                    property_LogRepository.Insert(new Model.Entity.Property.RB_Property_Log()
                    {
                        Type = 3,
                        Content = "采购单入库",
                        CreateBy = empId,
                        CreateDate = DateTime.Now,
                        Id = 0,
                        MallBaseId = mallBaseId,
                        SourceId = demodel.Id,
                        TenantId = tenantId
                    });
                }
                procurementRepository.DBSession.Commit();
                return "";
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "");
                procurementRepository.DBSession.Rollback();
                return "出错啦，请联系管理员";
            }
        }

        /// <summary>
        /// 设置入库单
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetStockInInfo(RB_Supplies_StockIn_Extend demodel, System.Data.IDbTransaction trans)
        {
            try
            {
                //生产编号
                demodel.StockInState = 1;
                var tmodel = GetTempleteModel(PropertyFlowEnum.StockIn, demodel.RB_Branch_Id ?? 0);
                demodel.TempleteId = tmodel?.Id ?? 0;
                var rmodel = auditRelevanceRepository.GetList(new RB_Property_AuditRelevance() { RB_Group_Id = demodel.RB_Group_Id, Type = PropertyFlowEnum.StockIn }).FirstOrDefault();
                if (rmodel != null && rmodel.Enabled == 1)
                {
                    demodel.StockInState = 2;
                }
                int Id = supplies_StockInRepository.Insert(demodel, trans);
                if (Id > 0)
                {
                    //编码自动生成
                    string BMStr = Id.ToString();
                    if (BMStr.Length < 5)
                    {
                        switch (BMStr.Length)
                        {
                            case 1:
                                BMStr = "0000" + BMStr; break;
                            case 2:
                                BMStr = "000" + BMStr; break;
                            case 3:
                                BMStr = "00" + BMStr; break;
                            case 4:
                                BMStr = "0" + BMStr; break;
                        }
                    }
                    BMStr = "RK" + DateTime.Now.ToString("yyyyMMdd") + BMStr;
                    Dictionary<string, object> files = new Dictionary<string, object>() {
                        { nameof(RB_Supplies_StockIn.StockInNum),BMStr}
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                                FiledName=nameof(RB_Supplies_StockIn.Id),
                                FiledValue=Id,
                                OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    supplies_StockInRepository.Update(files, wheres, trans);

                    //新增明细
                    foreach (var item in demodel.DetailList)
                    {
                        supplies_StockInDetailRepository.Insert(new RB_Supplies_StockInDetail()
                        {
                            CreateBy = demodel.CreateBy,
                            CreateDate = demodel.CreateDate,
                            Money = item.Money,
                            Number = item.Number,
                            RB_Branch_Id = demodel.RB_Branch_Id,
                            Id = 0,
                            RB_Group_Id = demodel.RB_Group_Id,
                            Remark = item.Remark,
                            Status = 0,
                            StockInId = Id,
                            SuppliesId = item.SuppliesId,
                            UnitPrice = item.UnitPrice,
                            UpdateBy = demodel.UpdateBy,
                            UpdateDate = demodel.UpdateDate
                        }, trans);

                        if (demodel.StockInState == 1)
                        {
                            //新增库存表数据
                            var ilist = supplies_InventoryRepository.GetList(new RB_Supplies_Inventory_Extend() { RB_Group_Id = demodel.RB_Group_Id, WarehouseId = demodel.WarehouseId, SuppliesId = item.SuppliesId });
                            if (ilist.Any())
                            {
                                var iModel = ilist.FirstOrDefault();
                                iModel.Number += item.Number;//增加库存
                                iModel.Money += item.Money;
                                var iflag = supplies_InventoryRepository.Update(iModel, trans);
                                if (iflag)
                                {
                                    //增加库存明细
                                    supplies_InventoryDetailRepository.Insert(new RB_Supplies_InventoryDetail()
                                    {
                                        CreateBy = demodel.CreateBy,
                                        CreateDate = DateTime.Now,
                                        InventoryId = iModel.Id,
                                        Number = item.Number,
                                        Money = item.Money,
                                        RB_Branch_Id = demodel.RB_Branch_Id,
                                        RB_Group_Id = demodel.RB_Group_Id,
                                        Status = 0,
                                        Type = 1,
                                        Id = 0,
                                        Description = "新增库存"
                                    }, trans);
                                }
                            }
                            else
                            {
                                //新增库存表
                                int iId = supplies_InventoryRepository.Insert(new RB_Supplies_Inventory()
                                {
                                    CreateBy = demodel.CreateBy,
                                    CreateDate = DateTime.Now,
                                    Id = 0,
                                    Number = item.Number,
                                    Money = item.Money,
                                    RB_Branch_Id = demodel.RB_Branch_Id,
                                    RB_Group_Id = demodel.RB_Group_Id,
                                    Status = 0,
                                    SuppliesId = item.SuppliesId,
                                    UpdateBy = demodel.UpdateBy,
                                    UpdateDate = demodel.UpdateDate,
                                    WarehouseId = demodel.WarehouseId
                                }, trans);
                                if (iId > 0)
                                {
                                    //增加库存明细
                                    supplies_InventoryDetailRepository.Insert(new RB_Supplies_InventoryDetail()
                                    {
                                        CreateBy = demodel.CreateBy,
                                        CreateDate = DateTime.Now,
                                        InventoryId = iId,
                                        Number = item.Number,
                                        Money = item.Money,
                                        RB_Branch_Id = demodel.RB_Branch_Id,
                                        RB_Group_Id = demodel.RB_Group_Id,
                                        Status = 0,
                                        Type = 1,
                                        Id = 0,
                                        Description = "新增库存"
                                    }, trans);
                                }
                            }
                        }
                    }

                    #region 新增耗材入库流程

                    //判断是否需要流程审批                    
                    if (rmodel != null && rmodel.Enabled == 1 && tmodel != null)
                    {
                        var financeObj = new { StockInId = Id };
                        string sign = EncryptionHelper.AesEncrypt(JsonHelper.Serialize(financeObj), Config.FinanceKey);
                        var resultInfo = new
                        {
                            msg = sign
                        };
                        //调用资产 生成审核流程
                        string apiResult = HttpHelper.HttpPost(Config.PropertyApi, JsonHelper.Serialize(resultInfo), "");
                        LogHelper.Write(apiResult);
                        var apir = JsonConvert.DeserializeObject<ApiResult>(apiResult);
                        if (apir.resultCode == 1)
                        {
                            Dictionary<string, object> files1 = new Dictionary<string, object>() {
                                { nameof(RB_Supplies_StockIn.Remark),"创建流程成功"}
                            };
                            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                new WhereHelper(){
                                        FiledName=nameof(RB_Supplies_StockIn.Id),
                                        FiledValue=Id,
                                        OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            supplies_StockInRepository.Update(files1, wheres1, trans);
                        }
                        else
                        {
                            Dictionary<string, object> files1 = new Dictionary<string, object>() {
                                { nameof(RB_Supplies_StockIn.Remark),"创建流程失败"}
                            };
                            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                new WhereHelper(){
                                        FiledName=nameof(RB_Supplies_StockIn.Id),
                                        FiledValue=Id,
                                        OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            supplies_StockInRepository.Update(files1, wheres1, trans);
                        }
                    }

                    #endregion
                }
                return Id > 0;
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetStockInInfo");
                return false;
            }
        }

        /// <summary>
        /// 获取流程模板
        /// </summary>
        /// <param name="audite"></param>
        /// <param name="BranchId"></param>
        /// <returns></returns>
        private Rb_Workflow_Template_Extend GetTempleteModel(PropertyFlowEnum audite, int BranchId)
        {
            var tempList = workflow_TemplateRepository.GetList(new Rb_Workflow_Template_Extend() { TemplateSorce = 2, PropertyType = (int)audite, Status = 1 });
            List<RB_FinanceFlowConnect_Extend> fcList = new List<RB_FinanceFlowConnect_Extend>();
            //再验证公司别
            if (tempList.Any())
            {
                fcList = financeFlowConnectRepository.GetExtendList(new RB_FinanceFlowConnect_Extend() { FlowtemplateIds = string.Join(",", tempList.Select(x => x.Id)) });
            }
            foreach (var item in tempList)
            {
                var fc2list = fcList.Where(x => x.FlowtemplateId == item.Id).ToList();
                if (fc2list.Where(x => x.Type == FinanceFlowConnectEnum.Company).Any())
                {
                    //集团通用
                    return item;
                }
                else if (fc2list.Where(x => x.Type == FinanceFlowConnectEnum.Branch && x.SuitableObjectId == BranchId).Any())
                {
                    //该公司在使用该流程
                    return item;
                }
            }
            return null;
        }

        /// <summary>
        /// 获取入库单的标签
        /// </summary>
        /// <param name="procurementId"></param>
        /// <param name="eRPEmpId"></param>
        /// <param name="eRPGroupId"></param>
        /// <param name="empId"></param>
        /// <returns></returns>
        public object GetProcurementStockInLableList(int procurementId, int StockInId, int eRPEmpId, int eRPGroupId, int empId)
        {
            List<object> RObj = new List<object>();
            var pmodel = procurementRepository.GetEntity(procurementId);
            var siList = supplies_StockInRepository.GetList(new RB_Supplies_StockIn_Extend() { RB_Group_Id = eRPGroupId, ProcurementId = procurementId, Id = StockInId });
            if (siList.Any())
            {
                string siIds = string.Join(",", siList.Where(x => x.StockInState == 1).Select(x => x.Id));
                var sidList = supplies_StockInDetailRepository.GetList(new RB_Supplies_StockInDetail_Extend() { RB_Group_Id = eRPGroupId, StockInIdStr = siIds });
                List<RB_Supplies_Material_Extend> materialList = new List<RB_Supplies_Material_Extend>();
                List<Model.Extend.Property.RB_Employee_Extend> empList = new List<Model.Extend.Property.RB_Employee_Extend>();
                List<RB_Goods_Extend> GList = new List<RB_Goods_Extend>();
                if (sidList.Any())
                {
                    string matIds = string.Join(",", sidList.Select(x => x.SuppliesId).Distinct());
                    materialList = supplies_MaterialRepository.GetList(new RB_Supplies_Material_Extend() { RB_Group_Id = eRPGroupId, SuppliesIdStr = matIds });
                    if (materialList.Where(x => x.GoodsId > 0).Any())
                    {
                        string goodsIds = string.Join(",", materialList.Where(x => x.GoodsId > 0).Select(x => x.GoodsId).Distinct());
                        GList = goodsRepository.GetSingleListForGoodsSubName(new RB_Goods_Extend() { GoodsIds = goodsIds });
                    }
                    string erpEmpIds = string.Join(",", sidList.Select(x => x.CreateBy ?? 0).Distinct());
                    empList = erpemployeeRepository.GetList(new Model.Extend.Property.RB_Employee_Extend() { RB_Group_id = eRPGroupId, EmployeeIds = erpEmpIds });
                }
                foreach (var item in sidList)
                {

                    var siModel = siList.Where(x => x.Id == item.StockInId).FirstOrDefault();
                    var materialModel = materialList.Where(x => x.Id == item.SuppliesId).FirstOrDefault();
                    if (materialModel == null) { continue; }

                    List<string> spList = new List<string>();
                    if (!string.IsNullOrEmpty(materialModel.SpecificationName) && materialModel.SpecificationName != "[]")
                    {
                        spList = JsonConvert.DeserializeObject<List<string>>(materialModel.SpecificationName);
                    }
                    var empModel = empList.Where(x => x.EmployeeId == item.CreateBy).FirstOrDefault();

                    string QRCode = "D-" + (siModel.WarehouseId ?? 0) + "-" + procurementId + "-" + (item.SuppliesId ?? 0) + "-" + (item.StockInId ?? 0);
                    string TQRCode = "DA" + (siModel.WarehouseId ?? 0) + "A" + procurementId + "A" + (item.SuppliesId ?? 0) + "A" + (item.StockInId ?? 0);
                    #region 生成二维码 + 条形码
                    string QRName = "QR-" + DateTime.Now.ToString("yyyyMMdd") + "-" + procurementId + "-" + (item.SuppliesId ?? 0) + ".jpg";
                    string TQRName = "TQR-" + DateTime.Now.ToString("yyyyMMdd") + "-" + procurementId + "-" + (item.SuppliesId ?? 0) + ".jpg";
                    string basepath = AppContext.BaseDirectory;
                    string QRPath = basepath + "\\upfile\\code\\" + QRName;
                    string QRImage = "/upfile/code/" + QRName;
                    string TQRPath = basepath + "\\upfile\\code\\" + TQRName;
                    string TQRImage = "/upfile/code/" + TQRName;
                    //验证文件是否存在，  存在的话就不用生成了
                    if (!File.Exists(QRPath))
                    {
                        QRCodeHelper.CreateQRCode(QRCode, 5, "", QRPath, ImageFormat.Jpeg);
                    }
                    if (!File.Exists(TQRPath))
                    {
                        int width = 340;
                        if (TQRCode.Length > 30)
                        {
                            width = 370;
                        }
                        QRCodeHelper.CreateTQRCode(TQRCode, TQRPath, ImageFormat.Jpeg, width, 50);
                    }
                    #endregion

                    var gmodel = GList.Where(x => x.Id == (materialModel.GoodsId ?? 0)).FirstOrDefault();
                    string SubName = gmodel?.SubName ?? "";
                    for (int i = 0; i < (item.Number ?? 0); i++)
                    {
                        RObj.Add(new
                        {
                            materialModel.GoodsId,
                            GoodsName = SubName == "" ? materialModel.Name : SubName,
                            SpecificationList = spList,
                            CreateDate = item.CreateDate.HasValue ? item.CreateDate.Value.ToString("yyyy-MM-dd") : "",
                            EmName = empModel?.EmName ?? "",
                            siModel.WareHouseName,
                            CostMoney = item.UnitPrice,
                            QRImage,
                            TQRImage,
                            TQRCode
                        });
                    }
                }

            }
            return RObj;
        }

        /// <summary>
        /// 获取采购入库批次列表
        /// </summary>
        /// <param name="procurementId"></param>
        /// <param name="eRPEmpId"></param>
        /// <param name="eRPGroupId"></param>
        /// <param name="empId"></param>
        /// <returns></returns>
        public object GetProcurementSotckInBatchList(int procurementId, int eRPEmpId, int eRPGroupId, int empId)
        {
            List<object> RObj = new List<object>();
            var siList = supplies_StockInRepository.GetList(new RB_Supplies_StockIn_Extend() { RB_Group_Id = eRPGroupId, ProcurementId = procurementId });
            siList = siList.Where(x => x.StockInState == 1).ToList();
            return siList.Select(x => new
            {
                StockInId = x.Id,
                x.StockInNum
            });
        }

        #endregion

        #region 获取资产物料列表

        /// <summary>
        /// 获取物料档案分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="demodel"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public List<RB_Supplies_Material_Extend> GetMaterialPageList(int pageIndex, int pageSize, RB_Supplies_Material_Extend demodel, out long count)
        {
            var list = supplies_MaterialRepository.GetPageList(pageIndex, pageSize, demodel, out count);
            List<RB_Supplies_Inventory_Extend> iList = new List<RB_Supplies_Inventory_Extend>();
            if (demodel.WareHouseId > 0 && list.Any())
            {
                //查询出该仓库  耗材下 所有的库存
                string Sstr = string.Join(",", list.Select(x => x.Id).Distinct());
                iList = supplies_InventoryRepository.GetList(new RB_Supplies_Inventory_Extend() { RB_Group_Id = demodel.RB_Group_Id, WarehouseIdStr = demodel.WareHouseId.Value.ToString(), SuppliesIdStr = Sstr });
            }
            foreach (var item in list)
            {
                if (item.Images == "" || item.Images == null)
                {
                    item.Images = "[]";
                }
                item.ImageList = JsonConvert.DeserializeObject<List<string>>(item.Images);

                item.InventoryNum = iList.Where(x => x.SuppliesId == item.Id).FirstOrDefault()?.Number ?? 0;
                item.GoodsSpecificationList = new List<string>();
                item.GoodsCategoryList = new List<string>();
                if (!string.IsNullOrEmpty(item.SpecificationName))
                {
                    item.GoodsSpecificationList = JsonConvert.DeserializeObject<List<string>>(item.SpecificationName);
                }
                if (!string.IsNullOrEmpty(item.GoodsCategoryName))
                {
                    item.GoodsCategoryList = JsonConvert.DeserializeObject<List<string>>(item.GoodsCategoryName);
                }
            }
            return list;
        }

        /// <summary>
        /// 同步商品信息至资产物料
        /// </summary>
        /// <param name="wareHouseId"></param>
        /// <param name="categoryIdList"></param>
        /// <param name="eRPEmpId"></param>
        /// <param name="eRPGroupId"></param>
        /// <returns></returns>
        public bool SetSyncGoodsToMaterial(int wareHouseId, List<int> categoryIdList, int eRPEmpId, int eRPBranchId, int eRPGroupId, int tenantId, int mallBaseId, int EmpId)
        {
            try
            {
                string CategoryIds = "";
                if (categoryIdList.Any())
                {
                    var cateids = string.Join(",", categoryIdList);
                    var cateList = product_CategoryRepository.GetList(new RB_Product_Category_Extend() { CategoryIds = cateids, TenantId = tenantId, MallBaseId = mallBaseId });
                    List<int> AllClist = new List<int>();
                    foreach (var cmodel in cateList)
                    {
                        //获取该分类下所有子集分类
                        if (cmodel != null)
                        {
                            AllClist.Add(cmodel.Id);
                            var clist = product_CategoryRepository.GetList(new RB_Product_Category_Extend() { TenantId = tenantId, MallBaseId = mallBaseId, RootId = cmodel.RootId });
                            var OneList = clist.Where(x => x.ParentId == cmodel.Id).ToList();
                            foreach (var item in OneList)
                            {
                                AllClist.Add(item.Id);
                                var TwoList = clist.Where(x => x.ParentId == item.Id).ToList();
                                if (TwoList.Any())
                                {
                                    AllClist.AddRange(TwoList.Select(x => x.Id).Distinct().ToList());
                                }
                            }
                        }
                    }
                    if (AllClist.Any())
                    {
                        CategoryIds = string.Join(",", AllClist);
                    }
                }
                //根据分类  查询出所有的商品
                var GoodsList = goodsRepository.GetList(new RB_Goods_Extend() { CategoryIds = CategoryIds, TenantId = tenantId, MallBaseId = mallBaseId });
                if (GoodsList.Any())
                {
                    var SpecificationList = new List<RB_Goods_Specification_Extend>();
                    var SpecificationPriceList = new List<RB_Goods_SpecificationPrice_Extend>();
                    //查询出商品规格
                    if (GoodsList.Where(x => x.IsCustomSpecification == 1).Any())
                    {
                        string goodsIds = string.Join(",", GoodsList.Where(x => x.IsCustomSpecification == 1).Select(x => x.Id));
                        SpecificationList = goods_SpecificationRepository.GetList(new RB_Goods_Specification_Extend() { GoodsIds = goodsIds, TenantId = tenantId, MallBaseId = mallBaseId });
                        if (SpecificationList.Any())
                        {
                            var svlist = goods_SpecificationValueRepository.GetList(new RB_Goods_SpecificationValue_Extend() { GoodsIds = goodsIds, TenantId = tenantId, MallBaseId = mallBaseId });
                            foreach (var item in svlist)
                            {
                                item.ImagePath = item.Image;
                            }
                            foreach (var item in SpecificationList)
                            {
                                item.SpecificationValueList = svlist.Where(x => x.SpecificationId == item.Id).ToList();
                            }
                        }
                        SpecificationPriceList = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { GoodsIds = goodsIds, TenantId = tenantId, MallBaseId = mallBaseId });
                        foreach (var item in SpecificationPriceList)
                        {
                            if (!string.IsNullOrEmpty(item.SpecificationSort))
                            {
                                var SpList = SpecificationList.Where(x => x.GoodsId == item.GoodsId).ToList();
                                var ssarr = item.SpecificationSort.Split(':');
                                int Sort = Convert.ToInt32(ssarr[0]);
                                List<string> AttrList = new List<string>();
                                for (int i = 0; i < ssarr.Length; i++)
                                {
                                    var smodel = SpList[i];
                                    var svmodel = smodel.SpecificationValueList.Where(x => x.Sort == Convert.ToInt32(ssarr[i])).FirstOrDefault();
                                    AttrList.Add(smodel.Name + "：" + svmodel.Name);
                                }
                                item.AttrStr = JsonConvert.SerializeObject(AttrList);
                            }
                        }
                    }
                    var GCList = goods_CategoryRepository.GetList(new RB_Goods_Category_Extend() { GoodsIds = string.Join(",", GoodsList.Select(x => x.Id)), TenantId = tenantId, MallBaseId = mallBaseId });
                    string SupplierIds = string.Join(",", GoodsList.Where(x => x.SupplierId > 0).Select(x => x.SupplierId).Distinct());
                    var Supplierlist = supplierRepository.GetList(new RB_Supplier_Extend() { SupplierIds = SupplierIds, TenantId = tenantId, MallBaseId = mallBaseId });
                    var mList = supplies_MaterialRepository.GetList(new RB_Supplies_Material_Extend() { RB_Group_Id = eRPGroupId, TenantId = tenantId, MallBaseId = mallBaseId });
                    foreach (var item in GoodsList)
                    {
                        var supplierModel = Supplierlist.Where(x => x.ID == item.SupplierId).FirstOrDefault();
                        var QGCList = GCList.Where(x => x.GoodsId == item.Id).ToList();
                        string GoodsCategoryIds = string.Join(",", QGCList.Select(x => x.CategoryId).Distinct());
                        string GoodsCategoryName = JsonConvert.SerializeObject(QGCList.Select(x => x.CategoryName).Distinct());
                        var spList = SpecificationPriceList.Where(x => x.GoodsId == item.Id).ToList();
                        if (spList.Any())
                        {
                            foreach (var qitem in spList)
                            {
                                var mModel = mList.Where(x => x.GoodsId == item.Id && x.SpecificationKey == qitem.SpecificationSort).FirstOrDefault();
                                if (mModel == null)
                                {
                                    //新增该耗材
                                    int MaterialId = supplies_MaterialRepository.Insert(new Model.Entity.Property.RB_Supplies_Material()
                                    {
                                        Barcode = "",
                                        BrandName = "",
                                        CategoryId = 1,
                                        CreateBy = eRPEmpId,
                                        CreateDate = DateTime.Now,
                                        GoodsCategoryIds = GoodsCategoryIds,
                                        GoodsCategoryName = GoodsCategoryName,
                                        GoodsId = item.Id,
                                        Id = 0,
                                        Images = item.CarouselImage,
                                        Money = item.CostPrice,
                                        Name = item.Name,
                                        RB_Branch_Id = eRPBranchId,
                                        RB_Group_Id = eRPGroupId,
                                        Remark = "电商同步",
                                        ReservedStock = 0,
                                        SafetyStock = 0,
                                        SpecificationKey = qitem.SpecificationSort,
                                        SpecificationName = qitem.AttrStr,
                                        Status = 0,
                                        SupplierName = supplierModel?.Name ?? "",
                                        SuppliesModel = "",
                                        SuppliesNum = "",
                                        Units = item.Unit,
                                        UpdateBy = eRPEmpId,
                                        UpdateDate = DateTime.Now,
                                        TenantId = tenantId,
                                        MallBaseId = mallBaseId
                                    });
                                    if (MaterialId > 0)
                                    {
                                        //编码自动生成
                                        string BMStr = MaterialId.ToString();
                                        if (BMStr.Length < 5)
                                        {
                                            switch (BMStr.Length)
                                            {
                                                case 1:
                                                    BMStr = "0000" + BMStr; break;
                                                case 2:
                                                    BMStr = "000" + BMStr; break;
                                                case 3:
                                                    BMStr = "00" + BMStr; break;
                                                case 4:
                                                    BMStr = "0" + BMStr; break;
                                            }
                                        }
                                        Dictionary<string, object> files = new Dictionary<string, object>() {
                                            { nameof(RB_Supplies_Material_Extend.SuppliesNum),BMStr}
                                        };
                                        List<WhereHelper> wheres = new List<WhereHelper>() {
                                            new WhereHelper(){
                                                 FiledName=nameof(RB_Supplies_Material_Extend.Id),
                                                  FiledValue=MaterialId,
                                                   OperatorEnum=OperatorEnum.Equal
                                            }
                                        };
                                        supplies_MaterialRepository.Update(files, wheres);
                                    }
                                }
                                else
                                {
                                    //修改
                                    Dictionary<string, object> files = new Dictionary<string, object>() {
                                        { nameof(RB_Supplies_Material_Extend.GoodsCategoryIds),GoodsCategoryIds},
                                        { nameof(RB_Supplies_Material_Extend.GoodsCategoryName),GoodsCategoryName},
                                        { nameof(RB_Supplies_Material_Extend.Images), item.CarouselImage},
                                        { nameof(RB_Supplies_Material_Extend.Money),item.CostPrice},
                                        { nameof(RB_Supplies_Material_Extend.Name),item.Name},
                                        { nameof(RB_Supplies_Material_Extend.SpecificationKey),qitem.SpecificationSort},
                                        { nameof(RB_Supplies_Material_Extend.SpecificationName),qitem.AttrStr},
                                        { nameof(RB_Supplies_Material_Extend.Units),item.Unit},
                                        { nameof(RB_Supplies_Material_Extend.SupplierName),supplierModel?.Name ?? ""},
                                    };
                                    List<WhereHelper> wheres = new List<WhereHelper>() {
                                        new WhereHelper(){
                                                FiledName=nameof(RB_Supplies_Material_Extend.Id),
                                                FiledValue=mModel.Id,
                                                OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                                    supplies_MaterialRepository.Update(files, wheres);
                                }
                            }
                        }
                        else
                        {
                            string SpecificationName = "[\"规格：" + item.DefaultSpecificationName + "\"]";
                            var mModel = mList.Where(x => x.GoodsId == item.Id && x.SpecificationKey == "").FirstOrDefault();
                            if (mModel == null)
                            {
                                //新增该耗材
                                int MaterialId = supplies_MaterialRepository.Insert(new Model.Entity.Property.RB_Supplies_Material()
                                {
                                    Barcode = "",
                                    BrandName = "",
                                    CategoryId = 1,
                                    CreateBy = eRPEmpId,
                                    CreateDate = DateTime.Now,
                                    GoodsCategoryIds = GoodsCategoryIds,
                                    GoodsCategoryName = GoodsCategoryName,
                                    GoodsId = item.Id,
                                    Id = 0,
                                    Images = item.CarouselImage,
                                    Money = item.CostPrice,
                                    Name = item.Name,
                                    RB_Branch_Id = eRPBranchId,
                                    RB_Group_Id = eRPGroupId,
                                    Remark = "电商同步",
                                    ReservedStock = 0,
                                    SafetyStock = 0,
                                    SpecificationKey = "",
                                    SpecificationName = SpecificationName,
                                    Status = 0,
                                    SupplierName = supplierModel?.Name ?? "",
                                    SuppliesModel = "",
                                    SuppliesNum = "",
                                    Units = item.Unit,
                                    UpdateBy = eRPEmpId,
                                    UpdateDate = DateTime.Now,
                                    TenantId = tenantId,
                                    MallBaseId = mallBaseId
                                });
                                if (MaterialId > 0)
                                {
                                    //编码自动生成
                                    string BMStr = MaterialId.ToString();
                                    if (BMStr.Length < 5)
                                    {
                                        switch (BMStr.Length)
                                        {
                                            case 1:
                                                BMStr = "0000" + BMStr; break;
                                            case 2:
                                                BMStr = "000" + BMStr; break;
                                            case 3:
                                                BMStr = "00" + BMStr; break;
                                            case 4:
                                                BMStr = "0" + BMStr; break;
                                        }
                                    }
                                    Dictionary<string, object> files = new Dictionary<string, object>() {
                                            { nameof(RB_Supplies_Material_Extend.SuppliesNum),BMStr}
                                        };
                                    List<WhereHelper> wheres = new List<WhereHelper>() {
                                            new WhereHelper(){
                                                 FiledName=nameof(RB_Supplies_Material_Extend.Id),
                                                  FiledValue=MaterialId,
                                                   OperatorEnum=OperatorEnum.Equal
                                            }
                                        };
                                    supplies_MaterialRepository.Update(files, wheres);
                                }
                            }
                            else
                            {
                                //修改
                                Dictionary<string, object> files = new Dictionary<string, object>() {
                                    { nameof(RB_Supplies_Material_Extend.GoodsCategoryIds),GoodsCategoryIds},
                                    { nameof(RB_Supplies_Material_Extend.GoodsCategoryName),GoodsCategoryName},
                                    { nameof(RB_Supplies_Material_Extend.Images), item.CarouselImage},
                                    { nameof(RB_Supplies_Material_Extend.Money),item.CostPrice},
                                    { nameof(RB_Supplies_Material_Extend.Name),item.Name},
                                    { nameof(RB_Supplies_Material_Extend.SpecificationKey),""},
                                    { nameof(RB_Supplies_Material_Extend.SpecificationName),SpecificationName},
                                    { nameof(RB_Supplies_Material_Extend.Units),item.Unit},
                                    { nameof(RB_Supplies_Material_Extend.SupplierName),supplierModel?.Name ?? ""},
                                };
                                List<WhereHelper> wheres = new List<WhereHelper>() {
                                    new WhereHelper(){
                                            FiledName=nameof(RB_Supplies_Material_Extend.Id),
                                            FiledValue=mModel.Id,
                                            OperatorEnum=OperatorEnum.Equal
                                    }
                                };
                                supplies_MaterialRepository.Update(files, wheres);
                            }
                        }
                    }
                }
                property_LogRepository.Insert(new Model.Entity.Property.RB_Property_Log()
                {
                    Type = 2,
                    Content = "同步商品信息至资产耗材，wareHouseId=" + wareHouseId,
                    CreateBy = EmpId,
                    CreateDate = DateTime.Now,
                    Id = 0,
                    MallBaseId = mallBaseId,
                    SourceId = 0,
                    TenantId = tenantId
                });
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetSyncGoodsToMaterial");
                return false;
            }
        }


        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Supplies_Material_Extend> GetSuppliesMaterialList(RB_Supplies_Material_Extend dmodel)
        {
            return supplies_MaterialRepository.GetList(dmodel);
        }



        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Supplies_Material_Extend> GetHaveInventory(RB_Supplies_Material_Extend dmodel)
        {
            return supplies_MaterialRepository.GetHaveInventory(dmodel);
        }
        #endregion


        #region 盘点

        /// <summary>
        /// 获取盘点单分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="demodel"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public List<RB_Supplies_Check_Extend> GetSuppliesCheckPageList(int pageIndex, int pageSize, RB_Supplies_Check_Extend demodel, out long count)
        {
            var list = supplies_CheckRepository.GetPageList(pageIndex, pageSize, demodel, out count);
            if (list.Any())
            {
                //查询仓库
                var wlist = supplies_WareHouseRepository.GetList(new RB_Supplies_WareHouse_Extend() { RB_Group_Id = demodel.RB_Group_Id, WareHouseIdStr = string.Join(",", list.Select(x => x.WarehouseId ?? 0).Distinct()) });
                foreach (var item in list)
                {
                    var wmodel = wlist.Where(x => x.Id == item.WarehouseId).FirstOrDefault();
                    item.WarehouseName = wmodel?.Name ?? "";
                }
            }
            return list;
        }



        /// <summary>
        /// 根据条件获取盘点列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Supplies_Check_Extend> GetSuppliesCheckList(RB_Supplies_Check_Extend dmodel)
        {
            return supplies_CheckRepository.GetList(dmodel);
        }

        /// <summary>
        /// 获取盘点单
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public RB_Supplies_Check_Extend GetSuppliesCheck(int Id)
        {
            return supplies_CheckRepository.GetEntity<RB_Supplies_Check_Extend>(Id);
        }



        /// <summary>
        /// 盘点单复盘
        /// </summary>
        /// <param name="checkId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public bool RepeatSuppliesCheck(int checkId, UserInfo userInfo)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Supplies_Check_Extend.CheckState),SuppliesCheckStatusEnum.InTheInventory},
                { nameof(RB_Supplies_Check_Extend.UpdateBy),userInfo.ERPEmpId},
                { nameof(RB_Supplies_Check_Extend.UpdateDate),DateTime.Now},
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_Supplies_Check_Extend.Id),
                      FiledValue=checkId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = supplies_CheckRepository.Update(keyValues, wheres);
            if (flag)
            {
                //是否需要重置盘点明细的盘点状态

            }
            return flag;
        }

        /// <summary>
        /// 获取盘点单明细分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="demodel"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public List<RB_Supplies_CheckDetail_Extend> GetSuppliesCheckDetailPageList(int pageIndex, int pageSize, RB_Supplies_CheckDetail_Extend demodel, out long count)
        {
            var list = supplies_CheckDetailRepository.GetPageList(pageIndex, pageSize, demodel, out count);

            if (list.Any())
            {
                //组装规格
                foreach (var item in list)
                {
                    item.SpecificationList = new List<string>();
                    if (!string.IsNullOrEmpty(item.SpecificationName) && item.SpecificationName != "[]")
                    {
                        item.SpecificationList = JsonConvert.DeserializeObject<List<string>>(item.SpecificationName);
                    }
                    item.ImageList = new List<string>();
                    if (!string.IsNullOrEmpty(item.Images) && item.Images != "[]")
                    {
                        item.ImageList = JsonConvert.DeserializeObject<List<string>>(item.Images);
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 验证盘点单状态
        /// </summary>
        /// <param name="checkDetailId"></param>
        /// <returns></returns>
        public bool ValidataSuppliesCheckDetail(int checkDetailId)
        {
            var model = supplies_CheckDetailRepository.GetEntity(checkDetailId);
            var cmodel = supplies_CheckRepository.GetEntity(model?.CheckId ?? 0);
            if (cmodel != null && cmodel.CheckState == SuppliesCheckStatusEnum.InTheInventory)
            {
                return false;
            }
            return true;
        }



        #endregion

    }
}
