package com.pangu.base.service.impl;

import com.pangu.base.domain.Subject;
import com.pangu.base.mapper.SubjectMapper;
import com.pangu.base.service.ISubjectService;
import com.pangu.common.utils.DateUtils;
import com.pangu.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 学科管理Service实现
 * @author pangu
 */
@Service
public class SubjectServiceImpl implements ISubjectService {

    @Autowired
    private SubjectMapper subjectMapper;

    @Override
    public List<Subject> selectSubjectList(Subject subject) {
        return subjectMapper.selectSubjectList(subject);
    }

    @Override
    public List<Subject> selectSubjectOptions() {
        Subject subject = new Subject();
        subject.setStatus("0");
        return subjectMapper.selectSubjectList(subject);
    }

    @Override
    public Subject selectSubjectById(Long subjectId) {
        return subjectMapper.selectSubjectById(subjectId);
    }

    @Override
    public int insertSubject(Subject subject) {
        subject.setSubjectCode(generateSubjectCode());
        subject.setCreateTime(DateUtils.getNowDate());
        return subjectMapper.insertSubject(subject);
    }

    private String generateSubjectCode() {
        String maxCode = subjectMapper.selectMaxSubjectCode();
        if (StringUtils.isEmpty(maxCode)) {
            return "SUB001";
        }
        int num = Integer.parseInt(maxCode.substring(3)) + 1;
        return String.format("SUB%03d", num);
    }

    @Override
    public int updateSubject(Subject subject) {
        subject.setUpdateTime(DateUtils.getNowDate());
        return subjectMapper.updateSubject(subject);
    }

    @Override
    public int deleteSubjectById(Long subjectId) {
        return subjectMapper.deleteSubjectById(subjectId);
    }

    @Override
    public boolean checkSubjectNameUnique(Subject subject) {
        Long subjectId = subject.getSubjectId() == null ? -1L : subject.getSubjectId();
        Subject info = subjectMapper.checkSubjectNameUnique(subject.getSubjectName());
        return info == null || info.getSubjectId().equals(subjectId);
    }
}
