public ProductEditorWindow(ProductModel productModel) : this()
 {
     var viewmodel = new ProductEditorViewModel();
     var view = new ProductEditor(viewmodel);
     view.CompleteCommand = this.Close;
     viewmodel.Init();
     view.PrepareProductUi(productModel);
     MainViewGrid.Children.Clear();
     MainViewGrid.Children.Add(view);
 }
 /// <summary>
 /// Products the select.
 /// </summary>
 /// <param name="selectitem">The select item.</param>
 private void ProductSelect(ProductModel selectitem)
 {
     if (null != selectitem)
         _productEditor.PrepareProductUi(selectitem);
 }
 /// <summary>
 /// Servers to local product.
 /// </summary>
 /// <param name="serverModels">The server models.</param>
 /// <param name="itemcount">The item count.</param>
 /// <param name="itemindex">The item index.</param>
 private void ServerToLoalProduct(IEnumerable<FetchProductTemp> serverModels, int itemcount, ref int itemindex)
 {
     foreach (var servermodel in serverModels)
     {
         var localmodel = _productService.GetProductByServerId(servermodel.ServerId);
         if (null == localmodel)
         {
             localmodel = new ProductModel();
             localmodel.Setting = AppLocator.Contenxt;
             localmodel.CreateTime = DateTime.Now;
             localmodel.Status = Status.SyncSuccess;
             _productService.AddProduct(localmodel);
         }
         _productService.FetchProductTempToProductModel(servermodel, localmodel);
         _productService.Save();
         _productViewModel.ProgressValue = 100*(itemindex + 1)/itemcount;
         ++itemindex;
     }
 }
 /// <summary>
 /// Creates the product.
 /// </summary>
 /// <param name="sender">The sender.</param>
 /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
 private void CreateProduct(object sender, RoutedEventArgs e)
 {
     var entity = new ProductModel();
     var pwindow = new ProductEditorWindow(entity);
     pwindow.WTitle = LocalizationSearch.GetString("ProductEditorWindow_CreateProduct");
     pwindow.Show();
 }
 /// <summary>
 /// Initializes the specified view model.
 /// </summary>
 /// <param name="viewModel">The view model.</param>
 private void Init(ProductEditorViewModel viewModel)
 {
     _productEditorViewModel = viewModel;
     this.DataContext = viewModel;
     _productViewModel = ServiceLocator.Current.GetInstance<AllProductViewModel>();
     _productService = ServiceLocator.Current.GetInstance<IProductService>();
     _configService = ServiceLocator.Current.GetInstance<IConfigService>();
     _model = new ProductModel();
     InitializeComponent();
     _redProductBorderStyle = FindResource("RedProductBorder") as Style;
     _productBorderStyle = FindResource("ProductBorder") as Style;
 }
        /// <summary>
        /// Prepares the product UI.
        /// </summary>
        /// <param name="entity">The entity.</param>
        public void PrepareProductUi(ProductModel entity)
        {
            _model = entity;
            _productEditorViewModel.ProductName = entity.ProductName;
            _productEditorViewModel.USwopid = entity.USwopid;
            _productEditorViewModel.ProductMpn = entity.MerchantProductNumber;
            _productEditorViewModel.ProductPrice = entity.Price;
            _productEditorViewModel.Sku = entity.Sku;
            _productEditorViewModel.Gtin = entity.Gtin;
            _productEditorViewModel.ServerId = entity.ServiceId;

            if (entity.ServiceId == 0)
            {
                SeverIdLabel.Visibility = Visibility.Collapsed;
                SeverIdTextBox.Visibility = Visibility.Collapsed;
            }
            else
            {
                SeverIdLabel.Visibility = Visibility.Visible;
                SeverIdTextBox.Visibility = Visibility.Visible;
            }

            if (String.IsNullOrEmpty(entity.USwopid))
            {
                UswopLabel.Visibility = Visibility.Collapsed;
                UswopTextBox.Visibility = Visibility.Collapsed;
            }
            else
            {
                UswopLabel.Visibility = Visibility.Visible;
                UswopTextBox.Visibility = Visibility.Visible;
            }


            TreeItem treeselectitem = null;
            FindTreeItemById(entity.CategoryId, _productEditorViewModel.CategoryItems, ref treeselectitem);
            _productEditorViewModel.CategorySelectedItem = treeselectitem;

            var productimages = _productService.GetProductImageByProdutId(entity.Id);
            FillImage(productimages);
            GetHtmlEditor().BodyInnerHTML = entity.Descript;


            
            //AvailableQuantity
            if (!String.IsNullOrEmpty(entity.AvailableQuantity))
            {
                _productEditorViewModel.SizePropertySelectedItem = entity.ProductInventoryAttributeNameModel;
                var availquan =
                    JsonConvert.DeserializeObject<ObservableCollection<PropertyItem>>(entity.AvailableQuantity);
                foreach (var aq in availquan)
                {
                    SizeWrapPanelChecked(aq.Name);
                }

                //DataGrid update
                _productEditorViewModel.PropertyItems = availquan;
            }

            //Specification Attribute
            if (!String.IsNullOrEmpty(entity.SpecificationAttribute))
            {
                _productEditorViewModel.SelectSpecificationAttribute =
                    _productEditorViewModel.SpecificationAttributes.FirstOrDefault(
                        s => s.Id == entity.SelectSpecificationAttributeId);
                var specificationAttributes =
                    JsonConvert.DeserializeObject<ObservableCollection<SpeAttriItem>>(entity.SpecificationAttribute);
                foreach (var sa in specificationAttributes)
                {
                    SpecificationWrapPanelChecked(sa.Id);
                }

                //DataGrid update
                _productEditorViewModel.SpeAttriItems = specificationAttributes;

            }
        }
        /// <summary>
        /// Verifications the product model.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <returns></returns>
        public IList<string> VerificationProductModel(ProductModel entity)
        {
            var errors = new List<string>();
            if (String.IsNullOrEmpty(entity.ProductName))
                errors.Add("The product name cannot be empty");

            //if (String.IsNullOrEmpty(entity.MerchantProductNumber))
            //   errors.Add("The merchant product number name cannot be empty");

            if (entity.CategoryId == 0)
                errors.Add("The category cannot be empty");

            if (entity.Price == decimal.Zero)
                errors.Add("The price cannot be empty");

            //if (String.IsNullOrEmpty(entity.AvailableQuantity))
            //    errors.Add("The quantity cannot be empty");

            return errors;
        }
        /// <summary>
        /// Prepares the product model.
        /// </summary>
        /// <param name="entity">The entity.</param>
        private void PrepareProductModel(ProductModel entity)
        {
            entity.ProductName = _productEditorViewModel.ProductName;
            entity.USwopid = _productEditorViewModel.USwopid;
            entity.MerchantProductNumber = _productEditorViewModel.ProductMpn;
            entity.Price = _productEditorViewModel.ProductPrice;
            if (null != _productEditorViewModel.CategorySelectedItem)
                entity.CategoryId = _productEditorViewModel.CategorySelectedItem.Id;
            entity.CategoryName = CategoryName.Text;
            entity.Gtin = _productEditorViewModel.Gtin;
            entity.Sku = _productEditorViewModel.Sku;
            FetchImages(entity.ProductImages);
            entity.Descript = GetHtmlEditor().BodyInnerHTML;

            entity.ProductInventoryAttributeNameModel = _productEditorViewModel.SizePropertySelectedItem;
            entity.AvailableQuantity = JsonConvert.SerializeObject(_productEditorViewModel.PropertyItems);

            if (null != _productEditorViewModel.SelectSpecificationAttribute)
                entity.SelectSpecificationAttributeId = _productEditorViewModel.SelectSpecificationAttribute.Id;
            entity.SpecificationAttribute = JsonConvert.SerializeObject(_productEditorViewModel.SpeAttriItems);

            entity.Status = Status.WaitUpload;
            entity.Setting = AppLocator.Contenxt;
            entity.CreateTime = DateTime.Now;
        }
        /// <summary>
        /// Adds the product.
        /// </summary>
        /// <param name="entity">The entity.</param>
        public void AddProduct(ProductModel entity)
        {
            try
            {
                if (entity == null)
                    throw new ArgumentNullException("entity");

                _uswopContext.ProductModels.Add(entity);

                _uswopContext.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                var msg = string.Empty;

                foreach (var validationErrors in dbEx.EntityValidationErrors)
                    foreach (var validationError in validationErrors.ValidationErrors)
                        msg +=
                            string.Format("Property: {0} Error: {1}", validationError.PropertyName,
                                validationError.ErrorMessage) + Environment.NewLine;

                var fail = new Exception(msg, dbEx);
                //Debug.WriteLine(fail.Message, fail);
                throw fail;
            }
        }
        /// <summary>
        /// Products the upload.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <returns></returns>
        public bool ProductSync(ProductModel entity)
        {
            var requestparameter = new FetchProductRequest()
            {
                Accesstoken = AppLocator.Contenxt.Accesstoken,
                ProductId = entity.ServiceId
            };

            var request = new HttpRequestRemote(ApiUrl.Current.FetchProductUrl, requestparameter);
            var response = request.PostResponse<FetchProductResponse>();
            if (response.status != 1)
                return false;

            FetchProductTempToProductModel(response.detail, entity);
            return true;
        }
        /// <summary>
        /// Fetches the product temporary to product model.
        /// </summary>
        /// <param name="server">The server.</param>
        /// <param name="local">The local.</param>
        public void FetchProductTempToProductModel(FetchProductTemp server, ProductModel local)
        {
            local.ServiceId = server.ServerId;
            local.ProductName = server.ProductName;
            local.USwopid = server.USwopid;
            local.MerchantProductNumber = server.MerchantProductNumber;
            local.Sku = server.Sku;
            local.Gtin = server.Gtin;
            local.Descript = server.Descript;
            local.CategoryName = server.CategoryName;
            local.CategoryId = server.CategoryId;
            local.Price = server.Price;
            local.AvailableQuantity = JsonConvert.SerializeObject(server.AvailableQuantity);
            local.SpecificationAttribute = JsonConvert.SerializeObject(server.SpecificationAttribute);
            local.Status = Status.SyncSuccess;
            var attribute = GetProductAttributeNamesbyName(server.SizeName);
            local.ProductInventoryAttributeNameModel = attribute;
            Save();

            var localimages = local.ProductImages;
            var serviceimages = server.ExportProductImages;
            var removeimgs = new List<ProductImage>();
            // clear local image 
            foreach (var limg in localimages)
            {
                var serviceimage = serviceimages.FirstOrDefault(s => s.ServiceId == limg.ServerId);
                if (null == serviceimage)
                {
                    removeimgs.Add(limg);
                }
            }
            foreach (var rimg in removeimgs)
            {
                DeleteProductImage(rimg);
            }



            localimages = local.ProductImages.ToList();
            //Add new image
            foreach (var serviceimage in serviceimages)
            {
                var localimage = localimages.FirstOrDefault(l => l.ServerId == serviceimage.ServiceId);
                if (null != localimage) continue;
                var imgrequest = new HttpRequestRemote(serviceimage.PictureUrl, serviceimage.PictureUrl);
                var imgfilepath = imgrequest.GetFile();
                if (String.IsNullOrEmpty(imgfilepath)) continue;
                local.ProductImages.Add(new ProductImage()
                {
                    ServerId = serviceimage.ServiceId,
                    Path = imgfilepath
                });
            }

            if (local.ProductImages.Count != serviceimages.Count)
            {
                local.Status = Status.SyncFail;
                local.ErrorMsg = "Some Image Download Fail";
            }

            Save();
        }
        /// <summary>
        /// Products the upload.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <returns></returns>
        public ProductResponse ProductUpload(ProductModel entity)
        {
            var setting = AppLocator.Contenxt;
            var requestparameter = new ProductRequest()
            {
                Accesstoken = setting.Accesstoken,
                ProductName = entity.ProductName,
                MerchantProductNumber = entity.MerchantProductNumber,
                CategoryId = entity.CategoryId,
                Price = entity.Price,
                Descript = entity.Descript,
                Gtin = entity.Gtin,
                Sku = entity.Sku,
                UswopId=entity.USwopid
            };

            if (!String.IsNullOrEmpty(entity.AvailableQuantity))
                requestparameter.AvailableQuantity =
                    JsonConvert.DeserializeObject<IList<PropertyItem>>(entity.AvailableQuantity);

            if (null != entity.ProductInventoryAttributeNameModel)
                requestparameter.SizeCategory = entity.ProductInventoryAttributeNameModel.Name;

            if (!String.IsNullOrEmpty(entity.SpecificationAttribute))
                requestparameter.SpecificationAttributes =
                    JsonConvert.DeserializeObject<IList<SpeAttriItem>>(entity.SpecificationAttribute);

            var images = GetProductImageByProdutId(entity.Id);
            var imgsresponse = ImageUpload(images);
            var imageuploadstatus = true;
            if (null == imgsresponse || imgsresponse.status == 0)
            {
                imageuploadstatus = false;
                //image upload fail
                entity.Status = Status.UploadFail;
                entity.ErrorMsg = "Image upload fail";
            }

            requestparameter.Images = String.Join(",",
                entity.ProductImages.Where(pi => pi.ServerId != 0).Select(pi => pi.ServerId));

            var request = new HttpRequestRemote(ApiUrl.Current.EditProductUrl, requestparameter);
            var response = request.PostResponse<ProductResponse>();
            if (response == null || response.status == 0)
            {
                Save();
                return new ProductResponse()
                {
                    status = 400
                };
            }
            if (response.status == 1 && response.detail.code == 1)
            {
                if (imageuploadstatus)
                    entity.Status = Status.UploadSuccess;
                entity.USwopid = response.detail.USwopid;
                entity.ServiceId = response.detail.ServiceId;
                Save();
            }
            else
            {
                entity.Status = Status.UploadFail;
                entity.ErrorMsg = string.Join("\r\n", response.detail.ErrorMsgList);
                Save();
            }
            return response;
        }
 /// <summary>
 /// Deletes the product.
 /// </summary>
 /// <param name="entity">The entity.</param>
 public void DeleteProduct(ProductModel entity)
 {
     _uswopContext.ProductModels.Remove(entity);
     _uswopContext.SaveChanges();
 }