NewSearchproduct.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. /**
  2. * NewSearchproduct.js - Enhanced product search functionality
  3. *
  4. * This script handles the product search and specification management
  5. * for the country price management interface.
  6. */
  7. // Make sure jQuery is available before initializing
  8. (function($) {
  9. // Run when document is ready
  10. $(document).ready(function() {
  11. // Initialize the product specification search functionality
  12. initProductSearch();
  13. // Ensure search input is enabled on page load
  14. $('#specificationSearch').prop('disabled', false);
  15. // Add form validation for price fields
  16. $('form[name="form1"]').on('submit', function(e) {
  17. var hasError = false;
  18. var firstErrorField = null;
  19. // Check country name and area code fields
  20. var $countryName = $('#countryName');
  21. var $countryCode = $('#countryCode');
  22. // Validate country name
  23. if ($countryName.val().trim() === '') {
  24. hasError = true;
  25. $countryName.css('border-color', 'red');
  26. if (!firstErrorField) {
  27. firstErrorField = $countryName;
  28. }
  29. // Show inline error
  30. if ($countryName.next('.field-error').length === 0) {
  31. $countryName.after('<div class="field-error" style="color:red;font-size:12px;margin-top:5px;">国家名称不能为空</div>');
  32. }
  33. } else {
  34. $countryName.css('border-color', '');
  35. $countryName.next('.field-error').remove();
  36. }
  37. // Validate area code
  38. if ($countryCode.val().trim() === '') {
  39. hasError = true;
  40. $countryCode.css('border-color', 'red');
  41. if (!firstErrorField) {
  42. firstErrorField = $countryCode;
  43. }
  44. // Show inline error
  45. if ($countryCode.next('.field-error').length === 0) {
  46. $countryCode.after('<div class="field-error" style="color:red;font-size:12px;margin-top:5px;">区号不能为空</div>');
  47. }
  48. } else {
  49. $countryCode.css('border-color', '');
  50. $countryCode.next('.field-error').remove();
  51. }
  52. // Check all price fields
  53. $('input[name="spec_price[]"]').each(function() {
  54. var price = $(this).val().trim();
  55. if (price === '' || price === '0' || parseFloat(price) <= 0) {
  56. hasError = true;
  57. $(this).css('border-color', 'red');
  58. // Store reference to first error field for scrolling
  59. if (!firstErrorField) {
  60. firstErrorField = $(this);
  61. }
  62. // Find product and spec name for error message
  63. var $specItem = $(this).closest('.specitem');
  64. var productName = $specItem.prevAll('.product-header').first().text().trim();
  65. var specName = $specItem.find('.spec-name').text().trim();
  66. // Show inline error under the field
  67. var $errorMsg = $('<div class="price-error" style="color:red;font-size:12px;margin-top:5px;">售价不能为0或空白</div>');
  68. $specItem.find('.price-error').remove();
  69. $(this).after($errorMsg);
  70. } else {
  71. $(this).css('border-color', '');
  72. $(this).next('.price-error').remove();
  73. }
  74. });
  75. if (hasError) {
  76. e.preventDefault();
  77. // Create appropriate error message
  78. var errorMessage = '错误:';
  79. if ($countryName.val().trim() === '' || $countryCode.val().trim() === '') {
  80. errorMessage += '国家名称和区号不能为空!';
  81. }
  82. // Check if there are price errors
  83. var hasPriceErrors = false;
  84. $('input[name="spec_price[]"]').each(function() {
  85. var price = $(this).val().trim();
  86. if (price === '' || price === '0' || parseFloat(price) <= 0) {
  87. hasPriceErrors = true;
  88. return false; // Break the loop
  89. }
  90. });
  91. if (hasPriceErrors) {
  92. if (errorMessage !== '错误:') {
  93. errorMessage += '\n\n';
  94. }
  95. errorMessage += '部分产品规格的售价为0或空白,请检查并填写所有售价!';
  96. }
  97. alert(errorMessage);
  98. // Scroll to first error field
  99. if (firstErrorField) {
  100. $('html, body').animate({
  101. scrollTop: firstErrorField.offset().top - 100
  102. }, 500);
  103. }
  104. return false;
  105. }
  106. return true;
  107. });
  108. });
  109. /**
  110. * Initialize the product search functionality
  111. */
  112. function initProductSearch() {
  113. var $searchInput = $('#specificationSearch');
  114. var $resultsList = $('#specificationlist');
  115. var searchTimeout;
  116. // Product search input keyup event with debounce
  117. $searchInput.on('keyup', function() {
  118. var keyword = $(this).val().trim();
  119. // Clear previous timeout to implement debounce
  120. clearTimeout(searchTimeout);
  121. // Hide results and return if search term is too short
  122. if (keyword.length < 2) {
  123. $resultsList.find('ul').empty();
  124. $resultsList.hide();
  125. return;
  126. }
  127. // Set a timeout to prevent too many requests
  128. searchTimeout = setTimeout(function() {
  129. // Show loading indicator
  130. $resultsList.find('ul').html('<li class="search-loading">正在搜索产品...</li>');
  131. $resultsList.show();
  132. // Make AJAX request to search products
  133. $.ajax({
  134. url: 'ajax_search_products_for_spec.php',
  135. type: 'POST',
  136. data: {keyword: keyword},
  137. dataType: 'html',
  138. success: function(data) {
  139. // Check for session errors in the response
  140. if (data.indexOf('session') !== -1 && data.indexOf('Notice') !== -1) {
  141. console.warn("Session notice detected in response. This may be harmless.");
  142. }
  143. $resultsList.find('ul').html(data);
  144. // Show or hide results based on content
  145. if ($resultsList.find('ul li').length > 0) {
  146. $resultsList.show();
  147. } else {
  148. $resultsList.hide();
  149. }
  150. },
  151. error: function(xhr, status, error) {
  152. console.error("Search error:", error);
  153. $resultsList.find('ul').html('<li class="search-error">搜索失败,请重试</li>');
  154. }
  155. });
  156. }, 300); // 300ms debounce
  157. });
  158. // Show search results when input is focused (if results exist and search term is valid)
  159. $searchInput.on('focus', function() {
  160. var keyword = $(this).val().trim();
  161. if (keyword.length >= 2 && $resultsList.find('ul li').length > 0) {
  162. $resultsList.show();
  163. }
  164. });
  165. // Handle product selection from search results
  166. $(document).on('click', '#specificationlist ul li', function() {
  167. if ($(this).hasClass('search-loading') || $(this).hasClass('search-error')) {
  168. return; // Don't process clicks on loading or error messages
  169. }
  170. var $this = $(this);
  171. var productId = $this.data('product-id');
  172. // Skip if no product ID was found
  173. if (!productId) {
  174. console.error("No product ID found");
  175. return;
  176. }
  177. var productName = $this.data('product-name');
  178. var categoryName = $this.data('category-name');
  179. var productUnit = $this.data('unit');
  180. // Check if product is already added
  181. if ($('.specifications .product-header:contains("' + productName + '")').length > 0) {
  182. alert('该产品已添加!');
  183. return;
  184. }
  185. // Hide results and show loading state
  186. $resultsList.hide();
  187. $searchInput.val('正在加载产品规格...').prop('disabled', true);
  188. // Fetch product specifications
  189. $.ajax({
  190. url: 'ajax_get_product_specifications.php',
  191. type: 'POST',
  192. data: {product_id: productId},
  193. dataType: 'html',
  194. success: function(data) {
  195. // Check for session errors in the response
  196. if (data.indexOf('session') !== -1 && data.indexOf('Notice') !== -1) {
  197. console.warn("Session notice detected in response. This may be harmless.");
  198. // Try to extract the actual content after the notice
  199. data = data.substring(data.indexOf('</p>') + 4);
  200. }
  201. // Check if we received an error message about no specifications
  202. if (data.indexOf('没有规格信息') !== -1) {
  203. alert('该产品没有规格信息,请先在产品管理中添加规格');
  204. $searchInput.val('').prop('disabled', false);
  205. return;
  206. }
  207. // Create product header
  208. var categoryDisplay = categoryName ? ' <span class="category-tag">(' + categoryName + ')</span>' : '';
  209. var productHeader = $('<div class="product-header">' + productName + categoryDisplay + '</div>');
  210. // Append product header and specifications
  211. $('.specifications').append(productHeader);
  212. $('.specifications').append(data);
  213. // Make sure price fields are empty and don't have placeholders
  214. var $lastHeader = $('.specifications .product-header:last');
  215. $lastHeader.nextUntil('.product-header', '.specitem').find('input[name="spec_price[]"]').attr('placeholder', '').val('');
  216. // Reset search input
  217. $searchInput.val('').prop('disabled', false);
  218. },
  219. error: function(xhr, status, error) {
  220. console.error("Error loading specifications:", error);
  221. alert('加载产品规格失败,请重试');
  222. $searchInput.val('').prop('disabled', false);
  223. },
  224. complete: function() {
  225. // Always make sure search input is re-enabled
  226. setTimeout(function() {
  227. $searchInput.prop('disabled', false);
  228. }, 500);
  229. }
  230. });
  231. });
  232. // Delete specification when delete button is clicked
  233. $(document).on('click', '.specdelete', function() {
  234. // if (!confirm('确定要删除此规格吗?')) {
  235. // return;
  236. // }
  237. var $specItem = $(this).closest('.specitem');
  238. var $productHeader = $specItem.prevAll('.product-header').first();
  239. // Remove specification item
  240. $specItem.fadeOut(200, function() {
  241. $(this).remove();
  242. // Check if there are any specifications left for this product
  243. var hasSpecs = false;
  244. $productHeader.nextUntil('.product-header', '.specitem').each(function() {
  245. hasSpecs = true;
  246. return false; // Break the loop
  247. });
  248. // If no specifications left, remove product header
  249. if (!hasSpecs) {
  250. $productHeader.fadeOut(200, function() {
  251. $(this).remove();
  252. });
  253. }
  254. });
  255. });
  256. // Hide search results when clicking outside
  257. $(document).on('click', function(e) {
  258. if (!$(e.target).closest('#specificationSearch, #specificationlist').length) {
  259. $resultsList.hide();
  260. }
  261. });
  262. }
  263. })(jQuery);