package com.pangu.base.service.impl;

import com.pangu.base.domain.Grade;
import com.pangu.base.mapper.GradeMapper;
import com.pangu.base.service.IGradeService;
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 GradeServiceImpl implements IGradeService {

    @Autowired
    private GradeMapper gradeMapper;

    @Override
    public List<Grade> selectGradeList(Grade grade) {
        return gradeMapper.selectGradeList(grade);
    }

    @Override
    public List<Grade> selectGradeOptions() {
        Grade grade = new Grade();
        grade.setStatus("0"); // 只查询启用的
        return gradeMapper.selectGradeList(grade);
    }

    @Override
    public Grade selectGradeById(Long gradeId) {
        return gradeMapper.selectGradeById(gradeId);
    }

    @Override
    public int insertGrade(Grade grade) {
        // 生成年级编码
        grade.setGradeCode(generateGradeCode());
        grade.setCreateTime(DateUtils.getNowDate());
        return gradeMapper.insertGrade(grade);
    }

    /**
     * 生成年级编码：GRD + 3位序号
     */
    private String generateGradeCode() {
        String maxCode = gradeMapper.selectMaxGradeCode();
        if (StringUtils.isEmpty(maxCode)) {
            return "GRD001";
        }
        int num = Integer.parseInt(maxCode.substring(3)) + 1;
        return String.format("GRD%03d", num);
    }

    @Override
    public int updateGrade(Grade grade) {
        grade.setUpdateTime(DateUtils.getNowDate());
        return gradeMapper.updateGrade(grade);
    }

    @Override
    public int deleteGradeById(Long gradeId) {
        return gradeMapper.deleteGradeById(gradeId);
    }

    @Override
    public boolean checkGradeNameUnique(Grade grade) {
        Long gradeId = grade.getGradeId() == null ? -1L : grade.getGradeId();
        Grade info = gradeMapper.checkGradeNameUnique(grade.getGradeName());
        return info == null || info.getGradeId().equals(gradeId);
    }
}
