using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Mall.Common;
using Mall.Common.API;
using Mall.Common.Plugin;
using Mall.Model.Entity.Product;
using Mall.Model.Entity.User;
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.Product;
using Mall.Repository.Property;
using Mall.Repository.User;
using Newtonsoft.Json;

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



        #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() { 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() { 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 = "[]";
                            }
                            var imglist = JsonConvert.DeserializeObject<List<string>>(item.MaterialModel.Images);
                            item.MaterialModel.ImageList = new List<string>();
                        }
                        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() { 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)
        {
            var pmodel = procurementRepository.GetEntity<RB_Procurement_Extend>(procurementId);
            //查询明细
            var pdList = procurement_DetailRepository.GetList(new RB_Procurement_Detail_Extend() { 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() { 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 = "[]";
                        }
                        var imglist = JsonConvert.DeserializeObject<List<string>>(item.MaterialModel.Images);
                        item.MaterialModel.ImageList = new List<string>();
                    }
                    else
                    {
                        item.MaterialModel = new RB_Supplies_Material_Extend();
                    }
                }
            }
            var wlist = supplies_WareHouseRepository.GetList(new RB_Supplies_WareHouse_Extend() { 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)
        {
            //核实提交的商品物料里是否存在
            string GoodsIds = string.Join(",", demodel.DetailList.Select(x => x.GoodsId).Distinct());
            var mList = supplies_MaterialRepository.GetList(new RB_Supplies_Material_Extend() { 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;
            }
            demodel.TotalCostMoney = demodel.DetailList.Sum(x => x.CostMoney ?? 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;

            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
                        }, trans);
                    }
                    //生成采购财务单

                }
            }
            catch (Exception)
            {

                throw;
            }
            

            return "";
        }

        #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 = "[]";
                }
                var imglist = JsonConvert.DeserializeObject<List<string>>(item.Images);
                item.ImageList = new List<string>();
                //foreach (var img in imglist)
                //{
                //    item.ImageList.Add(Config.GetFileUrl(img));
                //}
                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;
            }
        }

        #endregion
    }
}
