package com.artfess.base.filter;



import com.artfess.base.constants.SQLConst;
import com.artfess.base.interceptor.ResultSetFilter;
import com.artfess.base.util.SQLUtil;

import java.sql.Clob;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * oracle 下查询结果 clob 数据格式化处理
 *
 * @author lingpj
 */
public class ClobDataResultSetFilter implements ResultSetFilter {

    @Override
    public void handle(Object obj) {
        if (obj instanceof ArrayList) {
            ArrayList<HashMap<String, Object>> arrayList = (ArrayList<HashMap<String, Object>>) obj;
            for (HashMap<String, Object> data : arrayList) {
                // 转换 clob 类型
                if (data instanceof HashMap) {
                    for (String key : data.keySet()) {
                        if (data.get(key) instanceof Clob) {
                            Clob clob = (Clob) data.get(key);
							try {
								data.put(key, clob.getSubString(1, (int) clob.length()));
							} catch (SQLException e) {
								e.printStackTrace();
							}
                        }
                    }
                }
            }
        }
    }

    @Override
    public boolean support(String id, String sql, List<String> tableNames) {
        String dbType = SQLUtil.getDbType();
        // oracle 数据库下 和 达梦数据库下
        if (SQLConst.DB_ORACLE.equals(dbType) || SQLConst.DB_DM.equals(dbType)) {
            // 拦截查询列表
            List<String> mappedStatementIds = new ArrayList<>();
            //  获取已办事宜
            mappedStatementIds.add("com.artfess.bpm.persistence.dao.BpmProcessInstanceDao.getHandledByUserId");
            // 自定义查询
            mappedStatementIds.add("com.artfess.base.dao.CommonDao.query");
            mappedStatementIds.add("com.artfess.base.dao.CommonDao.queryByPage");
            mappedStatementIds.add("com.artfess.base.dao.CommonDao.queryByCustomSql");
            mappedStatementIds.add("com.artfess.base.dao.CommonDao.queryByQueryFilter");
            if (mappedStatementIds.contains(id)) {
                return true;
            }
        }
        return false;
    }

}
