package com.uas.search.console.util;

import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.DoubleField;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.LongField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.uas.search.console.model.BrandSimpleInfo;
import com.uas.search.console.model.ComponentSimpleInfo;
import com.uas.search.console.model.KindSimpleInfo;
import com.uas.search.console.model.OrderInvoiceSimpleInfo;
import com.uas.search.console.model.OrderSimpleInfo;
import com.uas.search.console.model.PropertyValueSimpleInfo;
import com.uas.search.console.model.PurchaseInvoiceSimpleInfo;
import com.uas.search.console.model.PurchaseSimpleInfo;

import net.sf.ehcache.search.SearchException;

/**
 * 将对象转换为Document的工具类
 * 
 * @author sunyj
 * @since 2016年10月17日 上午11:32:19
 */
public class ObjectToDocumentUtils {

	/**
	 * 将对象转为Document
	 * 
	 * @param object
	 *            对象，可为KindSimpleInfo、BrandSimpleInfo、ComponentSimpleInfo、
	 *            OrderSimpleInfo、OrderInvoiceSimpleInfo、PurchaseSimpleInfo、
	 *            PurchaseInvoiceSimpleInfo
	 * 
	 * @return 转换的Document
	 */
	public static Document toDocument(Object object) {
		if (object == null) {
			return null;
		}
		if (object instanceof KindSimpleInfo) {
			return toDocument((KindSimpleInfo) object);
		} else if (object instanceof BrandSimpleInfo) {
			return toDocument((BrandSimpleInfo) object);
		} else if (object instanceof ComponentSimpleInfo) {
			return toDocument((ComponentSimpleInfo) object);
		} else if (object instanceof OrderSimpleInfo) {
			return toDocument((OrderSimpleInfo) object);
		} else if (object instanceof OrderInvoiceSimpleInfo) {
			return toDocument((OrderInvoiceSimpleInfo) object);
		} else if (object instanceof PurchaseSimpleInfo) {
			return toDocument((PurchaseSimpleInfo) object);
		} else if (object instanceof PurchaseInvoiceSimpleInfo) {
			return toDocument((PurchaseInvoiceSimpleInfo) object);
		} else {
			throw new SearchException("不支持将以下类型转换为Document：" + object.getClass().getName());
		}
	}

	/**
	 * KindSimpleInfo对象转为Document
	 * 
	 * @param kind
	 * @return
	 */
	public static Document toDocument(KindSimpleInfo kind) {
		if (kind == null || kind.getId() == null || StringUtils.isEmpty(kind.getNameCn()) || kind.getIsLeaf() == null
				|| kind.getLevel() == null) {
			return null;
		}
		Document document = new Document();
		// 不能用LongField，否则后续实时更新索引时，方法updateDocument(new Term("", ""),
		// doc)无法根据id进行更新
		document.add(new StringField(SearchConstants.KIND_ID_FIELD, String.valueOf(kind.getId()), Store.YES));
		document.add(new TextField(SearchConstants.KIND_NAMECN_FIELD, kind.getNameCn(), Store.YES));
		document.add(new StringField(SearchConstants.KIND_ISLEAF_FIELD, String.valueOf(kind.getIsLeaf()), Store.YES));
		document.add(new StringField(SearchConstants.KIND_LEVEL_FIELD, String.valueOf(kind.getLevel()), Store.YES));
		return document;
	}

	/**
	 * BrandSimpleInfo对象转为Document
	 * 
	 * @param brand
	 * @return
	 */
	public static Document toDocument(BrandSimpleInfo brand) {
		if (brand == null || brand.getId() == null || StringUtils.isEmpty(brand.getNameCn())
				|| StringUtils.isEmpty(brand.getUuid())) {
			return null;
		}
		Document document = new Document();
		document.add(new StringField(SearchConstants.BRAND_ID_FIELD, String.valueOf(brand.getId()), Store.YES));
		document.add(new TextField(SearchConstants.BRAND_NAMECN_FIELD, brand.getNameCn(), Store.YES));
		String nameEn = brand.getNameEn();
		if (!StringUtils.isEmpty(nameEn)) {
			document.add(new TextField(SearchConstants.BRAND_NAMEEN_FIELD, nameEn, Store.YES));
		}
		document.add(new StringField(SearchConstants.BRAND_UUID_FIELD, brand.getUuid(), Store.YES));
		return document;
	}

	/**
	 * ComponentSimpleInfo对象转为Document
	 * 
	 * @param component
	 * @return
	 */
	public static Document toDocument(ComponentSimpleInfo component) {
		if (component == null || component.getId() == null || StringUtils.isEmpty(component.getUuid())
				|| StringUtils.isEmpty(component.getCode()) || component.getKindid() == null
				|| component.getBrandid() == null) {
			return null;
		}
		Document document = new Document();
		document.add(new StringField(SearchConstants.COMPONENT_ID_FIELD, String.valueOf(component.getId()), Store.YES));
		document.add(new StringField(SearchConstants.COMPONENT_UUID_FIELD, component.getUuid(), Store.YES));
		// 转小写，以避免分词，又不会因大小写影响搜索
		String code = component.getCode().toLowerCase();
		document.add(new StringField(SearchConstants.COMPONENT_CODE_FIELD, code, Store.YES));
		document.add(new StringField(SearchConstants.COMPONENT_KINDID_FIELD, String.valueOf(component.getKindid()),
				Store.YES));
		document.add(new StringField(SearchConstants.COMPONENT_BRANDID_FIELD, String.valueOf(component.getBrandid()),
				Store.YES));
		if (component.getReserve() != null) {
			document.add(new DoubleField(SearchConstants.COMPONENT_RESERVE_FIELD, component.getReserve(), Store.YES));
		}
		if (component.getSampleQty() != null) {
			document.add(
					new DoubleField(SearchConstants.COMPONENT_SAMPLE_QTY_FIELD, component.getSampleQty(), Store.YES));
		}
		if (component.getOriginalQty() != null) {
			document.add(new DoubleField(SearchConstants.COMPONENT_ORIGINAL_QTY_FIELD, component.getOriginalQty(),
					Store.YES));
		}
		if (component.getInactionStockQty() != null) {
			document.add(new DoubleField(SearchConstants.COMPONENT_INACTION_STOCK_QTY_FIELD,
					component.getInactionStockQty(), Store.YES));
		}

		// 属性值加入索引，索引中field的键："pr_"前缀连接属性的id
		Set<PropertyValueSimpleInfo> propertyValues = component.getProperties();
		for (PropertyValueSimpleInfo propertyValue : propertyValues) {
			if (!StringUtils.isEmpty(propertyValue.getValue())) {
				String fieldKey = SearchConstants.COMPONENT_PROPERTY_PREFIX + propertyValue.getPropertyid();
				document.add(new StringField(fieldKey, propertyValue.getValue(), Store.YES));

				// 另建一份分词的属性索引，用于属性值联想时不区分大小写
				String fieldKeyTokenized = fieldKey + SearchConstants.COMPONENT_PROPERTY_TOKENIZED_SUFFIX;
				document.add(new TextField(fieldKeyTokenized, propertyValue.getValue(), Store.YES));
			}
		}
		return document;
	}

	/**
	 * OrderSimpleInfo对象转为Document
	 * 
	 * @param order
	 *            OrderSimpleInfo对象
	 * @return 转换的Document
	 */
	public static Document toDocument(OrderSimpleInfo order) {
		if (order == null || order.getId() == null || StringUtils.isEmpty(order.getCode()) || order.getBuyeruu() == null
				|| StringUtils.isEmpty(order.getBuyername()) || order.getBuyerEnterprise() == null
				|| order.getBuyerEnterprise().getUu() == null
				|| StringUtils.isEmpty(order.getBuyerEnterprise().getEnName()) || order.getSellerEnterprise() == null
				|| order.getSellerEnterprise().getUu() == null
				|| StringUtils.isEmpty(order.getSellerEnterprise().getEnName()) || order.getCreatetime() == null
				|| order.getStatus() == null) {
			return null;
		}
		Document document = new Document();
		document.add(new StringField(SearchConstants.ORDER_ID_FIELD, String.valueOf(order.getId()), Store.YES));
		// 利用正则搜索，code等不会被分词为多个词的字段存为TextField
		document.add(new TextField(SearchConstants.ORDER_CODE_FIELD, order.getCode(), Store.YES));
		document.add(
				new StringField(SearchConstants.ORDER_BUYERUU_FIELD, String.valueOf(order.getBuyeruu()), Store.YES));
		// 利用正则搜索，name等会被分词为多个词的字段存为StringField（不然会有边界问题，影响准确度）
		document.add(new StringField(SearchConstants.ORDER_BUYERNAME_FIELD, order.getBuyername(), Store.YES));
		document.add(new StringField(SearchConstants.ORDER_BUYERENUU_FIELD,
				String.valueOf(order.getBuyerEnterprise().getUu()), Store.YES));
		document.add(new StringField(SearchConstants.ORDER_BUYERENNAME_FIELD, order.getBuyerEnterprise().getEnName(),
				Store.YES));
		document.add(new StringField(SearchConstants.ORDER_SELLERENUU_FIELD,
				String.valueOf(order.getSellerEnterprise().getUu()), Store.YES));
		document.add(new StringField(SearchConstants.ORDER_SELLERENNAME_FIELD, order.getSellerEnterprise().getEnName(),
				Store.YES));
		document.add(new LongField(SearchConstants.ORDER_CREATETIME_FIELD, order.getCreatetime().getTime(), Store.YES));
		document.add(new StringField(SearchConstants.ORDER_STATUS_FIELD, String.valueOf(order.getStatus()), Store.YES));
		// 明细以json的格式存储
		if (!CollectionUtils.isEmpty(order.getDetails())) {
			document.add(new TextField(SearchConstants.ORDER_DETAILS_FIELD, JSONObject.toJSONString(order.getDetails()),
					Store.YES));
		}
		return document;
	}

	/**
	 * OrderInvoiceSimpleInfo对象转为Document
	 * 
	 * @param orderInvoice
	 *            OrderInvoiceSimpleInfo对象
	 * @return 转换的Document
	 */
	public static Document toDocument(OrderInvoiceSimpleInfo orderInvoice) {
		if (orderInvoice == null || orderInvoice.getId() == null || StringUtils.isEmpty(orderInvoice.getCode())
				|| orderInvoice.getBuyeruu() == null || StringUtils.isEmpty(orderInvoice.getBuyername())
				|| orderInvoice.getBuyerEnterprise() == null || orderInvoice.getBuyerEnterprise().getUu() == null
				|| StringUtils.isEmpty(orderInvoice.getBuyerEnterprise().getEnName())
				|| orderInvoice.getCreatetime() == null || orderInvoice.getStatus() == null) {
			return null;
		}
		Document document = new Document();
		document.add(new StringField(SearchConstants.ORDER_INVOICE_ID_FIELD, String.valueOf(orderInvoice.getId()),
				Store.YES));
		document.add(new TextField(SearchConstants.ORDER_INVOICE_CODE_FIELD, orderInvoice.getCode(), Store.YES));
		document.add(new StringField(SearchConstants.ORDER_INVOICE_BUYERUU_FIELD,
				String.valueOf(orderInvoice.getBuyeruu()), Store.YES));
		document.add(
				new StringField(SearchConstants.ORDER_INVOICE_BUYERNAME_FIELD, orderInvoice.getBuyername(), Store.YES));
		document.add(new StringField(SearchConstants.ORDER_INVOICE_BUYERENUU_FIELD,
				String.valueOf(orderInvoice.getBuyerEnterprise().getUu()), Store.YES));
		document.add(new StringField(SearchConstants.ORDER_INVOICE_BUYERENNAME_FIELD,
				orderInvoice.getBuyerEnterprise().getEnName(), Store.YES));
		document.add(new LongField(SearchConstants.ORDER_INVOICE_CREATETIME_FIELD,
				orderInvoice.getCreatetime().getTime(), Store.YES));
		document.add(new StringField(SearchConstants.ORDER_INVOICE_STATUS_FIELD,
				String.valueOf(orderInvoice.getStatus()), Store.YES));
		if (!CollectionUtils.isEmpty(orderInvoice.getDetails())) {
			document.add(new TextField(SearchConstants.ORDER_INVOICE_DETAILS_FIELD,
					JSONObject.toJSONString(orderInvoice.getDetails()), Store.YES));
		}
		return document;
	}

	/**
	 * PurchaseSimpleInfo对象转为Document
	 * 
	 * @param order
	 *            PurchaseSimpleInfo对象
	 * @return 转换的Document
	 */
	public static Document toDocument(PurchaseSimpleInfo purchase) {
		if (purchase == null || purchase.getId() == null || StringUtils.isEmpty(purchase.getCode())
				|| purchase.getSellerenuu() == null || StringUtils.isEmpty(purchase.getSellerenname())
				|| purchase.getCreatetime() == null || purchase.getStatus() == null) {
			return null;
		}
		Document document = new Document();
		document.add(new StringField(SearchConstants.PURCHASE_ID_FIELD, String.valueOf(purchase.getId()), Store.YES));
		document.add(new TextField(SearchConstants.PURCHASE_CODE_FIELD, purchase.getCode(), Store.YES));
		document.add(new StringField(SearchConstants.PURCHASE_SELLERENUU_FIELD,
				String.valueOf(purchase.getSellerenuu()), Store.YES));
		document.add(
				new StringField(SearchConstants.PURCHASE_SELLERENNAME_FIELD, purchase.getSellerenname(), Store.YES));
		document.add(new LongField(SearchConstants.PURCHASE_CREATETIME_FIELD, purchase.getCreatetime().getTime(),
				Store.YES));
		document.add(new StringField(SearchConstants.PURCHASE_STATUS_FIELD, String.valueOf(purchase.getStatus()),
				Store.YES));
		if (!CollectionUtils.isEmpty(purchase.getDetails())) {
			document.add(new TextField(SearchConstants.PURCHASE_DETAILS_FIELD,
					JSONObject.toJSONString(purchase.getDetails()), Store.YES));
		}
		return document;
	}

	/**
	 * PurchaseInvoiceSimpleInfo对象转为Document
	 * 
	 * @param purchaseInvoice
	 *            PurchaseInvoiceSimpleInfo对象
	 * @return 转换的Document
	 */
	public static Document toDocument(PurchaseInvoiceSimpleInfo purchaseInvoice) {
		if (purchaseInvoice == null || purchaseInvoice.getId() == null || StringUtils.isEmpty(purchaseInvoice.getCode())
				|| purchaseInvoice.getSellerenuu() == null || StringUtils.isEmpty(purchaseInvoice.getSellerenname())
				|| purchaseInvoice.getCreatetime() == null || purchaseInvoice.getStatus() == null) {
			return null;
		}
		Document document = new Document();
		document.add(new StringField(SearchConstants.PURCHASE_INVOICE_ID_FIELD, String.valueOf(purchaseInvoice.getId()),
				Store.YES));
		document.add(new TextField(SearchConstants.PURCHASE_INVOICE_CODE_FIELD, purchaseInvoice.getCode(), Store.YES));
		document.add(new StringField(SearchConstants.PURCHASE_INVOICE_SELLERENUU_FIELD,
				String.valueOf(purchaseInvoice.getSellerenuu()), Store.YES));
		document.add(new StringField(SearchConstants.PURCHASE_INVOICE_SELLERENNAME_FIELD,
				purchaseInvoice.getSellerenname(), Store.YES));
		document.add(new LongField(SearchConstants.PURCHASE_INVOICE_CREATETIME_FIELD,
				purchaseInvoice.getCreatetime().getTime(), Store.YES));
		document.add(new StringField(SearchConstants.PURCHASE_INVOICE_STATUS_FIELD,
				String.valueOf(purchaseInvoice.getStatus()), Store.YES));
		if (!CollectionUtils.isEmpty(purchaseInvoice.getDetails())) {
			document.add(new TextField(SearchConstants.PURCHASE_INVOICE_DETAILS_FIELD,
					JSONObject.toJSONString(purchaseInvoice.getDetails()), Store.YES));
		}
		return document;
	}

}
