package com.ruoyi.demo.controller;


import com.ruoyi.common.core.domain.R;
import com.ruoyi.demo.constant.RedisContant;
import com.ruoyi.demo.entity.AddrCategory;
import com.ruoyi.demo.entity.bo.WdCount;
import com.ruoyi.demo.entity.vo.AddrCategoryBody;
import com.ruoyi.demo.entity.vo.TypeByBody;
import com.ruoyi.demo.service.CommonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/common")
public class CommonController {
    @Autowired
    CommonService commonService;

    @Autowired
    RedisTemplate redisTemplate;
    //获取网点标签
    @GetMapping("/tag")
    public R tag(){
        List<TypeByBody>  wdCount = (List<TypeByBody>) redisTemplate.boundValueOps(RedisContant.COMMON_TAG).get();
        if (wdCount != null) {
            return R.ok(wdCount);
        }

        List<TypeByBody> tag = commonService.tag();
        //4.保存到redis中
        redisTemplate.boundValueOps(RedisContant.COMMON_TAG).set(tag);
        redisTemplate.expire(RedisContant.COMMON_TAG,RedisContant.COMMON_TAG_TIME, TimeUnit.MINUTES); //30分钟
        return R.ok(tag);
    }

    //获取网点标签
    @GetMapping("/addrCodeMap")
    public R addrCodeMap(){
        List<AddrCategoryBody>  wdCount = (List<AddrCategoryBody>) redisTemplate.boundValueOps(RedisContant.COMMON_ADDR_CODE_MAP).get();
        if (wdCount != null) {
            return R.ok(wdCount);
        }

        List<AddrCategoryBody> addrCategoryBodies = commonService.addrCodeMap();
        redisTemplate.boundValueOps(RedisContant.COMMON_ADDR_CODE_MAP).set(wdCount);
        redisTemplate.expire(RedisContant.COMMON_ADDR_CODE_MAP,RedisContant.COMMON_ADDR_CODE_MAP_TIME, TimeUnit.MINUTES); //30分钟
        return R.ok(addrCategoryBodies);
    }

    @GetMapping("/addrCodeLevel")
    public R addrCodeLevel(String code,String level){
        //2.查看redis中是否存在有缓存
        List<AddrCategory>  wdCount = (List<AddrCategory> ) redisTemplate.boundHashOps(RedisContant.COMMON_LEVEL).get(code+level);
        if (wdCount != null) {
            return R.ok(wdCount);
        }

        List<AddrCategory> addrCategories = commonService.addrCodeLevel(code,level);
        redisTemplate.boundHashOps(RedisContant.COMMON_LEVEL).put(code+level,addrCategories);
        redisTemplate.expire(RedisContant.COMMON_LEVEL,RedisContant.COMMON_LEVEL_TIME, TimeUnit.MINUTES); //30分钟
        return R.ok(addrCategories);
    }
}
