package com.salpa.web.controller.subject;

import com.salpa.common.constant.UserConstants;
import com.salpa.common.core.controller.BaseController;
import com.salpa.common.core.domain.AjaxResult;
import com.salpa.common.core.page.TableDataInfo;
import com.salpa.subject.domain.MonitorSubject;
import com.salpa.subject.service.SubjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 主题管理
 *
 * @author zhuff
 */
@RestController
@RequestMapping("/subject/manage")
public class SubjectController extends BaseController {

    @Autowired
    private SubjectService subjectService;

    /**
     * 获取主题管理列表
     * @author zhuff
     * @param pageNum
     * @param pageSize
     * @param subjectName
     * @return
     */
    @GetMapping("list")
    public TableDataInfo getList(@RequestParam Integer pageNum,@RequestParam Integer pageSize,@RequestParam String subjectName) {
        List<MonitorSubject> list = subjectService.getList(pageNum,pageSize,subjectName);
        return getDataTable(list);
    }

    /**
     * 根据项目id获取主题管理
     * @author zhuff
     * @param id
     * @return
     */
    @GetMapping("getById")
    public AjaxResult getById(Integer id) {
        return AjaxResult.success(subjectService.getById(id));
    }

    /**
     * 新增主题管理
     * @author zhuff
     * @param monitorSubject
     * @return
     */
    @PostMapping("add")
    public AjaxResult addSubject(@RequestBody MonitorSubject monitorSubject) {
        if (UserConstants.NOT_UNIQUE.equals(subjectService.checkSubjectNameUnique(monitorSubject.getSubjectName())))
        {
            return AjaxResult.error("新增主题'" + monitorSubject.getSubjectName() + "'失败，该主题已存在");
        }
        return toAjax(subjectService.addSubject(monitorSubject));
    }

    /**
     * 修改主题管理
     * @author zhuff
     * @param monitorSubject
     * @return
     */
    @PostMapping("update")
    public AjaxResult updateSubject(@RequestBody MonitorSubject monitorSubject) {
        MonitorSubject subject = subjectService.getById(monitorSubject.getId());
        if (!subject.getSubjectName().equals(monitorSubject.getSubjectName())){
            if (UserConstants.NOT_UNIQUE.equals(subjectService.checkSubjectNameUnique(monitorSubject.getSubjectName())))
            {
                return AjaxResult.error("修改主题'" + monitorSubject.getSubjectName() + "'失败，该主题已存在");
            }
        }
        return toAjax(subjectService.updateSubject(monitorSubject));
    }

    /**
     * 删除主题管理
     * @author zhuff
     * @param id
     * @return
     */
    @DeleteMapping("delete")
    public AjaxResult deleteSubject(Integer id) {
        return toAjax(subjectService.deleteSubject(id));
    }
}
