package com.xjrsoft.module.datalog.service.impl;

import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.pictc.jdbc.JdbcTools;
import com.pictc.jdbc.SqlBuilder;
import com.pictc.jdbc.model.JdbcParam;
import com.pictc.jdbc.model.ParamItem;
import com.pictc.jdbc.model.ParamQueryBo;
import com.pictc.jdbc.model.QueryParameter;
import com.pictc.utils.ListUtils;
import com.xjrsoft.module.datalog.service.QueryService;

@Service
public class QueryServiceImpl implements QueryService{

	    public static final String SQL_FIND_SQL = "select sql from lng_sql_rpt where id = ?";
	    
		public String getQuerySql(String queryId) {
			String sql= JdbcTools.queryPrimitive(SQL_FIND_SQL,String.class,ListUtils.ofArray(JdbcParam.of(Types.VARCHAR, String.class, queryId)));
			if(sql.contains("call")) {
				return sql;
			}
			return "SELECT * FROM ("+sql+") t";
		}
	    

	    @Transactional(rollbackFor = Exception.class)
		@Override
		public JSONArray queryList(QueryParameter param) {
			return JdbcTools.query(getQuerySql(param.getQueryId()),param);
		}


	    @Transactional(rollbackFor = Exception.class)
		@Override
		public IPage<JSONObject> queryPage(QueryParameter param) {
			return JdbcTools.queryPage(getQuerySql(param.getQueryId()), param);
		}

	    @Transactional(rollbackFor = Exception.class)
		@Override
		public JSONArray queryParamsList(ParamQueryBo param) {
			SqlBuilder sql = new SqlBuilder();
			sql.append(getQuerySql(param.getQueryId()));
			List<ParamItem> params2 = param.getParams();
			List<JdbcParam> params = new ArrayList<JdbcParam>();
			if(params2!=null && !params2.isEmpty()) {
				for (ParamItem item : params2) {
					params.add(item.toParam());
				}
			}
			return JdbcTools.queryArray(sql.toString(), params);
		}

}
