package cn.estsh.i3plus.pojo.base.dynamic;

import cn.estsh.i3plus.pojo.base.bean.BaseBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.springframework.cglib.beans.BeanGenerator;
import org.springframework.cglib.beans.BeanMap;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @Description : 动态转换对象，用于配合dynamicEntity进行动态属性添加
 * @Reference :
 * @Author : alwaysfrin
 * @CreateDate : 2019-01-23 13:45
 * @Modify:
 **/
public class DynamicBean {

    @ApiParam(value ="目标对象")
    private Object target;

    @ApiParam(value ="属性集合")
    private BeanMap beanMap;

    public DynamicBean(){
    }

    public DynamicBean(Class superclass, Map<String, Class> propertyMap) {
        this.target = generateBean(superclass, propertyMap);
        this.beanMap = BeanMap.create(this.target);
    }


    /**
     * bean 添加属性和值
     *
     * @param property
     * @param value
     */
    public void setValue(String property, Object value) {
        if(!beanMap.containsKey(property)){
            beanMap.put(property, value);
        }
    }

    /**
     * 获取属性值
     *
     * @param property
     * @return
     */
    public Object getValue(String property) {
        return beanMap.get(property);
    }

    /**
     * 获取对象
     *
     * @return
     */
    public Object getTarget() {
        return this.target;
    }


    /**
     * 根据属性生成对象
     *
     * @param superclass
     * @param propertyMap
     * @return
     */
    private Object generateBean(Class superclass, Map<String, Class> propertyMap) {
        BeanGenerator generator =new BeanGenerator();
        if(null != superclass) {
            generator.setSuperclass(superclass);
        }
        BeanGenerator.addProperties(generator, propertyMap);
        return generator.create();
    }
}
