package jnpf.cultivate.v2.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jnpf.base.entity.SuperBaseEntity;
import jnpf.cultivate.mapper.FtbCultivateOfflineTrainMapper;
import jnpf.cultivate.service.impl.FtbCultivateFileService;
import jnpf.cultivate.v2.service.V2CultivateOfflineTrainService;
import jnpf.model.cultivate.event.JnpfApplicationEvent;
import jnpf.model.cultivate.event.dto.file.FileEventDTO;
import jnpf.model.cultivate.po.FtbCultivateFile;
import jnpf.model.cultivate.po.offline.FtbCultivateOfflineTrain;
import jnpf.model.cultivate.v2.offline.V2CultivateOfflineTrainUpdateDTO;
import jnpf.util.UserProvider;
import jnpf.util.context.SpringContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class V2CultivateOfflineTrainServiceImpl implements V2CultivateOfflineTrainService {

    @Autowired
    private FtbCultivateOfflineTrainMapper ftbCultivateOfflineTrainMapper;

    @Autowired
    private FtbCultivateFileService ftbCultivateFileService;

    /**
     * 修改培训结果
     *
     * @param req
     */
    @Override
    public void updateTrainingResults(V2CultivateOfflineTrainUpdateDTO req) {
        //修改线下培训反馈结果
        String userId = UserProvider.getUser().getUserId();
        LambdaUpdateWrapper<FtbCultivateOfflineTrain> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(SuperBaseEntity.SuperIBaseEntity::getId, req.getId())
                .set(FtbCultivateOfflineTrain::getFeedHeadUserId, userId)
                .set(FtbCultivateOfflineTrain::getHeadContent, req.getHeadContent())
                .set(FtbCultivateOfflineTrain::getFeedBackTime, new Date());
        ftbCultivateOfflineTrainMapper.update(new FtbCultivateOfflineTrain(), updateWrapper);

        //删除就得反馈文件
        LambdaQueryWrapper<FtbCultivateFile> fileRemoveWrapper = Wrappers.lambdaQuery();
        fileRemoveWrapper
                .eq(FtbCultivateFile::getBusinessId, req.getId())
                .eq(FtbCultivateFile::getType, FileEventDTO.FileType.OFFLINE_TRAINING_FEEDBACK.getType());
        ftbCultivateFileService.remove(fileRemoveWrapper);

        // 附件文件
        if (CollUtil.isNotEmpty(req.getFiles())) {
            SpringContext.getApplicationContext().publishEvent(new JnpfApplicationEvent<>(FileEventDTO.builder()
                    .files(req.getFiles())
                    .businessTypeID(req.getId())
                    .type(FileEventDTO.FileType.OFFLINE_TRAINING_FEEDBACK)
                    .build()));
        }
    }
}
