package com.zhgd.mybatis;

import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.baomidou.mybatisplus.extension.parser.JsqlParserSupport;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.zhgd.annotation.DataScope;
import lombok.Setter;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.Select;
import net.sf.jsqlparser.statement.select.SelectBody;
import net.sf.jsqlparser.statement.select.SetOperationList;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

public class DataScopeInterceptor extends JsqlParserSupport implements InnerInterceptor {

    @Setter
    private DataScopeHandler dataScopeHandler;

    private List<String> ignoreList = Arrays.asList("getSnListByEnterprise");

    public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
        try {
            Class<?> clazz = Class.forName(ms.getId().substring(0, ms.getId().lastIndexOf(".")));
            boolean ignore = true;
            if (ignoreList.contains(ms.getId().substring(ms.getId().lastIndexOf(".") + 1))) {
                ignore = false;
            }
            DataScope annotation = clazz.getAnnotation(DataScope.class);
            if (ignore && annotation != null) {
                PluginUtils.MPBoundSql mpBs = PluginUtils.mpBoundSql(boundSql);
                mpBs.sql(this.parserSingle(mpBs.sql(), ms.getId()));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    protected void processSelect(Select select, int index, String sql, Object obj) {
        SelectBody selectBody = select.getSelectBody();
        PlainSelect plainSelect = null;
        if (selectBody instanceof SetOperationList) {
            SetOperationList setOperationList = (SetOperationList) select.getSelectBody();
            plainSelect = (PlainSelect) setOperationList.getSelects().get(0);
        } else {
            plainSelect = (PlainSelect) select.getSelectBody();
        }
        this.dataScopeHandler.getSqlSegment(plainSelect);
    }

//    PlainSelect plainSelect = null;
//        if (select.getSelectBody() instanceof  SetOperationList) {
//        SetOperationList setOperationList = (SetOperationList) select.getSelectBody();
//        plainSelect = (PlainSelect) setOperationList.getSelects().get(0);
//    } else {
//        plainSelect = (PlainSelect) select.getSelectBody();
//    }
//        this.dataScopeHandler.getSqlSegment(plainSelect);
}
