package com.pangu.base.controller;

import com.pangu.base.domain.Grade;
import com.pangu.base.service.IGradeService;
import com.pangu.common.core.controller.BaseController;
import com.pangu.common.core.domain.AjaxResult;
import com.pangu.common.core.page.TableDataInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 年级管理Controller
 * @author pangu
 */
@RestController
@RequestMapping("/api/grade")
public class GradeController extends BaseController {

    @Autowired
    private IGradeService gradeService;

    /**
     * 获取年级列表
     */
    @GetMapping("/list")
    public TableDataInfo list(Grade grade) {
        startPage();
        List<Grade> list = gradeService.selectGradeList(grade);
        return getDataTable(list);
    }

    /**
     * 获取年级选项列表（下拉用）
     */
    @GetMapping("/options")
    public AjaxResult options() {
        List<Grade> list = gradeService.selectGradeOptions();
        return success(list);
    }

    /**
     * 获取年级详情
     */
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long gradeId) {
        return success(gradeService.selectGradeById(gradeId));
    }

    /**
     * 新增年级
     */
    @PostMapping
    public AjaxResult add(@Validated @RequestBody Grade grade) {
        if (!gradeService.checkGradeNameUnique(grade)) {
            return error("年级名称已存在");
        }
        grade.setCreateBy("admin");
        return toAjax(gradeService.insertGrade(grade));
    }

    /**
     * 修改年级
     */
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody Grade grade) {
        if (!gradeService.checkGradeNameUnique(grade)) {
            return error("年级名称已存在");
        }
        grade.setUpdateBy("admin");
        return toAjax(gradeService.updateGrade(grade));
    }

    /**
     * 删除年级
     */
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable("id") Long gradeId) {
        // TODO: 检查是否被学校引用
        return toAjax(gradeService.deleteGradeById(gradeId));
    }
}
