package com.hotent.base.sqlbuilder;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.hotent.base.model.Column;
import com.hotent.base.query.QueryOP;
import com.hotent.base.util.JsonUtil;
import com.hotent.base.util.StringUtil;





/**
 * <pre>
 * 描述：TODO
 * 构建组：eip平台-base-db
 * 作者：lyj
 * 邮箱:liyj@jee-soft.cn
 * 日期:2014-7-16-下午4:33:40
 * 版权：广州宏天软件有限公司版权所有
 * </pre>
 */
public class KingbaseesSqlBuilder extends AbstractSqlBuilder {

	public KingbaseesSqlBuilder() {
		super();
	}

	@Override
	public String analyzeResultField() {
		StringBuffer sql = new StringBuffer();

		ArrayNode resultField = sqlBuilderModel.getResultField();
		if (resultField == null|| resultField.size()==0) {
			sql.append("* ");
		} else {
			for (int i = 0; i < resultField.size(); i++) {
				JsonNode jo = resultField.get(i);
				String field = jo.get("field").asText();
				String aggFuncOp = jo.get("AggFuncOp").asText();

				sql.append(aggFuncOp);
				sql.append("(" + field + ") ");// 拼装成eg：SELECT
												// count(id_),(dsalias_)
				//判断是否包含大写字母
				String regex = ".*[A-Z]+.*";
				boolean result = field.matches(regex);
				if(result) {
					field = "\"" + field + "\"";
				}
				if (!StringUtil.isEmpty(field)) {
					sql.append(" as " + field + " ");
				}

				if (i < resultField.size() - 1) {// 不是最后一个元素
					sql.append(",");
				}
			}
		}

		return sql.toString();

	}

	@Override
	public void handleDbTypeEqualDate(StringBuffer sql, String field, QueryOP op, Object value, String format) {
		if (op == QueryOP.BETWEEN) {
			ObjectNode value1 = (ObjectNode) value;
			String start = JsonUtil.getString( value1,"start","");
			String end = JsonUtil.getString(value1, "end", "");
			if (StringUtil.isNotEmpty(start)) {
				sql.append(" and " + field + " " + ">=" + " '" + start + "'");
			}
			if (StringUtil.isNotEmpty(end)) {
				sql.append(" and " + field + " " + "<=" + " '" + end + "'");
			}
		} else {
			sql.append(" and " + field + " " + op.op() + " '" + value.toString() + "'");
		}
	}
}
