package com.ruoyi.erp.request;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import java.util.Collection;
import java.util.List;

/**
 * 创建商品（批量）请求
 *
 * 对应接口：POST /api/open/product/batchCreate
 * 限制：每批次最多50个商品
 */
public class ProductBatchCreateRequest extends ERPRequestBase {
	public ProductBatchCreateRequest(IERPAccount erpAccount) {
		super("https://open.goofish.pro/api/open/product/batchCreate", erpAccount);
	}

	/**
	 * 设置一批商品数据，覆盖已有的 product_data
	 */
	public void setProducts(Collection<ProductBuilder> products) {
		ensureRequestBodyInitialized();
		if (products == null || products.isEmpty()) {
			throw new IllegalArgumentException("product_data不能为空");
		}
		if (products.size() > 50) {
			throw new IllegalArgumentException("每批次最多创建50个商品");
		}
		JSONArray array = new JSONArray();
		for (ProductBuilder builder : products) {
			array.add(builder.build());
		}
		this.requestBody.put("product_data", array);
	}

	/**
	 * 在原有 product_data 基础上追加一个商品
	 */
	public void addProduct(ProductBuilder product) {
		ensureRequestBodyInitialized();
		JSONArray array = this.requestBody.getJSONArray("product_data");
		if (array == null) {
			array = new JSONArray();
			this.requestBody.put("product_data", array);
		}
		if (array.size() >= 50) {
			throw new IllegalStateException("每批次最多创建50个商品");
		}
		array.add(product.build());
	}

	private void ensureRequestBodyInitialized() {
		if (this.requestBody == null) {
			this.requestBody = new JSONObject();
		}
	}

	/**
	 * 单个商品数据构建器
	 */
	public static class ProductBuilder {
		private final JSONObject data = new JSONObject();
		private final JSONArray channelPv = new JSONArray();
		private final JSONArray publishShop = new JSONArray();
		private final JSONArray skuItems = new JSONArray();

		public ProductBuilder setItemKey(String itemKey) {
			data.put("item_key", itemKey);
			return this;
		}

		public ProductBuilder setItemBizType(int itemBizType) {
			data.put("item_biz_type", itemBizType);
			return this;
		}

		public ProductBuilder setSpBizType(int spBizType) {
			data.put("sp_biz_type", spBizType);
			return this;
		}

		public ProductBuilder setChannelCatId(String channelCatId) {
			data.put("channel_cat_id", channelCatId);
			return this;
		}

		public ProductBuilder setPrice(long price) {
			data.put("price", price);
			return this;
		}

		public ProductBuilder setOriginalPrice(Long originalPrice) {
			if (originalPrice != null) {
				data.put("original_price", originalPrice);
			}
			return this;
		}

		public ProductBuilder setExpressFee(Long expressFee) {
			if (expressFee != null) {
				data.put("express_fee", expressFee);
			}
			return this;
		}

		public ProductBuilder setStock(int stock) {
			data.put("stock", stock);
			return this;
		}

		public ProductBuilder setOuterId(String outerId) {
			if (outerId != null) {
				data.put("outer_id", outerId);
			}
			return this;
		}

		public ProductBuilder setStuffStatus(Integer stuffStatus) {
			if (stuffStatus != null) {
				data.put("stuff_status", stuffStatus);
			}
			return this;
		}

		public ProductBuilder addChannelPv(String propertyId, String propertyName, String valueId, String valueName) {
			JSONObject pv = new JSONObject();
			pv.put("property_id", propertyId);
			pv.put("property_name", propertyName);
			pv.put("value_id", valueId);
			pv.put("value_name", valueName);
			channelPv.add(pv);
			return this;
		}

		public ProductBuilder addPublishShop(String userName, int province, int city, int district, String title, String content, List<String> images, String whiteImages, String serviceSupport) {
			JSONObject shop = new JSONObject();
			shop.put("user_name", userName);
			shop.put("province", province);
			shop.put("city", city);
			shop.put("district", district);
			shop.put("title", title);
			shop.put("content", content);
			if (images != null && !images.isEmpty()) {
				JSONArray imgs = new JSONArray();
				imgs.addAll(images);
				shop.put("images", imgs);
			}
			if (whiteImages != null) {
				shop.put("white_images", whiteImages);
			}
			if (serviceSupport != null) {
				shop.put("service_support", serviceSupport);
			}
			publishShop.add(shop);
			return this;
		}

		public ProductBuilder addSkuItem(long price, int stock, String skuText, String outerId) {
			JSONObject sku = new JSONObject();
			sku.put("price", price);
			sku.put("stock", stock);
			sku.put("sku_text", skuText);
			if (outerId != null) {
				sku.put("outer_id", outerId);
			}
			skuItems.add(sku);
			return this;
		}

		public ProductBuilder setDetailImages(JSONArray images) {
			if (images != null) {
				data.put("detail_images", images);
			}
			return this;
		}

		public ProductBuilder setSkuImages(JSONArray images) {
			if (images != null) {
				data.put("sku_images", images);
			}
			return this;
		}

		public ProductBuilder setBookData(JSONObject bookData) { return putIfNotNull("book_data", bookData); }
		public ProductBuilder setFoodData(JSONObject foodData) { return putIfNotNull("food_data", foodData); }
		public ProductBuilder setReportData(JSONObject reportData) { return putIfNotNull("report_data", reportData); }
		public ProductBuilder setFlashSaleType(Integer flashSaleType) { if (flashSaleType != null) data.put("flash_sale_type", flashSaleType); return this; }
		public ProductBuilder setAdventData(JSONObject adventData) { return putIfNotNull("advent_data", adventData); }
		public ProductBuilder setInspectData(JSONObject inspectData) { return putIfNotNull("inspect_data", inspectData); }
		public ProductBuilder setBrandData(JSONObject brandData) { return putIfNotNull("brand_data", brandData); }

		private ProductBuilder putIfNotNull(String key, Object value) {
			if (value != null) {
				data.put(key, value);
			}
			return this;
		}

		private void finalizeArrays() {
			if (!channelPv.isEmpty()) {
				data.put("channel_pv", channelPv);
			}
			if (!publishShop.isEmpty()) {
				data.put("publish_shop", publishShop);
			}
			if (!skuItems.isEmpty()) {
				data.put("sku_items", skuItems);
			}
		}

		private void validateRequired() {
			if (!data.containsKey("item_key")) throw new IllegalStateException("缺少必填字段: item_key");
			if (!data.containsKey("item_biz_type")) throw new IllegalStateException("缺少必填字段: item_biz_type");
			if (!data.containsKey("sp_biz_type")) throw new IllegalStateException("缺少必填字段: sp_biz_type");
			if (!data.containsKey("channel_cat_id")) throw new IllegalStateException("缺少必填字段: channel_cat_id");
			if (!data.containsKey("price")) throw new IllegalStateException("缺少必填字段: price");
			if (!data.containsKey("stock")) throw new IllegalStateException("缺少必填字段: stock");
			if (publishShop.isEmpty()) throw new IllegalStateException("缺少必填字段: publish_shop");
		}

		private JSONObject build() {
			finalizeArrays();
			validateRequired();
			return data;
		}
	}
}


