package com.pangu.base.service.impl;

import com.pangu.base.domain.PgClass;
import com.pangu.base.mapper.PgClassMapper;
import com.pangu.base.service.IPgClassService;
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 PgClassServiceImpl implements IPgClassService {

    @Autowired
    private PgClassMapper pgClassMapper;

    @Override
    public List<PgClass> selectClassList(PgClass pgClass) {
        return pgClassMapper.selectClassList(pgClass);
    }

    @Override
    public List<PgClass> selectClassOptions() {
        PgClass pgClass = new PgClass();
        pgClass.setStatus("0");
        return pgClassMapper.selectClassList(pgClass);
    }

    @Override
    public PgClass selectClassById(Long classId) {
        return pgClassMapper.selectClassById(classId);
    }

    @Override
    public int insertClass(PgClass pgClass) {
        pgClass.setClassCode(generateClassCode());
        pgClass.setCreateTime(DateUtils.getNowDate());
        return pgClassMapper.insertClass(pgClass);
    }

    private String generateClassCode() {
        String maxCode = pgClassMapper.selectMaxClassCode();
        if (StringUtils.isEmpty(maxCode)) {
            return "CLS001";
        }
        int num = Integer.parseInt(maxCode.substring(3)) + 1;
        return String.format("CLS%03d", num);
    }

    @Override
    public int updateClass(PgClass pgClass) {
        pgClass.setUpdateTime(DateUtils.getNowDate());
        return pgClassMapper.updateClass(pgClass);
    }

    @Override
    public int deleteClassById(Long classId) {
        return pgClassMapper.deleteClassById(classId);
    }

    @Override
    public boolean checkClassNameUnique(PgClass pgClass) {
        Long classId = pgClass.getClassId() == null ? -1L : pgClass.getClassId();
        PgClass info = pgClassMapper.checkClassNameUnique(pgClass.getClassName());
        return info == null || info.getClassId().equals(classId);
    }
}
