package com.rongwei.trainingcommon.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rongwei.rwadmincommon.system.vo.SysUserVo;
import com.rongwei.rwcommon.base.BaseDo;
import com.rongwei.rwcommon.base.R;
import com.rongwei.rwcommon.utils.SecurityUtil;
import com.rongwei.rwcommon.utils.StringUtils;
import com.rongwei.training.domain.*;
import com.rongwei.training.vo.PreviewTrainDemandVo;
import com.rongwei.training.vo.TrainingDemandVo;
import com.rongwei.trainingcommon.sys.dao.*;
import com.rongwei.trainingcommon.sys.service.TrainingDemandService;
import com.rongwei.trainingcommon.sys.service.TrainingSendNotifyService;
import com.rongwei.trainingcommon.sys.utils.TrainingListCopyUtils;
import com.rongwei.trainingcommon.sys.utils.TrainingUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import static com.rongwei.safecommon.utils.CXCommonUtils.aFewDaysApart;
import static com.rongwei.safecommon.utils.SaveConstans.DemandState.RELEASE;

/**
 * TrainingDemandService class
 *
 * @author XH
 * @date 2023/11/24
 */
@Service
public class TrainingDemandServiceImpl implements TrainingDemandService {
    private final Logger log = LoggerFactory.getLogger(this.getClass().getName());

    @Autowired
    private TrainingDemandQuestionDao trainingDemandQuestionDao;
    @Autowired
    private TrainingDemandQuestionOptionDao trainingDemandQuestionOptionDao;
    @Autowired
    private TrainingDemandSurveyCustomDetailDao trainingDemandSurveyCustomDetailDao;
    @Autowired
    private TrainingDemandSurveyDao trainingDemandSurveyDao;
    @Autowired
    private TrainingDemandTempDao trainingDemandTempDao;
    @Autowired
    private TrainingDemandTempDetailDao trainingDemandTempDetailDao;
    @Autowired
    private TrainingDemandTempQuestionOptionDao trainingDemandTempQuestionOptionDao;
    @Autowired
    private TrainingDemandSurveyTempDetailDao trainingDemandSurveyTempDetailDao;
    @Autowired
    private TrainingDemandQuestionBackupsServiceImpl trainingDemandQuestionBackupsServiceImpl;
    @Autowired
    private TrainingDemandQuestionOptionBackupsServiceImpl trainingDemandQuestionOptionBackupsServiceImpl;
    @Autowired
    private TrainingDemandSurveyBackupsServiceImpl trainingDemandSurveyBackupsServiceImpl;
    @Autowired
    private TrainingDemandSurveyCustomDetailBackupsServiceImpl trainingDemandSurveyCustomDetailBackupsServiceImpl;
    @Autowired
    private TrainingDemandTempBackupsServiceImpl trainingDemandTempBackupsServiceImpl;
    @Autowired
    private DemandSurveyContentContentServiceImpl demandSurveyContentServiceImpl;
    @Autowired
    private TrainingDemandSurveyBackupsDao trainingDemandSurveyBackupsDao;
    @Autowired
    private TraningCommonDao traningCommonDao;
    @Autowired
    private DemandSurveyContentDao demandSurveyContentDao;
    @Autowired
    private DemandSurveyUserAnswerServiceImpl demandSurveyUserAnswerService;
    @Autowired
    private TrainingSendNotifyService sendNotifyService;

    public static final String ERROR_MSG = "问卷调查发布失败";
    /**
     * 全员参与问卷调查
     */
    public static final String FULL_PARTICIPATION = "y";

    @Override
    public R releaseTrainDemand(Map<String, Object> parameter) {
        String id = parameter.getOrDefault("id", "").toString();
        TrainingDemandSurveyDo trainingDemandSurveyDo = trainingDemandSurveyDao.selectById(id);
        if (trainingDemandSurveyDo == null) {
            log.error("无法通过id：{},获取到培训需求调查信息", trainingDemandSurveyDo);
            return R.error(String.format("%s原因为:%s", ERROR_MSG, "无法获取到问卷调查信息"));
        }
        if (RELEASE.equals(trainingDemandSurveyDo.getState())) {
            log.error("调查问卷 ：{}已发布无法再次发布", trainingDemandSurveyDo.getName());
            return R.error("调查问卷已发布");
        }
        List<DemandSurveyContentDo> saveDemandSurveyContentDos = new ArrayList<>();
        /******************************获取参与此次问卷的用户信息*********************************************/
        Set<String> participantUserId = getParticipantUser(trainingDemandSurveyDo);
        log.info("参与本次问卷调查的员工数为:{}", participantUserId.size());
        if (participantUserId.size() == 0) {
            log.error("本次问卷调查参与人数为0");
            return R.error(String.format("%s原因为:%s", ERROR_MSG, "暂无问卷参与人"));
        }
        /******************************开始复制业务数据*********************************************/
        // 调查问卷自定义信息
        List<TrainingDemandSurveyCustomDetailDo> surveyCustomDetailDos = trainingDemandSurveyCustomDetailDao.selectList(new LambdaQueryWrapper<TrainingDemandSurveyCustomDetailDo>()
                .eq(TrainingDemandSurveyCustomDetailDo::getSurverid, id).orderByAsc(TrainingDemandSurveyCustomDetailDo::getNum));
        // 调查问卷模板信息
        List<TrainingDemandSurveyTempDetailDo> surveyTempDetailDos = trainingDemandSurveyTempDetailDao.selectList(new LambdaQueryWrapper<TrainingDemandSurveyTempDetailDo>()
                .eq(TrainingDemandSurveyTempDetailDo::getSurverid, id).orderByAsc(TrainingDemandSurveyTempDetailDo::getNum));
        if (surveyTempDetailDos.isEmpty()) {
            log.error("问卷项目信息为空");
            return R.error("问卷项目信息为空");
        }
        // 模板信息
        List<TrainingDemandTempDo> trainingDemandTempDos = trainingDemandTempDao.selectList(new LambdaQueryWrapper<TrainingDemandTempDo>()
                .in(TrainingDemandTempDo::getId, surveyTempDetailDos.stream()
                        .map(TrainingDemandSurveyTempDetailDo::getTempid)
                        .collect(Collectors.toList())));
        if(trainingDemandTempDos.isEmpty()){
            log.error("培训模板不存在");
            return R.error("培训模板不存在");
        }
        // 模板子表
        List<TrainingDemandTempDetailDo> trainingDemandTempDetailDos = trainingDemandTempDetailDao.selectList(
                new LambdaQueryWrapper<TrainingDemandTempDetailDo>()
                .in(TrainingDemandTempDetailDo::getDemandtempid,
                        trainingDemandTempDos.stream().map(TrainingDemandTempDo::getId).collect(Collectors.toList()))
                        .orderByAsc(TrainingDemandTempDetailDo::getNum));
        // 模板问题选项记录表
        List<TrainingDemandTempQuestionOptionDo> trainingDemandTempQuestionOptionDos = trainingDemandTempQuestionOptionDao.selectList(new LambdaQueryWrapper<TrainingDemandTempQuestionOptionDo>()
                .in(TrainingDemandTempQuestionOptionDo::getDemandtempdetailid,
                        trainingDemandTempDetailDos.stream().map(TrainingDemandTempDetailDo::getId).collect(Collectors.toList()))
                .orderByAsc(TrainingDemandTempQuestionOptionDo::getNum));

        String userIds = participantUserId.stream().map(info -> info.split("-;-")[0]).collect(Collectors.joining(","));
        String userNames = participantUserId.stream().map(info -> info.split("-;-")[1]).collect(Collectors.joining(","));
        /************调查主表备份*************/
        TrainingDemandSurveyBackupsDo saveDemandSurveyBackupsDo = generateSurveyBackups(trainingDemandSurveyDo, userIds, userNames);
        /************自定义内容备份*************/
        List<TrainingDemandSurveyCustomDetailBackupsDo> saveDemandSurveyCustomDetailBackupsDos = TrainingListCopyUtils.copyListProperties(surveyCustomDetailDos, TrainingDemandSurveyCustomDetailBackupsDo::new);
        saveDemandSurveyCustomDetailBackupsDos.forEach(info -> info.setSurverid(saveDemandSurveyBackupsDo.getId()));
        /************其他数据备份*************/
        // 保存问题数据备份
        List<TrainingDemandQuestionBackupsDo> saveDemandQuestionBackupsDos = new ArrayList<>();
        // 保存问题选项数据备份
        List<TrainingDemandQuestionOptionBackupsDo> saveDemandQuestionOptionBackupsDos = new ArrayList<>();
        // 保存模板数据备份
        List<TrainingDemandTempBackupsDo> saveDemandTempBackupsDo = new ArrayList<>();
        int num = 1;
        int questionNum= 1;
        DemandSurveyContentDo addDemandSurveyDo;
        for (int i = 0; i < surveyTempDetailDos.size(); i++) {
            /************ 问卷调查模板内容备份*************/
            TrainingDemandSurveyTempDetailDo surveyTempDetail = surveyTempDetailDos.get(i);
            /******************模板备份************************/
            TrainingDemandTempDo trainingDemandTempDo = trainingDemandTempDos.stream()
                    .filter(info -> info.getId().equals(surveyTempDetail.getTempid()))
                    .findFirst()
                    .orElse(null);
            TrainingDemandTempBackupsDo trainingDemandTempBackupsDo = new TrainingDemandTempBackupsDo();
            trainingDemandTempBackupsDo.setId(SecurityUtil.getUUID());
            trainingDemandTempBackupsDo.setSurverid(saveDemandSurveyBackupsDo.getId());
            trainingDemandTempBackupsDo.setName(surveyTempDetail.getTempname());
            trainingDemandTempBackupsDo.setYear(trainingDemandTempDo.getYear());
            trainingDemandTempBackupsDo.setNum(i);
            saveDemandTempBackupsDo.add(trainingDemandTempBackupsDo);
            /************ 循环问题明细*************/
            List<TrainingDemandTempDetailDo> demandTempDetail = trainingDemandTempDetailDos.stream()
                    .filter(info -> trainingDemandTempDo.getId().equals(info.getDemandtempid()))
                    .collect(Collectors.toList());
            for (int j = 0; j < demandTempDetail.size(); j++) {
                TrainingDemandTempDetailDo trainingDemandTempDetailDo = demandTempDetail.get(j);
                /******************问题备份************************/
                TrainingDemandQuestionBackupsDo questionBackupsDo = new TrainingDemandQuestionBackupsDo();
                questionBackupsDo.setId(SecurityUtil.getUUID());
                questionBackupsDo.setName(trainingDemandTempDetailDo.getContent());
                questionBackupsDo.setQuestiontype(trainingDemandTempDetailDo.getQuestiontype());
                questionBackupsDo.setSurveyid(surveyTempDetail.getId());
                questionBackupsDo.setTempid(trainingDemandTempBackupsDo.getId());
                questionBackupsDo.setNum(questionNum);
                questionNum++;
                saveDemandQuestionBackupsDos.add(questionBackupsDo);
                /************ 问题答案备份 *************/
                List<TrainingDemandTempQuestionOptionDo> questionOptions = trainingDemandTempQuestionOptionDos.stream()
                        .filter(info -> trainingDemandTempDetailDo.getQuestionid().equals(info.getQuestionid()) &&
                                trainingDemandTempDetailDo.getId().equals(info.getDemandtempdetailid())
                        ).collect(Collectors.toList());
                List<TrainingDemandQuestionOptionBackupsDo> addOptions = TrainingListCopyUtils.copyListProperties(questionOptions, TrainingDemandQuestionOptionBackupsDo::new);
                addOptions.forEach(info -> {
                    info.setQuestionid(questionBackupsDo.getId());
                });
                saveDemandQuestionOptionBackupsDos.addAll(addOptions);
                // 生成用户问卷
                saveDemandSurveyContentDos.add(generateUserDemandSurvey(num, questionBackupsDo, trainingDemandTempBackupsDo,
                        saveDemandSurveyBackupsDo, addOptions));
                num++;
            }
        }
        for (int k = 0; k < saveDemandSurveyCustomDetailBackupsDos.size(); k++) {
            addDemandSurveyDo = new DemandSurveyContentDo();
            addDemandSurveyDo.setId(SecurityUtil.getUUID());
            addDemandSurveyDo.setNum(num);
            addDemandSurveyDo.setSurverid(saveDemandSurveyBackupsDo.getId());
            addDemandSurveyDo.setSurvername(saveDemandSurveyBackupsDo.getName());
            addDemandSurveyDo.setQuestionid(saveDemandSurveyCustomDetailBackupsDos.get(k).getId());
            addDemandSurveyDo.setQuestionname(saveDemandSurveyCustomDetailBackupsDos.get(k).getContent());
            addDemandSurveyDo.setQuestiontype(saveDemandSurveyCustomDetailBackupsDos.get(k).getQuestiontype());
            saveDemandSurveyContentDos.add(addDemandSurveyDo);
            num++;
        }
        // 数据存表
        saveData(saveDemandSurveyBackupsDo, saveDemandSurveyCustomDetailBackupsDos,
                saveDemandQuestionBackupsDos, saveDemandQuestionOptionBackupsDos,
                saveDemandSurveyContentDos, saveDemandTempBackupsDo, trainingDemandSurveyDo);
        // 发送消息提醒
        sendNotifyService.sendQuestionnaireSurveyNotify(Arrays.asList(saveDemandSurveyBackupsDo));
        return R.ok();
    }

    /**
     * 预览培训需求调查
     *
     * @param previewTrainDemandVo
     * @return
     */
    @Override
    public R previewTrainDemand(PreviewTrainDemandVo previewTrainDemandVo) {
        List<String> tempIdList = previewTrainDemandVo.getTempIdList();
        if (tempIdList == null || previewTrainDemandVo.getTempIdList().isEmpty()) {
            return R.error("培训模板信息为空");
        }
        // 问题模板信息
        List<TrainingDemandTempDo> trainingDemandTempDos = trainingDemandTempDao.selectList(new LambdaQueryWrapper<TrainingDemandTempDo>()
                .in(TrainingDemandTempDo::getId, tempIdList).eq(BaseDo::getDeleted, "0"));
        // 问题模板问题
        List<TrainingDemandTempDetailDo> trainingDemandTempDetailDos = trainingDemandTempDetailDao.selectList(
                new LambdaQueryWrapper<TrainingDemandTempDetailDo>()
                .in(TrainingDemandTempDetailDo::getDemandtempid, tempIdList)
                        .eq(BaseDo::getDeleted, "0").orderByAsc(TrainingDemandTempDetailDo::getNum));
        List<String> questionIdList = trainingDemandTempDetailDos.stream().map(TrainingDemandTempDetailDo::getQuestionid).collect(Collectors.toList());
        // 问题答案
        List<TrainingDemandQuestionOptionDo> trainingDemandQuestionDos = trainingDemandQuestionOptionDao.selectList(new LambdaQueryWrapper<TrainingDemandQuestionOptionDo>()
                .in(TrainingDemandQuestionOptionDo::getQuestionid, questionIdList)
                .eq(BaseDo::getDeleted, "0")
                .orderByAsc(TrainingDemandQuestionOptionDo::getNum));

        List<TrainingDemandVo> trainingDemandVoList = new ArrayList<>();
        int num = 1;
        // 问题模板
        for (int i = 0; i < tempIdList.size(); i++) {
            int finalI = i;
            TrainingDemandTempDo trainingDemandTempDo = trainingDemandTempDos.stream().filter(info->info.getId().equals(tempIdList.get(finalI))).findFirst().get();
            // 当前模板拥有的问题
            List<TrainingDemandTempDetailDo> currentTempQuestion = trainingDemandTempDetailDos.stream()
                    .filter(info -> info.getDemandtempid().equals(trainingDemandTempDo.getId())).collect(Collectors.toList());
            for (int j = 0; j < currentTempQuestion.size(); j++) {
                TrainingDemandTempDetailDo currentQuestion = currentTempQuestion.get(j);
                // 问题答案
                List<String> collect = trainingDemandQuestionDos.stream().filter(info -> currentQuestion.getQuestionid().equals(info.getQuestionid()))
                        .map(TrainingDemandQuestionOptionDo::getContent)
                        .collect(Collectors.toList());
                TrainingDemandVo trainingDemandVo = new TrainingDemandVo();
                trainingDemandVo.setModelName(trainingDemandTempDo.getName());
                trainingDemandVo.setNum(num);
                trainingDemandVo.setQuestionContent(currentQuestion.getContent());
                trainingDemandVo.setQuestionType(currentQuestion.getQuestiontype());
                trainingDemandVo.setQuestionOptions(collect);
                num++;
                trainingDemandVoList.add(trainingDemandVo);
            }
        }
        LinkedHashMap<String, List<TrainingDemandVo>> collect = trainingDemandVoList.stream().collect(Collectors.groupingBy(TrainingDemandVo::getModelName, LinkedHashMap::new, Collectors.toList()));
        List<TrainingDemandVo> customerDataList = previewTrainDemandVo.getCustomerDataList();
        if (customerDataList != null || !customerDataList.isEmpty()) {
            collect.put("customQuestion", customerDataList);
        }
        return R.ok(collect);
    }

    /**
     * 获取当前登录用的调查问卷信息
     *
     * @param userId
     * @return
     */
    @Override
    public R getInfoByUser(String userId) {
        if (StringUtils.isBlank(userId)) {
            SysUserVo currentUser = TrainingUtils.getCurrentUser();
            userId = currentUser.getId();
        }
        if (StringUtils.isBlank(userId)) {
            log.debug("用户ID 为空");
            return R.ok();
        }
        List<TrainingDemandSurveyBackupsDo> list = trainingDemandSurveyBackupsDao.getValidListData(userId);
        return R.ok(list);
    }

    /**
     * 问卷
     *
     * @param id
     * @return
     */
    @Override
    public R showQuestionnaire(String id, boolean showAnswer) {
        if (StringUtils.isBlank(id)) {
            log.debug("参数异常");
            return R.ok();
        }

        TrainingDemandSurveyBackupsDo trainingDemandSurveyBackupsDo = trainingDemandSurveyBackupsServiceImpl.getById(id);
        if (trainingDemandSurveyBackupsDo == null) {
            log.debug("问卷不存在");
            return R.error("当前问卷已结束");
        }
        SysUserVo currentUser = TrainingUtils.getCurrentUser();
        // 不需要显示答案时如果当前用户已参与培训 则提示
        if (!showAnswer && currentUser != null && StringUtils.isNotBlank(trainingDemandSurveyBackupsDo.getParticipatinguserid())
                && trainingDemandSurveyBackupsDo.getParticipatinguserid().contains(currentUser.getId())) {
            log.debug("已参与问卷");
            return R.error("您已参与过当前问卷");
        }

        String oldSurveyId = trainingDemandSurveyBackupsDo.getOldSurveyId();
        TrainingDemandSurveyDo trainingDemandSurveyDo = trainingDemandSurveyDao.selectById(oldSurveyId);
        if (StringUtils.isBlank(trainingDemandSurveyDo.getState()) || !"1".equals(trainingDemandSurveyDo.getState())) {
            log.debug("问卷调查发布状态异常");
            return R.error("问卷调查已关闭");
        }
        if (trainingDemandSurveyDo.getDeadline() != null && aFewDaysApart(trainingDemandSurveyDo.getDeadline()) < 0) {
            log.debug("问卷调查发布状态异常");
            return R.error("问卷调查已结束");
        }

        List<TrainingDemandVo> surveyContent = demandSurveyContentDao.getSurveyContent(id,
                showAnswer ? currentUser == null ? "" : currentUser.getId() : "");

        LinkedHashMap<String, List<TrainingDemandVo>> collect = surveyContent.stream()
                .collect(Collectors.groupingBy(TrainingDemandVo::getModelName, LinkedHashMap::new, Collectors.toList()));
        return R.ok(collect);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R submit(List<TrainingDemandVo> trainingDemandVoList) {
        //  当前登录用户
        SysUserVo currentUser = TrainingUtils.getCurrentUser();
        if (currentUser == null) {
            log.error("无法获取到当前登录人信息");
            return R.error("请重新登录");
        }
        if (trainingDemandVoList == null || trainingDemandVoList.isEmpty()) {
            log.error("问卷答案为空");
            return R.error("请填写问卷调查信息");
        }
        boolean hasEmptySurverId = trainingDemandVoList.stream().anyMatch(info -> StringUtils.isBlank(info.getSurverid()));
        if (hasEmptySurverId) {
            log.error("存在问卷ID为空的数据");
            return R.error("数据异常");
        }
        boolean hasEmptycontentId = trainingDemandVoList.stream().anyMatch(info -> StringUtils.isBlank(info.getContentid()));
        if (hasEmptycontentId) {
            log.error("存在问卷内容ID为空的数据");
            return R.error("数据异常");
        }
        // 获取培训计划ID
        String surverid = trainingDemandVoList.get(0).getSurverid();
        Date currentDate = new Date();
        TrainingDemandSurveyBackupsDo trainingDemandSurveyBackupsDo = trainingDemandSurveyBackupsDao.selectById(surverid);
        // 判断是否以参与过该问卷
        String participatingUserList = trainingDemandSurveyBackupsDo.getParticipatinguserid();
        if(StringUtils.isNotBlank(participatingUserList) && participatingUserList.contains(currentUser.getId())){
            log.error("当前用户以参与过问卷");
            return R.error("您已提交过问卷!无法再次提交");
        }
        List<DemandSurveyUserAnswerDo> saveData = trainingDemandVoList.stream().map(info -> {
            DemandSurveyUserAnswerDo demandSurveyUserAnswerDo = new DemandSurveyUserAnswerDo();
            demandSurveyUserAnswerDo.setId(SecurityUtil.getUUID());
            demandSurveyUserAnswerDo.setNum(info.getNum());
            demandSurveyUserAnswerDo.setAnswer(info.getUserAnswer());
            demandSurveyUserAnswerDo.setSurverid(info.getSurverid());
            demandSurveyUserAnswerDo.setSurvercontentid(info.getContentid());
            demandSurveyUserAnswerDo.setQuestiontype(info.getQuestionType());
            if (info.getQuestionOptions() != null && !info.getQuestionOptions().isEmpty()) {
                demandSurveyUserAnswerDo.setOptions(String.join("-;-", info.getQuestionOptions()));
            }
            demandSurveyUserAnswerDo.setCreateuserid(currentUser.getId());
            demandSurveyUserAnswerDo.setCreateusername(currentUser.getName());
            demandSurveyUserAnswerDo.setCreatedate(currentDate);
            demandSurveyUserAnswerDo.setModifyuserid(currentUser.getId());
            demandSurveyUserAnswerDo.setModifyusername(currentUser.getName());
            demandSurveyUserAnswerDo.setModifydate(currentDate);
            demandSurveyUserAnswerDo.setDeleted("0");
            demandSurveyUserAnswerDo.setTenantid(trainingDemandSurveyBackupsDo.getTenantid());
            return demandSurveyUserAnswerDo;
        }).collect(Collectors.toList());

        // 保存用户问卷结果
        demandSurveyUserAnswerService.saveBatch(saveData);
        // 更新问卷调查已参与用户和未参与用户
        trainingDemandSurveyBackupsDao.updateParticipant(currentUser.getId(), currentUser.getName(), surverid);
        return R.ok();
    }

    @Override
    public R releasedPreviewTrainDemand(String id) {
        if (StringUtils.isBlank(id)) {
            log.debug("参数异常");
            return R.ok();
        }
        List<TrainingDemandSurveyBackupsDo> trainingDemandSurveyBackupsDo = trainingDemandSurveyBackupsServiceImpl
                .list(new LambdaQueryWrapper<TrainingDemandSurveyBackupsDo>().eq(TrainingDemandSurveyBackupsDo::getOldSurveyId,id));
        List<TrainingDemandVo> surveyContent = demandSurveyContentDao.getSurveyContent(trainingDemandSurveyBackupsDo.get(0).getId(), "");
        LinkedHashMap<String, List<TrainingDemandVo>> collect = surveyContent.stream()
                .collect(Collectors.groupingBy(TrainingDemandVo::getModelName, LinkedHashMap::new, Collectors.toList()));
        return R.ok(collect);
    }

    /**
     * 数据保存
     *
     * @param saveDemandSurveyBackupsDo              问卷调查
     * @param saveDemandSurveyCustomDetailBackupsDos 培训内容自定义调查表
     * @param saveDemandQuestionBackupsDos
     * @param saveDemandQuestionOptionBackupsDos
     * @param saveDemandSurveyContentDos
     * @param saveDemandTempBackupsDo
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveData(TrainingDemandSurveyBackupsDo saveDemandSurveyBackupsDo,
                         List<TrainingDemandSurveyCustomDetailBackupsDo> saveDemandSurveyCustomDetailBackupsDos,
                         List<TrainingDemandQuestionBackupsDo> saveDemandQuestionBackupsDos,
                         List<TrainingDemandQuestionOptionBackupsDo> saveDemandQuestionOptionBackupsDos,
                         List<DemandSurveyContentDo> saveDemandSurveyContentDos,
                         List<TrainingDemandTempBackupsDo> saveDemandTempBackupsDo,
                         TrainingDemandSurveyDo trainingDemandSurveyDo) {
        if (!saveDemandQuestionBackupsDos.isEmpty()) {
            trainingDemandQuestionBackupsServiceImpl.saveOrUpdateBatch(saveDemandQuestionBackupsDos);
        }
        if (!saveDemandQuestionOptionBackupsDos.isEmpty()) {
            trainingDemandQuestionOptionBackupsServiceImpl.saveOrUpdateBatch(saveDemandQuestionOptionBackupsDos);
        }
        trainingDemandSurveyBackupsServiceImpl.saveOrUpdate(saveDemandSurveyBackupsDo);
        if (!saveDemandSurveyCustomDetailBackupsDos.isEmpty()) {
            trainingDemandSurveyCustomDetailBackupsServiceImpl.saveOrUpdateBatch(saveDemandSurveyCustomDetailBackupsDos);
        }
        if (!saveDemandTempBackupsDo.isEmpty()) {
            trainingDemandTempBackupsServiceImpl.saveOrUpdateBatch(saveDemandTempBackupsDo);
        }
        if (!saveDemandSurveyContentDos.isEmpty()) {
            demandSurveyContentServiceImpl.saveOrUpdateBatch(saveDemandSurveyContentDos);
        }
        trainingDemandSurveyDo.setState(RELEASE);
        trainingDemandSurveyDo.setReleasetime(new Date());
        trainingDemandSurveyDao.updateById(trainingDemandSurveyDo);
    }

    /**
     * 生成用户调查问卷
     *
     * @return
     */
    private DemandSurveyContentDo generateUserDemandSurvey(int num,
                                                           TrainingDemandQuestionBackupsDo questionBackupsDo,
                                                           TrainingDemandTempBackupsDo trainingDemandTempBackupsDo,
                                                           TrainingDemandSurveyBackupsDo trainingDemandSurveyBackupsDo,
                                                           List<TrainingDemandQuestionOptionBackupsDo> addOptions) {
        DemandSurveyContentDo demandSurveyDo = new DemandSurveyContentDo();
        demandSurveyDo.setId(SecurityUtil.getUUID());
        demandSurveyDo.setNum(num);
        demandSurveyDo.setSurverid(trainingDemandSurveyBackupsDo.getId());
        demandSurveyDo.setSurvername(trainingDemandSurveyBackupsDo.getName());
        demandSurveyDo.setTempid(trainingDemandTempBackupsDo.getId());
        demandSurveyDo.setTempname(trainingDemandTempBackupsDo.getName());
        demandSurveyDo.setQuestionid(questionBackupsDo.getId());
        demandSurveyDo.setQuestionname(questionBackupsDo.getName());
        demandSurveyDo.setQuestiontype(questionBackupsDo.getQuestiontype());
        demandSurveyDo.setOptions(addOptions.stream().map(TrainingDemandQuestionOptionBackupsDo::getContent).collect(Collectors.joining("-;-")));
        return demandSurveyDo;
    }

    /**
     * 调查主表备份
     *
     * @param trainingDemandSurveyDo
     * @param userIds
     * @param userNames
     * @return
     */
    private TrainingDemandSurveyBackupsDo generateSurveyBackups(TrainingDemandSurveyDo trainingDemandSurveyDo, String userIds, String userNames) {
        TrainingDemandSurveyBackupsDo trainingDemandSurveyBackupsDo = new TrainingDemandSurveyBackupsDo();
        BeanUtils.copyProperties(trainingDemandSurveyDo, trainingDemandSurveyBackupsDo);
        trainingDemandSurveyBackupsDo.setId(SecurityUtil.getUUID());
        trainingDemandSurveyBackupsDo.setOldSurveyId(trainingDemandSurveyDo.getId());
        trainingDemandSurveyBackupsDo.setParticipateuserid(userIds);
        trainingDemandSurveyBackupsDo.setParticipateusername(userNames);
        trainingDemandSurveyBackupsDo.setNoparticipatinguserid(userIds);
        trainingDemandSurveyBackupsDo.setNoparticipatingusername(userNames);
        return trainingDemandSurveyBackupsDo;
    }

    /**
     * 获取参与培训的员工
     *
     * @param trainingDemandSurveyDo
     * @return
     */
    private Set<String> getParticipantUser(TrainingDemandSurveyDo trainingDemandSurveyDo) {

        if (FULL_PARTICIPATION.equals(trainingDemandSurveyDo.getFullparticipation())) {
            log.debug("全员参与培训");
            String factoryId = trainingDemandSurveyDo.getTenantid();
            return traningCommonDao.getAllUserIdAndNameByOrgId(Arrays.asList(factoryId));
        }
        // 参与培训的员工信息
        Set<String> participantUserIdList = new HashSet<>();
        // 参与培训的部门
        String participatedeptid = trainingDemandSurveyDo.getParticipatedeptid();
        if (StringUtils.isNotBlank(participatedeptid)) {
            participantUserIdList = traningCommonDao.getAllUserIdAndNameByOrgId(Arrays.asList(participatedeptid.split(",")));
        }
        // 参与培训的员工
        String participateuserid = trainingDemandSurveyDo.getParticipateuserid();
        if (StringUtils.isNotBlank(participateuserid)) {
            String[] userIds = participateuserid.split(",");
            for (int i = 0; i < userIds.length; i++) {
                participantUserIdList.add(userIds[i]+"-;-"+trainingDemandSurveyDo.getParticipateusername().split(",")[i]);
            }
        }
        // 排除的员工
        String excludeuserid = trainingDemandSurveyDo.getExcludeuserid();
        if (StringUtils.isNotBlank(excludeuserid)) {
            String[] userIds = excludeuserid.split(",");
            for (int i = 0; i < userIds.length; i++) {
                participantUserIdList.remove(userIds[i]+"-;-"+trainingDemandSurveyDo.getExcludeusername().split(",")[i]);
            }
        }
        return participantUserIdList;
    }
}
