package com.jsc.oscm.controller;

import com.alibaba.fastjson.JSON;
import com.jsc.oscm.entity.RulesParser;
import com.jsc.oscm.model.ReturnT;
import com.jsc.oscm.service.RulesParserService;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/rules/parser")
public class RulesParserController {

    @Resource
    RulesParserService rulesParserService;

    @PostMapping("/add")
    public String add(@RequestBody RulesParser rulesParser) {
        return save(rulesParser);
    }

    @PostMapping("/update")
    public String update(@RequestBody RulesParser rulesParser) {
        return save(rulesParser);
    }

    @PostMapping("/delete")
    public String delete(@RequestBody RulesParser rulesParser) {
        ReturnT<String> returnT;
        try {
            rulesParserService.delete(rulesParser);
            returnT = new ReturnT<>(200, "", null);
        } catch (Exception e) {
            returnT = new ReturnT<>(500, e.getMessage(), null);
        }
        return JSON.toJSONString(returnT);
    }

    @PostMapping("/queryPageable/{index}/{size}")
    public String query(@PathVariable("index") Integer index,
                        @PathVariable("size") Integer size,
                        @RequestBody RulesParser rulesParser) {
        ReturnT<List<RulesParser>> returnT;
        try {
            returnT = new ReturnT<>(200,
                    String.valueOf(rulesParserService.queryCount(rulesParser)),
                    rulesParserService.queryPageable(rulesParser, index, size));
        } catch (Exception e) {
            returnT = new ReturnT<>(500, e.getMessage(), null);
        }
        return JSON.toJSONString(returnT);
    }

    @NotNull
    private String save(@RequestBody RulesParser rulesParser) {
        ReturnT<RulesParser> returnT;
        try {
            returnT = new ReturnT<>(200, "", rulesParserService.save(rulesParser));
        } catch (Exception e) {
            returnT = new ReturnT<>(500, e.getMessage(), null);
        }
        return JSON.toJSONString(returnT);
    }

}
