package com.ag.secp.platform.redis;

import com.ag.secp.platform.spring.SpringContextHolder;
import com.google.common.collect.Lists;
import com.wb.common.KvBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;

import static java.util.concurrent.Executors.newFixedThreadPool;

public class RedisPkgExecuteImpl implements RedisExecute {

    private static Logger logger = LoggerFactory.getLogger(RedisPkgExecuteImpl.class);

    private ExecutorService threads;

    private DataSourceTemplate dataSourceTemplate;

    public static ConcurrentHashMap<String,Class> redisRepository;

    static {
        redisRepository=new ConcurrentHashMap<>();
    }

    public RedisPkgExecuteImpl(DataSourceTemplate dataSourceTemplate) {
        this.dataSourceTemplate = dataSourceTemplate;
    }

    @Override
    public void init() {
        Set<String> keys=dataSourceTemplate.getRedisTemplate().keys("KVBUFF_"+"*");
        dataSourceTemplate.getRedisTemplate().delete(keys);
    }

    @Override
    public List<?> pull(String keyName) {
        return  SerializeUtil.unserializeForList(
                (byte[]) dataSourceTemplate.getRedisTemplate().opsForValue().get("KVBUFF_"+keyName));
    }
    @Override
    public void push(String keyName,List<?> list) {
        threads= newFixedThreadPool(5);
        threads.execute(()->{
            dataSourceTemplate.getRedisTemplate().opsForValue().set("KVBUFF_"+keyName,SerializeUtil.serialize(list));
        });
        threads.shutdown();
    }

    @Override
    public void update(String keyName) {
        threads= newFixedThreadPool(5);
        threads.submit(()->{
                this.updateRedis(keyName);
        });
        dataSourceTemplate.getRedisTemplate().delete("KVBUFF_"+keyName);
        threads.shutdown();
    }

    private void updateRedis(String keyName){
        JdbcTemplate jdbcTemplate= SpringContextHolder.getBean("jdbcTemplatebusiness");
        List<Map<String, Object>> sourceList=
        jdbcTemplate.queryForList("SELECT   'CODE_SET'  AS  DATA_FROM  FROM  CODE_SET WHERE  CODE_SET.TABLE_NAME='"+keyName+"' \n" +
                "UNION \n" +
                "SELECT   'S_CODE'  AS  DATA_FROM  FROM S_CODE  WHERE SYS_CATEGORY='"+keyName+"'\n" +
                "UNION \n" +
                "SELECT   'WB_KEY' AS DATA_FROM  FROM  WB_KEY WHERE K='"+keyName+"'");
        if (!CollectionUtils.isEmpty(sourceList)){
            String dataFrom= (String) sourceList.get(0).get("DATA_FROM");
            logger.info("Redis Data Source ...."+dataFrom);
            List<KvBean> kvBeanList=Lists.newArrayList();
            switch (dataFrom){
                case "CODE_SET":
                    List<String> sql
                            =jdbcTemplate.queryForList("SELECT COD_SQL FROM CODE_SET WHERE TABLE_NAME='"+keyName+"'",String.class);
                    if (!CollectionUtils.isEmpty(sql)){
                        kvBeanList=this.buildKvBeanList(sql.get(0));
                    }
                    break;
                case "S_CODE":
                    kvBeanList=this.buildKvBeanList("SELECT  SYS_CATEGORY AS KEY_NAME,SYS_KEY AS K,SYS_VALUE AS V," +
                            " SYS_NAME AS COMV,TO_CHAR(SYS_SEQ) AS COMV2   FROM S_CODE WHERE SYS_CATEGORY='"+keyName+"'");
                    break;
                case "WB_KEY":
                    kvBeanList=this.buildKvBeanList("SELECT KEY_NAME,TO_CHAR(K) AS K,TO_CHAR(V) AS V,KEY_ID AS COMV,KEY_ID AS COMV2  " +
                            "FROM WB_KEY WHERE KEY_NAME='"+keyName+"'");
                    break;
            }
            this.push(keyName,  kvBeanList);
        }else {
            Class obj=redisRepository.get(keyName);
            if (!ObjectUtils.isEmpty(obj)){
                List<?> buffList= null;
                try {
                    buffList =jdbcTemplate.query("SELECT * FROM "+keyName+" ORDER BY CREATED_ON DESC",new BeanPropertyRowMapper(Class.forName(obj.getName())));
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                this.push(keyName,buffList);
            }
        }
    }

    /**
     *  传统方式构建 K V bean集合
     * @param sql
     * @return
     */
    private List<KvBean> buildKvBeanList(String sql) {
        JdbcTemplate jdbcTemplate= SpringContextHolder.getBean("jdbcTemplatebusiness");
        return  jdbcTemplate.query(sql,new BeanPropertyRowMapper(KvBean.class));
    }


}