package cn.com.ty.lift.ud.common;

import cn.com.xwy.boot.web.dto.RestResponse;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

//@CrossOrigin
public abstract class BaseController<E extends BaseEntity,Q extends BasePageQuery> {
    protected abstract IService<E> getService();

    //新建
    @PostMapping("/insert")
    @ApiOperation(value = "新增")
    public RestResponse<E> create(@RequestBody E entity) {
        boolean saveFlag = getService().save(entity);
//        E byId = getService().getById(entity.getId());

        if (saveFlag)
            return RestResponse.success(null, "Created successfully");
        else
            return RestResponse.fail("Created unsuccessfully");
    }

    //修改
    @PutMapping("/update")
    @ApiOperation(value = "修改")
    public RestResponse update(@RequestBody E request) {
        boolean updateFlag = getService().updateById(request);
//        E e = getService().getById(request.getId());

        if (updateFlag)
            return RestResponse.success(null, "Updated successfully");
        else
            return RestResponse.fail("Updated unsuccessfully");
    }

    //根据id删除
    @DeleteMapping("/delete")
    @ApiOperation(value = "根据id删除")
    public RestResponse delete(@RequestBody DelReq req) {
        boolean deleteFlag = getService().removeById(req.getId());
        if (deleteFlag)
            return RestResponse.success(null, "Deleted successfully");
        else
            return RestResponse.fail("Deleted unsuccessfully");
    }

    //根据id批量删除
    @DeleteMapping("/delete-batch")
    @ApiOperation(value = "批量删除")
    public RestResponse deleteBath(@RequestBody DelReq req) {
        boolean deleteFlag = getService().removeByIds(req.getIds());
        if (deleteFlag)
            return RestResponse.success(null, "Deleted successfully");
        else
            return RestResponse.fail("Deleted unsuccessfully");
    }

    //根据id查详情
    @GetMapping("/query/{id}")
    @ApiOperation(value = "获取详情")
    public RestResponse get(@PathVariable Long id) {
        E entity = getService().getById(id);

        return RestResponse.success(entity, "Queried successfully");
    }

    //根据条件查询
    @PostMapping("/query-page")
    @ApiOperation(value = "分页查询")
    public RestResponse getCondition(@RequestBody Q request) {
        IPage<E> list = getService().page(request.page(), request.condition());

        return RestResponse.success(list, "Queried successfully");
    }
}
