package com.brilliance.isc.support;

import cn.hutool.core.util.StrUtil;
import com.brilliance.isc.bo.Etg;
import com.brilliance.isc.bo.Ety;
import com.brilliance.isc.common.context.SettleContext;
import com.brilliance.isc.common.context.SettleSession;
import com.brilliance.mda.support.mybatis.interceptor.CustomParameterInterceptor;
import com.brilliance.mda.support.mybatis.interceptor.ParameterProcessor;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

@Configuration
public class MyBatisConfig {

    @Bean
    public Interceptor customInterceptor() {
        return new CustomParameterInterceptor(new ParameterProcessor() {
            public static final String _ETY_PARAMETER_KEY = "_etyextkey";
            public static final String _ETG_PARAMETER_KEY = "_etgextkey";

            @Override
            public Object processCustomizedParameter(MappedStatement ms, Map<String, Object> paramMap, BoundSql boundSql, CacheKey pageKey) {
                SettleSession session = SettleContext.getUserSession();
                Ety ety = session.getEty();
                Etg etg = session.getEtg();

                paramMap.put(_ETY_PARAMETER_KEY, ety.getExtkey());
                paramMap.put(_ETG_PARAMETER_KEY, etg.getExtkey());
                //处理pageKey
                pageKey.update(ety);
                pageKey.update(etg);
                return paramMap;
            }

            /**
             * 检查SettleSession中是否有对应的ETY，ETG信息
             * @return
             */
            @Override
            public boolean checkParameter() {
                SettleSession session = SettleContext.getUserSession();
                if(session == null){
                    return false;
                }
                if(session.getEty() == null && session.getEtg() == null){
                    return false ;
                }
                if(StrUtil.isEmpty(session.getEty().getExtkey()) && StrUtil.isEmpty(session.getEtg().getExtkey())){
                    return false;
                }
                return true;
            }
        });
    }
}

