package com.app.service.basics;

import com.app.entity.basics.YearSemester;
import com.app.mapper.basics.YearSemesterMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * 功能描述：学年学期
 *
 * @Auther: 梁展鹏
 * @Date: 2018/7/24 11:38
 */
@Slf4j
@Service
public class YearSemesterService {

    @Autowired
    private YearSemesterMapper mapper;

    /**
     * 功能描述：查询当前机构的学年学期
     *
     * @return
     */
    @Cacheable(cacheNames = "organ:year-semester", key = "#organId")
    public YearSemester find(String organId) {
        return mapper.selectOne(new QueryWrapper<YearSemester>().lambda()
            .eq(YearSemester::getOrganId, organId)
            .eq(YearSemester::getIsDel, Boolean.FALSE)
        );
    }

    /**
     * 功能描述：保存/更新[学年学期]
     *
     * @param organId
     * @param schoolYear
     * @param semester
     * @return
     */
    @CachePut(cacheNames = "organ:year-semester", key = "#organId")
    public YearSemester saveOrUpdate(String organId, Integer schoolYear, Integer semester) {
        YearSemester _organYearSemester = this.find(organId);
        if (!Optional.ofNullable(_organYearSemester).isPresent()) {
            _organYearSemester = new YearSemester();
            _organYearSemester.setOrganId(organId);
            _organYearSemester.setSchoolYear(schoolYear).setSemester(semester);
            mapper.insert(_organYearSemester);
        } else {
            _organYearSemester.setSchoolYear(schoolYear).setSemester(semester);
            mapper.updateById(_organYearSemester);
        }

        return _organYearSemester;
    }

}
