package cn.com.qmth.stmms.biz.exam.service.impl;

import cn.com.qmth.stmms.biz.common.BaseQueryService;
import cn.com.qmth.stmms.biz.exam.dao.SubjectUserDao;
import cn.com.qmth.stmms.biz.exam.model.SubjectUser;
import cn.com.qmth.stmms.biz.exam.service.SubjectUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service("subjectUserService")
public class SubjectUserServiceImpl extends BaseQueryService<SubjectUser> implements SubjectUserService {

    @Autowired
    private SubjectUserDao subjectUserDao;

    @Transactional
    @Override
    public SubjectUser save(SubjectUser u) {
        return subjectUserDao.save(u);
    }

    @Override
    public List<SubjectUser> findByUserId(Integer userId) {
        return subjectUserDao.findByUserId(userId);
    }

    @Override
    public Set<String> findSubjectCode(Integer userId) {
        Set<String> set = new HashSet<>();
        List<SubjectUser> list = subjectUserDao.findByUserId(userId);
        for (SubjectUser su : list) {
            set.add(su.getSubjectCode());
        }
        return set;
    }

    @Override
    public int batchSave(List<SubjectUser> list) {
        subjectUserDao.save(list);
        return list.size();
    }

    @Override
    public SubjectUser findBySubjectCodeAndUserId(String subjectCode, Integer userId) {
        return subjectUserDao.findBySubjectCodeAndUserId(subjectCode, userId);
    }

    @Override
    public SubjectUser findById(Integer id) {
        return subjectUserDao.findOne(id);
    }

    @Override
    @Transactional
    public void save(String subjectCode, Integer[] userIds) {
        List<SubjectUser> list = new ArrayList<SubjectUser>();
        if (userIds != null && userIds.length > 0) {
            for (Integer userId : userIds) {
                SubjectUser subjectUser = this.findBySubjectCodeAndUserId(subjectCode, userId);
                if (subjectUser == null) {
                    subjectUser = new SubjectUser();
                    subjectUser.setSubjectCode(subjectCode);
                    subjectUser.setUserId(userId);
                    list.add(subjectUser);
                }
            }
        }
        subjectUserDao.save(list);

    }

    @Override
    @Transactional
    public void updateByUserId(Integer userId, Set<String> subjectCodeSet) {
        subjectUserDao.deleteByUserId(userId);
        for (String subjectCode : subjectCodeSet) {
            SubjectUser subjectUser = new SubjectUser();
            subjectUser.setSubjectCode(subjectCode);
            subjectUser.setUserId(userId);
            subjectUserDao.save(subjectUser);
        }
    }

}
