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.RelationDefine;
import com.persagy.dmp.basic.utils.QueryCriteriaHelper;
import com.persagy.dmp.rwd.define.service.IRelationDefineService;
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/rel")
public class RelationDefineController {

    @Autowired
    private IRelationDefineService service;

    @PostMapping("/query")
    public CommonResult<List<RelationDefine>> query(@RequestBody QueryCriteria criteria) {
        if(criteria == null) {
            throw new BusinessException(ResponseCode.A0400.getCode(), ResponseCode.A0400.getDesc());
        }
        QueryWrapper<RelationDefine> wrapper = new QueryWrapper<>();
        // 添加所属项目条件
        // ConditionUtil.ensureProjectCriteria(wrapper);
        // 转换查询条件
        QueryCriteriaHelper.toWrapper(wrapper, criteria, RelationDefine.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<RelationDefine> create(@Valid @RequestBody RelationDefine vo){
        vo = service.insert(vo);
        return ResultHelper.single(vo);
    }

    @PostMapping("/update")
    public CommonResult<RelationDefine> update(@Valid @RequestBody RelationDefine 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);
    }
}
