package com.tax.file.service.impl;


import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.tax.file.mapper.TkUserUrlMapper;
import com.tax.file.model.TkUserUrl;
import com.tax.file.model.TkUserUrlExample;
import com.tax.file.service.api.TkUserUrlService;
import com.yxcheng.token.common.cache.RedisService;
import com.yxcheng.token.common.service.AbstractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;


@Transactional
@Component
@ComponentScan(basePackages = {"com.tax.file.dao", "com.tax.file.integration"})
public class TkUserUrlServiceImpl extends AbstractService<TkUserUrlMapper,TkUserUrlExample,TkUserUrl> implements TkUserUrlService {

    @Autowired
    private RedisService redisService;

    @Override
    public TkUserUrl getUserUrlInfo(String accessKeyId, String functionNo) {
        return baseMapper.getUserUrlInfo(accessKeyId, functionNo);
    }

    @Override
    public List<TkUserUrl> getUserUrlList(String accessKeyId) {
        return baseMapper.getUserUrlList(accessKeyId);
    }

    public Map<String, TkUserUrl> getUserUrlMap(String accessKeyId) {
        Map<String, TkUserUrl> urlMap = Maps.newHashMap();
        List<TkUserUrl> urlList = baseMapper.getUserUrlList(accessKeyId);
        for(TkUserUrl userUrl:urlList) {
            urlMap.put(userUrl.getFunctionNo(), userUrl);
        }
        return urlMap;
    }

    public boolean checkUrlExist(Map<String, TkUserUrl> urlMap, String functionNo) {
        return urlMap.containsKey(functionNo);
    }

    public static final String CACHE_USER_URL_PREFIX = "taxsys:userurl:";

    public String getUserUrlName(String userName, String functionNo) {
        return CACHE_USER_URL_PREFIX + userName + ":" + functionNo;
    }

    public int flushUserUrlCache(String userName) {
        Map<String, TkUserUrl> urlMap = Maps.newHashMap();
        List<TkUserUrl> urlList = baseMapper.getUserUrlList(userName);

        redisService.delByReg(CACHE_USER_URL_PREFIX + userName);
        for(TkUserUrl userUrl:urlList) {
            urlMap.put(userUrl.getFunctionNo(), userUrl);
            redisService.set(getUserUrlName(userName, userUrl.getFunctionNo()), JSON.toJSONString(userUrl));
        }
        return urlList.size();
    }

    public boolean checkUserUrlExist(String userName, String functionNo) {
        return redisService.exists(getUserUrlName(userName, functionNo));
    }

    public TkUserUrl getUserUrl(String userName, String functionNo) {
        TkUserUrl userUrl = null;
        if(redisService.exists(getUserUrlName(userName, functionNo))) {
            userUrl = JSON.parseObject(redisService.get(getUserUrlName(userName, functionNo)), TkUserUrl.class);
        }
        return userUrl;
    }
}
