package net.wicp.tams.duckula.ops.convert;

import java.io.Serializable;

import org.apache.commons.beanutils.PropertyUtils;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;

import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.common.apiext.StringUtil;
import net.wicp.tams.common.callback.IConvertValue;

/***
 * 从数据库拿到解释(先只支持mysql),只支持主键为一个字段
 * 
 * @author Administrator
 *
 */
@Slf4j
public class ConvertValueMyBatis implements IConvertValue<Serializable> {
	private final BaseMapper<?> baseMapper;
	private final String retColNames;

	public ConvertValueMyBatis(BaseMapper<?> baseMapper, String retColNames) {
		this.baseMapper = baseMapper;
		this.retColNames = retColNames;
	}

	@Override
	public String getStr(Serializable keyObj) {
		if (StringUtil.isNull(keyObj)) {
			return "";
		}
		Object selectObj = this.baseMapper.selectById(keyObj);
		if (selectObj == null) {
			return "";
		}
		try {
			StringBuffer buff = new StringBuffer();
			for (String retColName : retColNames.split(",")) {
				buff.append("^" + PropertyUtils.getProperty(selectObj, retColName));
			}
			return buff.substring(1);
		} catch (Exception e) {
			log.error("错误取字段", e);
		}
		return "";
	}
}
