package cn.ibizlab.core.data.model;

import cn.ibizlab.util.helper.DataObject;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Getter
@Setter
@NoArgsConstructor
@Accessors(chain = true)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonIgnoreProperties(ignoreUnknown = true)
public class PojoProperty
{

	@JSONField(ordinal = 1)
	private String code;

	@JSONField(ordinal = 2)
	private String name;

	@JSONField(ordinal = 3)
	private Boolean required;

	@JSONField(ordinal = 4)
	private PojoModel.PropertyType propertyType;

	@JSONField(ordinal = 5)
	private Boolean uniqueKeys;

	@JSONField(ordinal = 6)
	private String dict;

	@JSONField(ordinal = 7)
	private String defaultValue;

	public String getDefaultValue()
	{
		if(defaultValue!=null&&defaultValue.equalsIgnoreCase("now"))
			return DataObject.dayFormat.format(new Date());
		return DataObject.getStringValue(defaultValue,"");
	}

	@JSONField(ordinal = 8)
	private PojoModel model;

	@JSONField(ordinal = 9)
	private Map<String, Object> extensions;

	public PojoModel getModel()
	{
		if (propertyType != null && propertyType.equals(PojoModel.PropertyType.recursion) && ownerModel != null) {
			model = JSON.toJavaObject(JSON.parseObject(JSON.toJSONString(ownerModel)), PojoModel.class);
			if(model!=null&&model.getProperties()!=null)
				model.getPropertyList().forEach(prop->prop.setParentProperty(this));
		}
		return model;

	}

	public PojoProperty setModel(PojoModel model)
	{
		if(model!=null&&model.getProperties()!=null)
			model.getPropertyList().forEach(prop->prop.setParentProperty(this));
		this.model=model;
		return this;
	}


	@JSONField(serialize = false)
	@JsonIgnore
	private PojoModel ownerModel;

	@JSONField(serialize = false)
	@JsonIgnore
	private PojoProperty parentProperty;

	@JSONField(serialize = false)
	@JsonIgnore
	public String getTag()
	{
		List<PojoProperty> list=new ArrayList<>();
		PojoProperty prop=this.getParentProperty();
		while (prop!=null)
		{
			list.add(prop);
			prop=prop.getParentProperty();
		}
		String tag="";
		for(int i=list.size()-1;i>=0;i--)
			tag=tag+list.get(i).getCode()+".";
		tag+=code;
		return tag;
	}


}