package com.gree.mall.manager.config.datascope;


import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.gree.mall.manager.annotation.DataPermission;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.utils.ApplicationContextUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.sql.SQLException;
import java.util.List;

/**
 * 此数据权限添加不启用（无需启用）
 */
@Order(200)
@Component
public class DataScopeInnerInterceptor implements InnerInterceptor {

    @Override
    public void beforeUpdate(Executor executor, MappedStatement ms, Object parameter) throws SQLException {
        BoundSql boundSql = ms.getBoundSql(parameter);
        //执行sql
        String originalSql = boundSql.getSql();
        //sql执行新增或者修改 insert or update
        String insertUpdate = originalSql.substring(0, originalSql.indexOf(" "));
        //表名称
        String tbName = insertUpdate.equals("INSERT")?originalSql.split(" ")[2]:originalSql.split(" ")[1];

        List<ParameterMapping> parameterMappings =  boundSql.getParameterMappings();
        //参数
        Object parameterObject = boundSql.getParameterObject();
        //parameterObject.getClass().isArray();

//        log.info("parameterObject: {}",parameterObject);
//        log.info("执行sql - originalSql: {}",originalSql);
//
//        if(parameterObject instanceof OrderBase){
//            log.info("OrderBase....sql执行头:{},执行表:{}",insertUpdate,tbName);
//        }else if(parameterObject instanceof OrderWorker){
//            log.info("OrderWorker....sql执行头:{},执行表:{}",insertUpdate,tbName);
//        }else if(parameterObject instanceof OrderInstallOperatingLog){
//            log.info("OrderInstallOperatingLog....sql执行头:{},执行表:{}",insertUpdate,tbName);
//        }
    }


    @Override
    public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds,
                            ResultHandler resultHandler, BoundSql boundSql) {

        PluginUtils.MPBoundSql mpBs = PluginUtils.mpBoundSql(boundSql);

        String originalSql = boundSql.getSql();
        //采用判断方法注解方式进行数据权限
        Class<?> clazz = null;
        try {
            //获取Mapper类
            clazz = Class.forName(ms.getId().substring(0,  ms.getId().lastIndexOf(".")));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        // 获取方法名
        String methodName = ms.getId().substring(ms.getId().lastIndexOf(".") + 1);
        Method[] methods = clazz.getMethods();
        //遍历类的方法
        for (Method method : methods) {
            DataPermission annotation = method.getAnnotation(DataPermission.class);
            //判断是否存在注解且方法名一致
            if (annotation != null && methodName.equals(method.getName())){

                CommonLogic commonLogic = ApplicationContextUtils.getBean(CommonLogic.class);
                List<String> companyWechatIds = commonLogic.getAdminUser().getCompanyWechatIds();
                if(companyWechatIds != null && companyWechatIds.size() > 0){
                    String scopeName = annotation.field();
                    // 优先获取赋值数据
                    List<String> data =  companyWechatIds;
                    String websitIds = StringUtils.join(data.toArray(), "','");
                    websitIds = "'" + websitIds + "'";
                    originalSql = String.format("SELECT * FROM (%s) temp_data_scope WHERE temp_data_scope.%s IN (%s)",
                                originalSql, scopeName, websitIds);

                }
            }
        }
        mpBs.sql(originalSql);
    }
}
