package thyyxxk.webserver.controller;

import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import thyyxxk.webserver.aop.interfaces.NeedMenu;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.enums.authorize.MenuEnum;
import thyyxxk.webserver.service.hutoolcache.CacheAll;
import thyyxxk.webserver.service.hutoolcache.HutoolCacheInterface;
import thyyxxk.webserver.utils.ResultVoUtil;

import java.util.*;

@RequestMapping("/cache/flushed")
@RestController
@RequiredArgsConstructor
public class CacheFlushedController {

    private final Map<String, HutoolCacheInterface<?>> cacheMap;

    @GetMapping("/getAllLabel")
    @NeedMenu(MenuEnum.cacheFlushed)
    public ResultVo<Map<String, String>> getAllLabel() {
        Map<String, String> map = new HashMap<>();
        for (Map.Entry<String, HutoolCacheInterface<?>> item : cacheMap.entrySet()) {
            String label = item.getValue().getLabel();
            if (item.getValue().getLabel() == null) {
                label = item.getKey();
            }

            map.put(item.getKey(), label);
        }
        return ResultVoUtil.success(map);
    }


    @GetMapping("/getAllCacheByKey")
    @NeedMenu(MenuEnum.cacheFlushed)
    public ResultVo<List<CacheAll>> getAllCacheByKey(@RequestParam("key") String key) {
        HutoolCacheInterface<?> hutoolCacheInterface = cacheMap.get(key);
        if (hutoolCacheInterface == null) {
            return ResultVoUtil.success(new ArrayList<>());
        }
        return ResultVoUtil.success(hutoolCacheInterface.getAll());
    }


    @Data
    public static class DelBody {
        private String labelKey;
        private String key;
    }

    @PostMapping("/delByKey")
    public ResultVo<String> delByKey(@RequestBody DelBody delBody) {
        HutoolCacheInterface<?> remove = cacheMap.get(delBody.labelKey);
        if (remove == null) {
            return ResultVoUtil.fail(ExceptionEnum.ERROR_MESSAGE_BOX, "没有对应的服务");
        }

        remove.del(delBody.key);
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_EL_NOTIFICATION);
    }


    @GetMapping("/specialMedicalAdvice")
    @NeedMenu(MenuEnum.cacheFlushed)
    public ResultVo<Boolean> specialMedicalAdvice() {
        return ResultVoUtil.success(true);
    }
}
