package com;


import com.chinaitop.depot.intelligent.utils.DataPolicyEngine;
import com.chinaitop.depot.intelligent.utils.RedisUtil;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.select.Select;
import net.sf.jsqlparser.util.TablesNamesFinder;
import org.apache.commons.lang.ObjectUtils;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.ReflectorFactory;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;

/**
 * Sql执行时间记录拦截器
 */
@Intercepts({ @Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class, Integer.class })})
@Component
public class DatePermissionInterceptor implements Interceptor {
	
	private static final ObjectFactory DEFAULT_OBJECT_FACTORY = new DefaultObjectFactory();
    private static final ObjectWrapperFactory DEFAULT_OBJECT_WRAPPER_FACTORY = new DefaultObjectWrapperFactory();
    private static final ReflectorFactory DEFAULT_REFLECTOR_FACTORY = new DefaultReflectorFactory();

	@Autowired
	private RedisUtil redisUtil;
	
	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		
		StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        MetaObject metaStatementHandler = MetaObject.forObject(statementHandler, DEFAULT_OBJECT_FACTORY,
                DEFAULT_OBJECT_WRAPPER_FACTORY, DEFAULT_REFLECTOR_FACTORY);
        
        MappedStatement mappedStatement = (MappedStatement) metaStatementHandler.getValue("delegate.mappedStatement");
        
		final BoundSql boundSql = statementHandler.getBoundSql();
		String bouString = boundSql.getSql();// 获取执行sql 
		
		//sql是查询的才进行权限过滤
	    if(mappedStatement.getSqlCommandType().toString().equals("select".toUpperCase())) {
	    
			//通过本地线程获取库id
			Object threadLocalObj = DataPolicyEngine.get();
			String orgId = null;
			if(threadLocalObj != null) {
				orgId = ObjectUtils.toString(threadLocalObj);
			}
			if(orgId!=null) {
				//解析sql中的表名
				Statement statement = CCJSqlParserUtil.parse(bouString);
			    Select selectStatement = (Select)statement;
			    TablesNamesFinder tablesNamesFinder = new TablesNamesFinder();
			    List<String> result = tablesNamesFinder.getTableList(selectStatement);
				
				Set<String> tableNames = new HashSet<String>();// 定义需要替换的table信息列表
				//获取业务表信息数据
				List<String> tableList = (List<String>)redisUtil.lGetAll("tableList").get(0);
				for(int i=0;i<result.size();i++) {
					for (int j = 0; j < tableList.size(); j++) {// 处理查看sql中是否有业务表
						if (result.get(i).equals(ObjectUtils.toString(tableList.get(j)))) {// 是否存在业务表
							tableNames.add(result.get(i));
						}
					}
				}
				
				if (tableNames != null && tableNames.size() > 0) {// sql中存在业务表进行sql拼接数据重新检索
					if(result.size() >= 2) {//sql中存在2张及以上表
						for (String table : tableNames) {// 进行业务表的数据权限替换
							table += " ";//表名后面加空格，防止两个表名一部分相似，导致替换出错
							bouString = bouString.replaceAll(table, "(SELECT * from " + table
									+ " WHERE org_id = '"+orgId+"') ");
						}
					}else {//sql中是单表
						for (String table : tableNames) {// 进行业务表的数据权限替换
							if(bouString.contains(table+" ")) {//防止是单表查询，表后面没有空格的时候替换不了
								table += " ";//表名后面加空格，防止两个表名一部分相似，导致替换出错
							}
							bouString = bouString.replaceAll(table, "(SELECT * from " + table
									+ " WHERE org_id = '"+orgId+"') "+table+" ");
						}
					}
					
					/*bouString = bouString.replaceAll(table, "(SELECT b.* from " + table
							+ " b,user_business u WHERE b.org_id = u.org_id AND u .user_id ='"+userId+"' AND u.business_type = '"+table+"') ");*/
					
				}
				
				//metaStatementHandler.setValue("delegate.boundSql.sql", bouString);
				
				Field field = getField(boundSql, "sql");
				if (field != null) {
					try {
						field.setAccessible(true);
						field.set(boundSql, bouString);
					} catch (IllegalArgumentException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		
	    }
			
		return invocation.proceed();
		

	}

	private static Field getField(Object obj, String fieldName) {
		Field field = null;
		for (Class<?> clazz = obj.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) {
			try {
				field = clazz.getDeclaredField(fieldName);
				break;
			} catch (NoSuchFieldException e) {
				// 这里不用做处理，子类没有该字段可能对应的父类有，都没有就返回null。
			}
		}
		return field;
	}

	@Override
	public Object plugin(Object target) {
		return Plugin.wrap(target, this);
	}

	@Override
	public void setProperties(Properties properties) {
	}

}