package com.diagbot.facade;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.diagbot.client.UserServiceClient;
import com.diagbot.dto.GetModuleDetailInfoDTO;
import com.diagbot.dto.GetModuleInfoOneDTO;
import com.diagbot.dto.GetQuestionInfoDTO;
import com.diagbot.dto.ModuleInfoDTO;
import com.diagbot.dto.ModuleInfoListDTO;
import com.diagbot.dto.RespDTO;
import com.diagbot.entity.DictionaryInfo;
import com.diagbot.entity.ModuleDetail;
import com.diagbot.entity.ModuleInfo;
import com.diagbot.entity.QuestionInfo;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.exception.CommonErrorCode;
import com.diagbot.exception.CommonException;
import com.diagbot.service.impl.ModuleInfoServiceImpl;
import com.diagbot.util.BeanUtil;
import com.diagbot.util.DateUtil;
import com.diagbot.util.ListUtil;
import com.diagbot.util.StringUtil;
import com.diagbot.util.UserUtils;
import com.diagbot.vo.AddModuleInfoVO;
import com.diagbot.vo.GetModuleDetailInfoVO;
import com.diagbot.vo.GetModuleInfoOneVO;
import com.diagbot.vo.GetModuleInfoVO;
import com.diagbot.vo.ModuleGetQuestionInfoVO;
import com.diagbot.vo.UpdateModuleInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
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 ModuleInfoFacade extends ModuleInfoServiceImpl {


    @Autowired
    ModuleDetailFacade moduleDetailFacade;
    @Autowired
    QuestionFacade questionFacade;
    @Autowired
    UserServiceClient userServiceClient;
    @Autowired
    DictionaryFacade dictionaryFacade;

    /**
     * 根据id删除标签模板
     *
     * @param ids
     * @return
     */
    public Boolean deleteByIdsFac(String ids) {
        if (StringUtil.isEmpty(ids)) {
            return true;
        }
        Map paramMap = new HashMap<>();
        paramMap.put("delete", IsDeleteEnum.Y.getKey());
        paramMap.put("ids", Arrays.asList(ids.split(",")));
        paramMap.put("gmtModified", DateUtil.now());
        paramMap.put("modifier", UserUtils.getCurrentPrincipleID());

        //删除模板
        this.deleteByIds(paramMap);

        //删除明细表
        moduleDetailFacade.deleteByModuleIdFac(paramMap);
        return true;
    }

    /**
     * 添加模板
     *
     * @param addModulInfoVO
     * @return
     */
    public Boolean saveModuleInfo(AddModuleInfoVO addModulInfoVO) {
        String userId = UserUtils.getCurrentPrincipleID();
        Date now = DateUtil.now();
        //查询该模板是否添加过
        QueryWrapper<ModuleInfo> moduleInfoQueryWrapper = new QueryWrapper<>();
        moduleInfoQueryWrapper.eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq("name", addModulInfoVO.getName());
        ModuleInfo moduleInfos = this.getOne(moduleInfoQueryWrapper);
        if (null != moduleInfos) {
            throw new CommonException(CommonErrorCode.INSERT_DATA_FAILED,
                    "模板名重复，请勿重复添加");
        }
        ModuleInfo moduleInfo = new ModuleInfo();
        BeanUtil.copyProperties(addModulInfoVO, moduleInfo);
        moduleInfo.setCreator(userId);
        moduleInfo.setModifier(userId);
        moduleInfo.setGmtCreate(now);
        moduleInfo.setGmtModified(now);
        moduleInfo.setType(addModulInfoVO.getType());
        this.save(moduleInfo);
        Long moduleId = moduleInfo.getId();
        return moduleDetailFacade.saveOrUpdateInfos(addModulInfoVO, moduleId);
    }

    /**
     * 修改模板
     *
     * @param updateModuleInfoVO
     * @return
     */
    public Boolean updateModuleInfo(UpdateModuleInfoVO updateModuleInfoVO) {
        String userId = UserUtils.getCurrentPrincipleID();
        UpdateWrapper<ModuleInfo> moduleInfoUpdateWrapper = new UpdateWrapper<>();
        moduleInfoUpdateWrapper.eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq("id", updateModuleInfoVO.getId())
                .set("name", updateModuleInfoVO.getName())
                .set("type", updateModuleInfoVO.getType())
                .set("modifier", userId)
                .set("gmt_modified", DateUtil.now());
        this.update(new ModuleInfo(), moduleInfoUpdateWrapper);
        AddModuleInfoVO addModuleInfoVO = new AddModuleInfoVO();
        BeanUtil.copyProperties(updateModuleInfoVO, addModuleInfoVO);
        return moduleDetailFacade.saveOrUpdateInfos(addModuleInfoVO, updateModuleInfoVO.getId());
    }

    /**
     * 获取标签池信息
     *
     * @param moduleGetQuestionInfoVO
     * @return
     */
    public List<GetQuestionInfoDTO> getQuestionInfos(ModuleGetQuestionInfoVO moduleGetQuestionInfoVO) {
        List<GetQuestionInfoDTO> getQuestionInfoDTOS = questionFacade.moduleGetQuestiongInfoByName(moduleGetQuestionInfoVO);
        return getQuestionInfoDTOS;
    }

    /**
     * 获取子模板
     *
     * @param getModuleInfoVO
     * @return
     */
    public List<ModuleInfoDTO> getModuleInfo(GetModuleInfoVO getModuleInfoVO) {
        //获取模板信息
        QueryWrapper<ModuleInfo> moduleInfoQueryWrapper = new QueryWrapper<>();
        moduleInfoQueryWrapper.eq("is_deleted", IsDeleteEnum.N.getKey());
        if (getModuleInfoVO.getType() != null) {
            moduleInfoQueryWrapper.eq("type", getModuleInfoVO.getType());
        }
        if(ListUtil.isNotEmpty(getModuleInfoVO.getNoIds())){
            moduleInfoQueryWrapper.notIn("id", getModuleInfoVO.getNoIds());
        }
        List<ModuleInfo> moduleInfoList = this.list(moduleInfoQueryWrapper);
        List<Long> moduleIdList = moduleInfoList.stream().map(m -> m.getId()).collect(Collectors.toList());
        //获取模板明细信息
        QueryWrapper<ModuleDetail> moduleDetailQueryWrapper = new QueryWrapper<>();
        moduleDetailQueryWrapper.eq("is_deleted", IsDeleteEnum.N.getKey())
                .in("module_id", moduleIdList);
        List<ModuleDetail> moduleDetailList = moduleDetailFacade.list(moduleDetailQueryWrapper);
        //将模板明细根据模板id放入map
        Map<Long, List<ModuleDetail>> moduleDetailMap = new HashMap<>();
        List<ModuleDetail> allModuleDetials = null;
        for (ModuleInfo moduleInfo : moduleInfoList) {
            allModuleDetials = new ArrayList<>();
            for (ModuleDetail moduleDetail : moduleDetailList) {
                if (moduleInfo.getId().longValue() == moduleDetail.getModuleId().longValue()) {
                    allModuleDetials.add(moduleDetail);
                }
            }
            moduleDetailMap.put(moduleInfo.getId(), allModuleDetials);
        }
        //给ModuleInfoDTO设值
        List<ModuleInfoDTO> moduleInfoDTOList = new ArrayList<>();
        ModuleInfoDTO moduleInfoDTO = null;
        for (ModuleInfo moduleInfo : moduleInfoList) {
            moduleInfoDTO = new ModuleInfoDTO();
            moduleInfoDTO.setId(moduleInfo.getId());
            moduleInfoDTO.setName(moduleInfo.getName());
            moduleInfoDTO.setModuleDetails(moduleDetailMap.get(moduleInfoDTO.getId()));
            moduleInfoDTOList.add(moduleInfoDTO);
        }
        return moduleInfoDTOList;
    }

    /**
     * 模板维护页面获取模板列表
     *
     * @param getModuleInfoVO
     * @return
     */
    public IPage<ModuleInfoListDTO> getModuleInfoList(GetModuleInfoVO getModuleInfoVO) {
        //获取模板信息
        IPage<ModuleInfoListDTO> moduleInfoDTOIPage = this.getModuleInfoListByType(getModuleInfoVO);
        List<String> ids = new ArrayList<>();
        for (ModuleInfoListDTO moduleInfoListDTO : moduleInfoDTOIPage.getRecords()) {
            ids.add(moduleInfoListDTO.getModifier());
        }
        //获取模板类型名称
        QueryWrapper<DictionaryInfo> dictionaryInfoQueryWrapper = new QueryWrapper<>();
        dictionaryInfoQueryWrapper.eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq("group_type", 4)
                .eq("return_type", 1)
                .orderByDesc("order_no");
        List<DictionaryInfo> dictionaryInfoList = dictionaryFacade.list(dictionaryInfoQueryWrapper);
        Map<String, DictionaryInfo> dictionaryInfoMap = dictionaryInfoList.stream().collect(Collectors.toMap(DictionaryInfo::getVal,dictionaryInfo -> dictionaryInfo));
        //获取用户信息
        RespDTO<Map<String, String>> respDTO = userServiceClient.getUserInfoByIds(ids);
        if (respDTO == null || !CommonErrorCode.OK.getCode().equals(respDTO.code)) {
            throw new CommonException(CommonErrorCode.RPC_ERROR,
                    "获取用户信息失败");
        }
        //将用户信息放入实体
        for (ModuleInfoListDTO moduleInfoListDTO : moduleInfoDTOIPage.getRecords()) {
            moduleInfoListDTO.setUserName(respDTO.data.get(moduleInfoListDTO.getModifier()));
            moduleInfoListDTO.setAscriptionName(dictionaryInfoMap.get(String.valueOf(moduleInfoListDTO.getType().intValue())).getName());
        }
        return moduleInfoDTOIPage;
    }

    /**
     * 模板维护修改获取已添加标签信息
     *
     * @param getModuleDetailInfoVO
     * @return
     */
    public List<GetModuleDetailInfoDTO> getModuleDetailInfo(GetModuleDetailInfoVO getModuleDetailInfoVO) {
        List<GetModuleDetailInfoDTO> getModuleDetailInfoDTOList = new ArrayList<>();
        GetModuleDetailInfoDTO getModuleDetailInfoDTO = null;
        //获取模板明细
        QueryWrapper<ModuleDetail> moduleDetailQueryWrapper = new QueryWrapper<>();
        moduleDetailQueryWrapper.eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq("module_id", getModuleDetailInfoVO.getModuleId());
        List<ModuleDetail> moduleDetailList = moduleDetailFacade.list(moduleDetailQueryWrapper);
        //获取标签信息
        QueryWrapper<QuestionInfo> questionInfoQueryWrapper = new QueryWrapper<>();
        questionInfoQueryWrapper.eq("is_deleted", IsDeleteEnum.N.getKey());
        List<QuestionInfo> questionInfoList = questionFacade.list(questionInfoQueryWrapper);
        Map<Long, QuestionInfo> questionInfoMap = questionInfoList.stream().collect(Collectors.toMap(QuestionInfo::getId,questionInfo -> questionInfo));
        //获取模板信息
        QueryWrapper<ModuleInfo> moduleInfoQueryWrapper = new QueryWrapper<>();
        questionInfoQueryWrapper.eq("is_deleted", IsDeleteEnum.N.getKey());
        List<ModuleInfo> moduleInfoList = this.list(moduleInfoQueryWrapper);
        Map<Long, ModuleInfo> moduleInfoMap = moduleInfoList.stream().collect(Collectors.toMap(ModuleInfo::getId,moduleInfo -> moduleInfo));
        //循环给出参赋值
        for (ModuleDetail moduleDetail : moduleDetailList) {
            getModuleDetailInfoDTO = new GetModuleDetailInfoDTO();
            BeanUtil.copyProperties(moduleDetail, getModuleDetailInfoDTO);
            if (moduleDetail.getQuestionId() != null) {
                getModuleDetailInfoDTO.setTagName(questionInfoMap.get(moduleDetail.getQuestionId()).getTagName());
                getModuleDetailInfoDTO.setTagType(questionInfoMap.get(moduleDetail.getQuestionId()).getTagType());
            } else {
                getModuleDetailInfoDTO.setRelationModuleName(moduleInfoMap.get(moduleDetail.getRelationModule()).getName());
            }
            getModuleDetailInfoDTOList.add(getModuleDetailInfoDTO);
        }

        return getModuleDetailInfoDTOList;
    }

    /**
     * 模板维护页面获取模板列表
     *
     * @param getModuleInfoOneVO
     * @return
     */
    public GetModuleInfoOneDTO getModuleInfoOne(GetModuleInfoOneVO getModuleInfoOneVO) {
        GetModuleInfoOneDTO getModuleInfoOneDTO = new GetModuleInfoOneDTO();
        //获取模板信息
        QueryWrapper<ModuleInfo> moduleInfoQueryWrapper = new QueryWrapper<>();
        moduleInfoQueryWrapper.eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq("id", getModuleInfoOneVO.getModuleId());
        ModuleInfo moduleInfo = this.getOne(moduleInfoQueryWrapper);
        //获取模板类型名称
        QueryWrapper<DictionaryInfo> dictionaryInfoQueryWrapper = new QueryWrapper<>();
        dictionaryInfoQueryWrapper.eq("is_deleted", IsDeleteEnum.N.getKey());
        List<DictionaryInfo> dictionaryInfoList = dictionaryFacade.list(dictionaryInfoQueryWrapper);
        Map<String, DictionaryInfo> dictionaryInfoMap = new HashMap<>();
        for (DictionaryInfo dictionaryInfo : dictionaryInfoList) {
            dictionaryInfoMap.put(dictionaryInfo.getVal(), dictionaryInfo);
        }
        BeanUtil.copyProperties(moduleInfo, getModuleInfoOneDTO);
        getModuleInfoOneDTO.setAscriptionName(dictionaryInfoMap.get(String.valueOf(moduleInfo.getType())).getName());
        return getModuleInfoOneDTO;
    }


}
