package com.yida.data.school.letter.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yida.data.common.core.entity.letter.EduLetterBoxReplyPerson;
import com.yida.data.common.core.entity.user.EduStaff;
import com.yida.data.school.dto.letterbox.LetterBoxConfigDTO;
import com.yida.data.school.letter.mapper.EduLetterBoxReplyPersonMapper;
import com.yida.data.school.letter.service.EduLetterBoxConfigService;
import com.yida.data.school.letter.service.EduLetterBoxReplyPersonService;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ccl
 */
@RefreshScope
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class EduLetterBoxReplyPersonServiceImpl extends ServiceImpl
        <EduLetterBoxReplyPersonMapper, EduLetterBoxReplyPerson> implements EduLetterBoxReplyPersonService {

    private final EduLetterBoxConfigService configService;

    /**
     * 查询对应回复人员列表
     * @param schoolId
     * @return
     */
    @Override
    public List<EduLetterBoxReplyPerson> findReplyPerson(Long schoolId) {

        return list(Wrappers.query(new EduLetterBoxReplyPerson()).lambda().eq(EduLetterBoxReplyPerson::getSchoolId,schoolId));
    }

    /**
     * 新增或修改回复人员
     * @param replyPeoples
     * @param schoolId
     */
    @Override
    public void saveOrUpdateReplyPerson(List<EduLetterBoxReplyPerson> replyPeoples, Long schoolId) {
        //删除历史配置
        remove(Wrappers.query(new EduLetterBoxReplyPerson()).lambda().eq(EduLetterBoxReplyPerson::getSchoolId,schoolId));
        //配置新数据
        saveBatch(replyPeoples);
    }

    /**
     * @param config   配置详细
     * @param schoolId 学校id
     */
    @Override
    public void saveOrUpdateConfig(LetterBoxConfigDTO config, Long schoolId) {
        List<EduStaff> staffs = config.getReplyPerson();
        List<EduLetterBoxReplyPerson> replies = new ArrayList<>();

        for (EduStaff person : staffs) {
            EduLetterBoxReplyPerson replyPerson = new EduLetterBoxReplyPerson();
            replyPerson.setSchoolId(schoolId);
            replyPerson.setUserId(person.getId());
            replies.add(replyPerson);
        }
        saveOrUpdateReplyPerson(replies,schoolId);
        configService.saveOrUpdateBanner(config.getBannerList(),schoolId);
    }
}
