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

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yida.data.common.core.entity.school.EduSchoolHomeNews;
import com.yida.data.common.core.entity.school.EduSchoolManuscript;
import com.yida.data.common.core.entity.system.Dept;
import com.yida.data.common.core.entity.system.EduYidaApp;
import com.yida.data.common.core.utils.AppUtil;
import com.yida.data.common.service.CommonService;
import com.yida.data.school.index.mapper.EduSchoolHomeNewsMapper;
import com.yida.data.school.index.service.EduSchoolHomeNewsService;
import com.yida.data.school.news.mapper.EduSchoolManuscriptMapper;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import lombok.RequiredArgsConstructor;

/**
 * Service实现
 *
 * @author zhanghaijun
 * @date 2021-07-19 17:21:58
 */
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class EduSchoolHomeNewsServiceImpl extends ServiceImpl
        <EduSchoolHomeNewsMapper, EduSchoolHomeNews> implements EduSchoolHomeNewsService {

    private final CommonService commonService;
    private final EduSchoolManuscriptMapper eduSchoolManuscriptMapper;

    @Override
    public void saveNews(EduSchoolHomeNews news) {

        Dept school = commonService.getDept(news.getSchoolId());

        EduSchoolHomeNews exist = null;
        if (news.getId() != null) {
            exist = getById(news.getId());
        }

        saveOrUpdate(news);
        if (exist.getTopNewsId() != null) {
            // 取消之前的的置顶
            if (school.getSchoolType().contains(Dept.TYPE_YIDA_APP)) {
                EduYidaApp yidaApp = commonService.getYidaApp(news.getSchoolId());
                EduSchoolManuscript manuscript = eduSchoolManuscriptMapper.getInfoIncludeDel(exist.getTopNewsId());
                AppUtil.setTop(manuscript.getYidaAppMunascriptId(), school.getYidaAppColId(), 0, yidaApp);
            }
            //当前置顶为空
            if (news.getTopNewsId() == null) {
                update(Wrappers.<EduSchoolHomeNews>lambdaUpdate()
                        .set(EduSchoolHomeNews::getTopNewsId, null)
                        .set(EduSchoolHomeNews::getTopNewsName, null)
                        .eq(EduSchoolHomeNews::getId, news.getId()));
            }
        }
        // 添加当前置顶置顶
        if (news.getTopNewsId() != null && school.getSchoolType().contains(Dept.TYPE_YIDA_APP)) {
            EduYidaApp yidaApp = commonService.getYidaApp(news.getSchoolId());
            EduSchoolManuscript manuscript =
                    eduSchoolManuscriptMapper.getInfoIncludeDel(news.getTopNewsId());
            AppUtil.setTop(manuscript.getYidaAppMunascriptId(), school.getYidaAppColId(), 0, yidaApp);
        }
    }
}
