package com.yihu.wlyy.service.system;

import com.yihu.wlyy.entity.dict.SystemDict;
import com.yihu.wlyy.repository.dict.SystemDictDao;
import com.yihu.wlyy.repository.dict.SystemDictListDao;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by Administrator on 2016/8/13.
 */
@Service
public class SystemDictService {
    @Autowired
    private SystemDictDao systemDictDao;
    @Autowired
    private StringRedisTemplate redisTemplate;

    public List<SystemDict> getDictByDictName(String name) {
        return systemDictDao.findByDictName(name);
    }


    /**
     * 字典转译
     * @param dictName
     * @param code
     * @return
     */
    public String getDictValue(String dictName,String code){
        String re = "";
        try {
            if(!StringUtils.isEmpty(code))
            {
                //判断该字典redis是否存在
                String exit = redisTemplate.opsForValue().get("systemDict:"+dictName);
                if(!StringUtils.isEmpty(exit))
                {
                    re =  redisTemplate.opsForValue().get("systemDict:"+dictName+":"+code);
                }
                else{
                    List<SystemDict> list = systemDictDao.findByDictName(dictName);
                    if(list!=null && list.size()>0)
                    {
                        redisTemplate.opsForValue().set("systemDict:"+dictName,"1");
                        for(SystemDict item:list)
                        {
                            redisTemplate.opsForValue().set("systemDict:"+dictName+":"+item.getCode(),item.getValue());
                            if(code.equals(item.getCode()))
                            {
                                re = item.getValue();
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            re = systemDictDao.findByDictNameAndCode(dictName,code);
        }
        return re;
    }
}
