
package com.jeelowcode.framework.plus.chain.parser;


import com.jeelowcode.framework.plus.chain.AbstractSQLParser;
import com.jeelowcode.framework.plus.chain.entity.TenantIdFilterEntity;
import com.jeelowcode.framework.plus.entity.SqlInfoEntity;
import com.jeelowcode.framework.plus.core.model.SqlFormatModel;
import com.jeelowcode.framework.tenant.utils.JeeLowCodeTenantUtils;
import com.jeelowcode.framework.utils.utils.FuncBase;

import java.util.Set;

/**
 * 多租户
 */
public class TenantSQLParser extends AbstractSQLParser {

    public TenantSQLParser(int level) {
        this.level=level;
    }

    @Override
    protected void sqlParse(SqlInfoEntity sqlInfoEntity) {
       try{
           TenantIdFilterEntity tenantIdFilterEntity = sqlInfoEntity.getTenantIdFilterEntity();
           if(FuncBase.isEmpty(tenantIdFilterEntity)){
               return;
           }

           SqlFormatModel sqlFormatModel = sqlInfoEntity.getSqlModelList().get(0);
           if(FuncBase.isEmpty(sqlFormatModel)){
               return;
           }
           String sql = sqlFormatModel.getSql();


           Long tenantId = tenantIdFilterEntity.getTenantId();
           if(FuncBase.isEmpty(tenantId)){
               return;
           }
           boolean enable = tenantIdFilterEntity.isEnable();
           if(!enable){//没有启动
               return;
           }
           boolean ignore = tenantIdFilterEntity.isIgnore();

           Set<String> ignoreTables = tenantIdFilterEntity.getIgnoreTables();
           Set<String> ignoreUrl = tenantIdFilterEntity.getIgnoreUrl();

           JeeLowCodeTenantUtils.initIgnoreTables(ignoreTables);//初始化
           JeeLowCodeTenantUtils.initIgnoreUrl(ignoreUrl);
           boolean threadIgnore = JeeLowCodeTenantUtils.isIgnore();
           if(!threadIgnore){
               JeeLowCodeTenantUtils.setIgnore(ignore);//本次
           }


           JeeLowCodeTenantUtils.setTenantId(tenantId);
           String newSql = JeeLowCodeTenantUtils.parseTenantSql(sql);
           sqlFormatModel.setSql(newSql);

       }catch (Exception e){
            e.printStackTrace();
       }

    }
}
