package com.diagbot.facade;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.diagbot.entity.ModuleDetail;
import com.diagbot.entity.QuestionInfo;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.enums.TagTypeEnum;
import com.diagbot.service.ModuleDetailService;
import com.diagbot.service.QuestionInfoService;
import com.diagbot.service.impl.ModuleDetailServiceImpl;
import com.diagbot.util.DateUtil;
import com.diagbot.util.ListUtil;
import com.diagbot.util.StringUtil;
import com.diagbot.util.UserUtils;
import com.diagbot.vo.AddModuleDetailVO;
import com.diagbot.vo.AddModuleInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author:zhoutg
 * @time: 2018/11/23 11:37
 */
@Component
public class ModuleDetailFacade extends ModuleDetailServiceImpl {

    @Autowired
    private ModuleInfoFacade moduleInfoFacade;
    @Autowired
    @Qualifier("moduleDetailServiceImpl")
    private ModuleDetailService moduleDetailService;
    @Autowired
    private QuestionFacade questionFacade;
    @Autowired
    @Qualifier("questionInfoServiceImpl")
    private QuestionInfoService questionInfoService;
    /**
     * 根据questionId删除明细
     *
     * @param map
     * @return
     */
    public void deleteByQuestionIdFac(Map map) {
        this.deleteByQuestionIds(map);
    }


    /**
     * 根据moduleId删除明细
     *
     * @param map
     * @return
     */
    public void deleteByModuleIdFac(Map map) {
        this.deleteByModuleIds(map);
    }

    /**
     * 添加模板明细
     *
     * @param addModuleInfoVO
     * @return
     */
    public Boolean saveOrUpdateInfos(AddModuleInfoVO addModuleInfoVO,Long moduleId){
        String userId = UserUtils.getCurrentPrincipleID();
        Date now = DateUtil.now();
        //如果该模板添加过明细，先删除
        UpdateWrapper<ModuleDetail> moduleDetailUpdateWrapper = new UpdateWrapper<>();
        moduleDetailUpdateWrapper.eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq("module_id",moduleId)
                .set("is_deleted",IsDeleteEnum.Y.getKey())
                .set("modifier",userId)
                .set("gmt_modified",now);
        this.update(new ModuleDetail(),moduleDetailUpdateWrapper);
        //查询自定义标签的id
        List<String> textList = new ArrayList<>();
        for(AddModuleDetailVO addModuleDetailVO:addModuleInfoVO.getModelDetils()){
            if(StringUtil.isNotEmpty(addModuleDetailVO.getText())){
                textList.add(addModuleDetailVO.getText());
            }
        }
        QueryWrapper<QuestionInfo> questionInfoQueryWrapper = new QueryWrapper<>();
        questionInfoQueryWrapper.eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq("tag_type", TagTypeEnum.T8.getKey())
                .eq("type", addModuleInfoVO.getTextType())
                .in("name",textList);
        List<QuestionInfo> questionInfoList = questionFacade.list(questionInfoQueryWrapper);
        //将标签id放入map
        Map<String,Long> questionIdMap = new HashMap<>();
        for (AddModuleDetailVO addModuleDetailVO: addModuleInfoVO.getModelDetils()) {
            if(StringUtil.isNotEmpty(addModuleDetailVO.getText())){
                questionIdMap = questionInfoList.stream().collect(Collectors.toMap(QuestionInfo::getTagName,questionInfo -> questionInfo.getId()));
            }
        }
        QuestionInfo addquestionInfo = null;
        List<QuestionInfo> addQuestionInfoList = new ArrayList<>();
        //循环给questionId赋值，如果遇到赋值失败的则是没有questionID，执行添加
        for (AddModuleDetailVO addModuleDetailVO:addModuleInfoVO.getModelDetils()) {
            if (StringUtil.isNotEmpty(addModuleDetailVO.getText())){
                addModuleDetailVO.setQuestionId(questionIdMap.get(addModuleDetailVO.getText()));
                if(addModuleDetailVO.getQuestionId() == null && addModuleDetailVO.getText() != null){
                    addquestionInfo = new QuestionInfo();
                    addquestionInfo.setModifier(userId);
                    addquestionInfo.setCreator(userId);
                    addquestionInfo.setGmtCreate(now);
                    addquestionInfo.setGmtModified(now);
                    addquestionInfo.setTagType(TagTypeEnum.T8.getKey());
                    addquestionInfo.setTagName(addModuleDetailVO.getText());
                    addquestionInfo.setName(addModuleDetailVO.getText());
                    addquestionInfo.setType(addModuleInfoVO.getTextType());
                    addquestionInfo.setSubType(1);
                    addquestionInfo.setName(addModuleDetailVO.getText());
                    if(!addQuestionInfoList.contains(addquestionInfo)){
                        addQuestionInfoList.add(addquestionInfo);
                    }
                }
            }
        }
        questionInfoService.saveBatch(addQuestionInfoList);
        //查询自定义标签的id
        QueryWrapper<QuestionInfo> questionInfoQueryWrapper1 = new QueryWrapper<>();
        questionInfoQueryWrapper.eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq("type", addModuleInfoVO.getTextType())
                .eq("tag_type", TagTypeEnum.T8.getKey());
        List<QuestionInfo> questionInfoList1 = questionFacade.list(questionInfoQueryWrapper1);
        if(ListUtil.isNotEmpty(questionInfoList1)){
            for (QuestionInfo questionInfo:questionInfoList1) {
                if(StringUtil.isNotEmpty(questionInfo.getTagName())){
                    questionIdMap.put(questionInfo.getTagName(),questionInfo.getId());
                }
            }
        }
        //二次赋值保证每一个questionId都有值
        ModuleDetail moduleDetail = null;
        List<ModuleDetail> moduleDetailList = new ArrayList<>();
        for(int i = 0; i < addModuleInfoVO.getModelDetils().size(); i++){
            moduleDetail = new ModuleDetail();
            moduleDetail.setModuleId(moduleId);
            moduleDetail.setCreator(userId);
            moduleDetail.setModifier(userId);
            moduleDetail.setGmtCreate(now);
            moduleDetail.setGmtModified(now);
            moduleDetail.setOrderNo(i+1);
            moduleDetail.setRelationModule(addModuleInfoVO.getModelDetils().get(i).getRelationModule());
            if (StringUtil.isNotEmpty(addModuleInfoVO.getModelDetils().get(i).getText())){
                moduleDetail.setQuestionId(questionIdMap.get(addModuleInfoVO.getModelDetils().get(i).getText()));
            }else {
                moduleDetail.setQuestionId(addModuleInfoVO.getModelDetils().get(i).getQuestionId());
            }
            moduleDetailList.add(moduleDetail);
        }
        //添加模板明细
        moduleDetailService.saveBatch(moduleDetailList);
        return true;
    }
}
