package com.engine.common.cmd;

import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.common.util.DbTools;
import com.engine.core.interceptor.CommandContext;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import weaver.general.Util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class QueryCommonCmd extends AbstractCommonCommand<Map<String,Object>> {

    public QueryCommonCmd(Map<String,Object> params){
        this.params=params;
    }
    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        Map<String,Object> resultMap = new HashMap<>();
        String action = Util.null2String(params.get("action"));
        String mark = Util.null2String(params.get("mark"));
        String condition = Util.null2String(params.get("condition"));
        String sql = "select sentence from uf_sqltool where action =? and mark =?";
        String sentenceSql = DbTools.getSql(sql,action,mark);
        String conditionSql = "";
        String[] conditions = condition.split(",");
        Object[] objs = new Object[conditions.length];
        int i = 0;
        for (String str :conditions){
            conditionSql = conditionSql +" "+ str.split(":")[0]+"=? and";
            objs[i] = str.split(":")[1];
            i++;
        }
        if (!"".equals(conditionSql)){
            conditionSql = conditionSql.substring(0,conditionSql.length()-3);
            sentenceSql = sentenceSql +" where "+ conditionSql;
        }
        log.info("sql : [{}]",sentenceSql);
        log.info("objs : [{}]",objs);
        List<Map<String,Object>> lists = DbTools.getSqlToList(sentenceSql,objs);

        resultMap.put("data",lists);
        return resultMap;
    }
}
