package com.sv.api.interceptor;

import com.sv.api.context.PlatformContext;
import com.ydd.framework.core.common.utils.ReflectUtil;
import com.ydd.framework.core.common.utils.RequestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.Properties;

@Intercepts({
        @Signature(type = Executor.class, method = "query", args = {
                MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "query", args = {
                MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
})
public class PlatformIdInterceptor implements Interceptor {

    private static final Logger logger = LoggerFactory.getLogger(PlatformIdInterceptor.class);

    /**
     * 搜索前缀
     */
    public static final String SEARCH_PREFIX = "search_";

    /**
     * 分隔符
     */
    public static final String DELIMITER = "_";

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 准备参数
        Executor executor = (Executor) invocation.getTarget();
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object parameter = args[1];
        BoundSql boundSql;
        //由于逻辑关系，只会进入一次
        if (args.length == 4) {
            //4 个参数时
            boundSql = ms.getBoundSql(parameter);
        } else {
            //6 个参数时
            boundSql = (BoundSql) args[5];
        }
        String sql = null;
        sql = buildSearchRequestParameters(boundSql.getSql());

        ReflectUtil.setFieldValue(boundSql, "sql", sql);

        return invocation.proceed();
    }

    /**
     * 构建搜索请求参数
     *
     * @param sql SQL
     * @return SQL
     */
    private String buildSearchRequestParameters(String sql) {
        HttpServletRequest request = null;
        try {
            request = RequestUtils.getRequest();
        }catch (Exception e){}
        if(request == null)
            return sql;
        StringBuilder condition = new StringBuilder(" 1 = 1 ");
        String platformKey = PlatformContext.getKey();
        if(StringUtils.isEmpty(platformKey))
            return sql;

        condition.append(" and ").append(PlatformContext.getKey()).append(" = '").append(PlatformContext.getValue()).append("'");
        String[] sqls = new String[2];
        int index = sql.toLowerCase().lastIndexOf("where");
        sqls[0] = sql.substring(0,index-1);
        sqls[1] = sql.substring(index+5,sql.length());
        return sqls[0] + " WHERE " + condition.toString() + (sqls.length == 2 ? " AND " + sqls[1] : "");
    }



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

    @Override
    public void setProperties(Properties properties) {

    }

}
