package com.persagy.dmp.rwd.define.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.persagy.dmp.basic.model.QueryCriteria;
import com.persagy.dmp.common.constant.ResponseCode;
import com.persagy.dmp.common.exception.BusinessException;
import com.persagy.dmp.common.model.response.CommonResult;
import com.persagy.dmp.common.utils.ResultHelper;
import com.persagy.dmp.define.entity.GraphDefine;
import com.persagy.dmp.basic.utils.QueryCriteriaHelper;
import com.persagy.dmp.rwd.define.service.IGraphDefineService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

/**
 * 对象类型 Controller
 * @author Charlie Yu
 * @date 2021-06-25
 */
@RestController
@RequestMapping("/rwd/def/graph")
public class GraphDefineController {

    @Autowired
    private IGraphDefineService service;

    @PostMapping("/query")
    public CommonResult<List<GraphDefine>> query(@RequestBody QueryCriteria criteria) {
        if(criteria == null) {
            throw new BusinessException(ResponseCode.A0400.getCode(), ResponseCode.A0400.getDesc());
        }
        QueryWrapper<GraphDefine> wrapper = new QueryWrapper<>();
        // 转换查询条件
        QueryCriteriaHelper.toWrapper(wrapper, criteria, GraphDefine.class);
        Page page = QueryCriteriaHelper.toPage(criteria);
        if(criteria.isOnlyCount()) {
            Integer total = service.queryCount(wrapper);
            page.setTotal(total);
        } else {
            page = service.queryByCondition(QueryCriteriaHelper.toPage(criteria), wrapper);
        }
        return ResultHelper.multi(page.getRecords(), page.getTotal());
    }

    @PostMapping("/create")
    public CommonResult<GraphDefine> create(@Valid @RequestBody GraphDefine vo){
        vo = service.insert(vo);
        return ResultHelper.single(vo);
    }

    @PostMapping("/update")
    public CommonResult<GraphDefine> update(@Valid @RequestBody GraphDefine vo){
        vo = service.update(vo);
        return ResultHelper.single(vo);
    }

    @PostMapping("/delete")
    public void delete(@RequestBody String id){
        if(StringUtils.isEmpty(id)){
            throw new BusinessException(ResponseCode.A0400.getCode(), "id不能为空");
        }
        service.delete(id);
    }
}
