package com.jay.monitor.data.server.controllers;

import cn.hutool.core.bean.BeanUtil;
import com.jay.monitor.data.core.model.response.ResponseCommonModel;
import com.jay.monitor.data.core.utils.ResponseUtils;
import com.jay.monitor.data.server.store.ISimpleCrudProcess;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author liukaixiong
 * @Email liukx@elab-plus.com
 * @date 2021/9/8 - 17:59
 */
public abstract class BaseSimpleCrudController<T> {

    public abstract ISimpleCrudProcess getCrudProcess();

    @RequestMapping(value = "/add", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public ResponseCommonModel addMapping(@RequestBody T request) throws Exception {
        addBefore(request);
        boolean save = getCrudProcess().save(request);
        return ResponseUtils.trues();
    }

    /**
     * 添加之前
     *
     * @param req
     */
    protected void addBefore(T req) {
    }

    protected void updateBefore(T req) {

    }

    protected void deleteBefore(T req) {
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public ResponseCommonModel updateMapping(@RequestBody T request) throws Exception {
        updateBefore(request);
        boolean update = getCrudProcess().update(request);
        return ResponseUtils.trues();
    }

    @RequestMapping(value = "/del", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public ResponseCommonModel delMapping(@RequestBody T request) throws Exception {
        deleteBefore(request);
        Object id = BeanUtil.getFieldValue(request, "id");
        boolean update = getCrudProcess().delete(id.toString());
        return ResponseUtils.trues();
    }
}
