
package com.lideeyunji.tool.framework.sql.chain.parser;


import com.lideeyunji.tool.framework.yunji.tool.spring.SpringUtils;
import com.lideeyunji.tool.framework.sql.chain.AbstractSQLParser;
import com.lideeyunji.tool.framework.sql.chain.entity.TenantIdFilterEntity;
import com.lideeyunji.tool.framework.sql.entity.SqlInfoEntity;
import com.lideeyunji.tool.framework.sql.core.model.SqlFormatModel;
import com.lideeyunji.tool.framework.tenant.config.TenantProperties;
import com.lideeyunji.tool.framework.tenant.core.context.TenantContextHolder;
import com.lideeyunji.tool.framework.tenant.core.util.LideeYunJiTenantUtils;
import com.lideeyunji.tool.framework.yunji.utils.FuncBase;

/**
 * 多租户
 */
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;
           }

           Long tenantId = tenantIdFilterEntity.getTenantId();
           if(FuncBase.isEmpty(tenantId)){
               return;
           }

           TenantProperties tenantProperties = SpringUtils.getBean(TenantProperties.class);

           boolean enable = false;
           if(FuncBase.isNotEmpty(tenantProperties)){
               enable = tenantProperties.getEnable();
           }

           if(!enable){//没有启动
               return;
           }

           TenantContextHolder.setTenantId(tenantId);

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

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

    }
}
