package com.qmth.teachcloud.report.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import com.qmth.teachcloud.report.business.bean.dto.query.TBSchoolClazzDto;
import com.qmth.teachcloud.report.business.entity.TBSchoolClazz;
import com.qmth.teachcloud.report.business.mapper.TBSchoolClazzMapper;
import com.qmth.teachcloud.report.business.service.TBSchoolClazzService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 学校班级表 服务实现类
 * </p>
 *
 * @author wangliang
 * @since 2021-06-01
 */
@Service
public class TBSchoolClazzServiceImpl extends ServiceImpl<TBSchoolClazzMapper, TBSchoolClazz> implements TBSchoolClazzService {
    @Override
    public TBSchoolClazz findByForeignKey(Long schoolId, String clazzCode, String clazzName) {
        List<TBSchoolClazz> tbSchoolClazzList = this.list(new QueryWrapper<TBSchoolClazz>().lambda()
                .eq(TBSchoolClazz::getSchoolId,schoolId)
                .eq(TBSchoolClazz::getClazzCode,clazzCode)
                .eq(TBSchoolClazz::getClazzName,clazzName));
        if (tbSchoolClazzList.size() != 1){
            throw ExceptionResultEnum.ERROR.exception("班级基础数据异常");
        }
        return tbSchoolClazzList.get(0);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveClazzInfo(List<TBSchoolClazzDto> tbSchoolClazzDtoList) {
        List<TBSchoolClazz> tbSchoolClazzList = new ArrayList<>();
        for (TBSchoolClazzDto tbSchoolClazzDto : tbSchoolClazzDtoList) {
            TBSchoolClazz old = this.getOne(new QueryWrapper<TBSchoolClazz>().lambda()
                    .eq(TBSchoolClazz::getSchoolId, tbSchoolClazzDto.getSchoolId())
                    .eq(TBSchoolClazz::getClazzCode, tbSchoolClazzDto.getClazzCode())
                    .eq(TBSchoolClazz::getClazzName, tbSchoolClazzDto.getClazzName()));
            Long id;
            if (Objects.nonNull(old)) {
                id = old.getId();
            } else {
                id = SystemConstant.getDbUuid();
            }

            TBSchoolClazz tbSchoolClazz = new TBSchoolClazz();
            tbSchoolClazz.setId(id);
            tbSchoolClazz.setSchoolId(tbSchoolClazzDto.getSchoolId());
            tbSchoolClazz.setClazzCode(tbSchoolClazzDto.getClazzCode());
            tbSchoolClazz.setClazzName(tbSchoolClazzDto.getClazzName());
            tbSchoolClazz.setEnable(true);
            tbSchoolClazz.setCreateTime(System.currentTimeMillis());
            tbSchoolClazz.setUpdateTime(System.currentTimeMillis());
            tbSchoolClazzList.add(tbSchoolClazz);
        }
        this.saveOrUpdateBatch(tbSchoolClazzList);
    }
}
