package com.jsc.oscm.controller;

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

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

@RestController
@RequestMapping("/rules/filter")
public class RulesFilterController {

    @Resource
    RulesFilterService rulesFilterService;

    @PostMapping("/add")
    public String add(@RequestBody RulesFilter rulesFilter) {
        return save(rulesFilter);
    }

    @PostMapping("/update")
    public String update(@RequestBody RulesFilter rulesFilter) {
        return save(rulesFilter);
    }

    @PostMapping("/delete")
    public String delete(@RequestBody RulesFilter rulesFilter) {
        ReturnT<String> returnT;
        try {
            rulesFilterService.delete(rulesFilter);
            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 RulesFilter rulesFilter) {
        ReturnT<List<RulesFilter>> returnT;
        try {
            returnT = new ReturnT<>(200,
                    String.valueOf(rulesFilterService.queryCount(rulesFilter)),
                    rulesFilterService.queryPageable(rulesFilter, index, size));
        } catch (Exception e) {
            returnT = new ReturnT<>(500, e.getMessage(), null);
        }
        return JSON.toJSONString(returnT);
    }

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

}
