package com.warmer.web.controller;

import com.warmer.base.util.R;
import com.warmer.web.model.CustomDictEntry;
import com.warmer.web.service.CustomDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/customDict")
@CrossOrigin(origins = "*", maxAge = 3600)
public class CustomDictController {

    @Autowired
    private CustomDictService customDictService;

    @GetMapping("/list")
    public R<List<CustomDictEntry>> list(@RequestParam(required = false) String domain,
                                         @RequestParam(required = false) Integer enabled) {
        return R.success(customDictService.list(domain, enabled));
    }

    @PostMapping("/add")
    public R<Boolean> add(@RequestBody Map<String, Object> body) {
        String word = Objects.toString(body.get("word"), "");
        String nature = Objects.toString(body.get("nature"), "n");
        Integer freq = body.get("freq") == null ? 1000 : Integer.valueOf(body.get("freq").toString());
        String domain = Objects.toString(body.get("domain"), null);
        String source = Objects.toString(body.get("source"), "manual");
        if (word.isEmpty()) return R.error("word不能为空");
        boolean ok = customDictService.addWord(word, nature, freq, domain, source);
        return ok ? R.success(true) : R.error("添加失败");
    }

    @PostMapping("/disable")
    public R<Boolean> disable(@RequestParam Integer id) {
        return customDictService.disable(id) ? R.success(true) : R.error("停用失败");
    }
}