package com.sysu.admin.controller.crop.range;

import com.sysu.admin.utils.TextUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class AutoTableNameInterceptor extends EmptyInterceptor {

    public static ThreadLocal<String> myTable = new ThreadLocal<>();


    @Override
    public String onPrepareStatement(String sql) {
        String tableName = myTable.get();
        if(StringUtils.isNotBlank(tableName) && sql.indexOf("p_crop ") > -1) {
            if (sql.indexOf("delete ") > -1 || sql.indexOf("insert ") > -1) {
                return sql;
            }
            if(sql.indexOf("update ") > -1){
                sql = sql.replaceAll("p_crop", tableName);
            }
            if (sql.indexOf("select ") > -1) {
                String[] tableArray =  TextUtil.split(tableName,",");
                if(tableArray.length == 1){
                    return sql.replaceAll("p_crop", tableArray[0]);
                }else{
                    String newSql = "";
                    int i=0;
                    for(String table : tableArray) {
                        if (i > 0) {
                            newSql += "\n union all \n";
                        }
                        newSql += sql.replaceAll("p_crop", table);
                        i++;
                    }
                    return newSql;
                }
            }
        }
        return sql;
    }
}
