package cc.smtweb.framework.core.db.impl;

import cc.smtweb.framework.core.common.SwEnum;
import cc.smtweb.framework.core.db.cache.ModelTableCache;
import cc.smtweb.framework.core.db.vo.ModelField;
import cc.smtweb.framework.core.db.vo.ModelTable;
import cc.smtweb.framework.core.exception.SwException;
import cc.smtweb.framework.core.util.DateUtil;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;

/**
 * Created by Akmm at 14-1-2 上午11:19
 * 实体bean抽象类
 */
public class DefaultEntity extends BaseBean implements Serializable, Cloneable {
    //表名
    public final static String tableNameKey = "_def_table_name";
    public final static String statusKey = "_status";

    public DefaultEntity() {
    }

    public DefaultEntity(String _def_table_name) {
        this.put(tableNameKey, _def_table_name);
    }

    public ModelTable getModelTable() {
        return ModelTableCache.getInstance().getByName(getTableName());
    }

    public String getTableName() {
        return getStr(tableNameKey);
    }

    public void setTableName(String tableName) {
        put(tableNameKey, tableName);
    }

    public void setIsNew(boolean isNew) {
        put(statusKey, isNew);
    }

    public boolean isNew() {
        return getBool(statusKey) || getEntityId() <= 0L;
    }

    public void removeStatus() {
        data.remove(statusKey);
    }

    //根据实体定义，设默认值
    public void init() {
        ModelTable entity = getModelTable();
        if (entity == null) return;
        String pkField = getPkFieldName();
        for (ModelField field : entity.getFields()) {
            if (data.containsKey(field.getName())) continue;//有值了，不能动
            if (field.getName().equalsIgnoreCase(pkField)) continue;//是pk，不要初始化
            if (field.getFieldType() == SwEnum.FieldType.CREATE_TIME.value || field.getFieldType() == SwEnum.FieldType.LAST_TIME.value) {
                put(field.getName(), DateUtil.nowDateTimeLong());
            } else {
                String s = field.getDefaultValue();
                if (StringUtils.isNotEmpty(s)) {
                    put(field.getName(), SwEnum.DataType.getDataValue(field.getDataType(), s));
                }
            }
        }
    }

    /**
     * 主键字段
     */
    public String getPkFieldName() {
        return getModelTable().getIdField();
    }

    public long getEntityId() {
        return getLong(getPkFieldName());
    }

    public void setEntityId(long id) {
        data.put(getPkFieldName(), id);
    }

    @Override
    public DefaultEntity clone() {
        try {
            DefaultEntity bean = (DefaultEntity) super.clone();
            bean.getData().remove(getPkFieldName());
            return bean;
        } catch (CloneNotSupportedException e) {
            throw new SwException(e);
        }
    }
}
