package com.diagbot.facade;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diagbot.dto.GetModuleInfoOneDTO;
import com.diagbot.dto.QcModuleDetailDTO;
import com.diagbot.dto.QuestionDTO;
import com.diagbot.entity.QcModuleDetail;
import com.diagbot.entity.QcModuleInfo;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.exception.CommonErrorCode;
import com.diagbot.exception.CommonException;
import com.diagbot.service.impl.QcModuleInfoServiceImpl;
import com.diagbot.util.BeanUtil;
import com.diagbot.util.EntityUtil;
import com.diagbot.util.ListUtil;
import com.diagbot.util.StringUtil;
import com.diagbot.vo.GetModuleInfoOneVO;
import com.diagbot.vo.GetModuleMapVO;
import com.diagbot.vo.QuestionIdsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.LinkedHashMap;
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 QcModuleInfoFacade extends QcModuleInfoServiceImpl {

    @Autowired
    QcModuleDetailFacade qcModuleDetailFacade;
    @Autowired
    QcQuestionFacade qcQuestionFacade;
    @Autowired
    SysHospitalSetFacade sysHospitalSetFacade;

    /**
     * 根据id获取模板信息
     *
     * @param getModuleInfoOneVO
     * @return
     */
    public GetModuleInfoOneDTO getByIdFac(GetModuleInfoOneVO getModuleInfoOneVO) {
        //获取模板信息
        GetModuleInfoOneDTO getModuleInfoOneDTO = this.getById(getModuleInfoOneVO);

        if (null == getModuleInfoOneDTO) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR,
                    "模板已删除【" + getModuleInfoOneVO.getModuleId() + "】");
        }
        List<QcModuleDetail> qcModuleDetailList = qcModuleDetailFacade.list(new QueryWrapper<QcModuleDetail>()
                .eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq("module_id", getModuleInfoOneDTO.getId())
                .orderByAsc("order_no")
        );
        List<QcModuleDetailDTO> qcModuleDetailDTOList = BeanUtil.listCopyTo(qcModuleDetailList, QcModuleDetailDTO.class);

        // 根据questionId获取所有的标签
        List<Long> questionIds = qcModuleDetailList.stream().map(r -> r.getQuestionId()).collect(Collectors.toList());
        QuestionIdsVO questionIdsVO = new QuestionIdsVO();
        questionIdsVO.setIds(questionIds);
        Map<Long, QuestionDTO> questionDTOMap = qcQuestionFacade.getByIds(questionIdsVO);
        for (QcModuleDetailDTO bean : qcModuleDetailDTOList) {
            QuestionDTO questionDTO = questionDTOMap.get(bean.getQuestionId());
            if (questionDTO != null) {
                bean.setQuestionDTO(questionDTO);
            }
        }
        Map<Integer, List<QcModuleDetailDTO>> map = EntityUtil.makeEntityListMap(qcModuleDetailDTOList, "groupId");
        getModuleInfoOneDTO.setModuleDetail(map);
        return getModuleInfoOneDTO;
    }

    /**
     * 根据模块获取模板信息
     *
     * @param getModuleMapVO
     * @return
     */
    @Cacheable(value = "cache", key = "'qcmodule:hospId_'+#getModuleMapVO.hospitalId")
    public Map<Long, GetModuleInfoOneDTO> getModuleMap(GetModuleMapVO getModuleMapVO) {
        Map<Long, GetModuleInfoOneDTO> res = new LinkedHashMap<>();
        List<QcModuleInfo> qcModuleInfoList = this.list(new QueryWrapper<QcModuleInfo>()
                .eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq(getModuleMapVO.getModeId() != null, "mode_id", getModuleMapVO.getModeId())
                .eq("hospital_id", getModuleMapVO.getHospitalId())
        );
        List<Long> ids = qcModuleInfoList.stream().map(r -> r.getId()).collect(Collectors.toList());
        if (ListUtil.isEmpty(ids)) {
            return new HashMap<>();
        }
        GetModuleInfoOneVO getModuleInfoOneVO = new GetModuleInfoOneVO();
        String pageShowFlag = sysHospitalSetFacade.getValue(getModuleMapVO.getHospitalId(), "page_show_flag");
        String pageShowConfig = sysHospitalSetFacade.getValue(getModuleMapVO.getHospitalId(), "page_show_config");
        for (Long id : ids) {
            getModuleInfoOneVO.setModuleId(id);
            GetModuleInfoOneDTO oneDTO = getByIdFac(getModuleInfoOneVO);
            //原文书（超链接）配置
            originalDocumentConfigure(oneDTO, pageShowFlag, pageShowConfig, getModuleMapVO.getHospitalId());
            res.put(id, oneDTO);
        }
        return res;
    }

    private void originalDocumentConfigure(GetModuleInfoOneDTO oneDTO, String pageShowFlag, String pageShowConfig, Long hospitalId) {
        if (StringUtil.isNotEmpty(pageShowFlag) && StringUtil.isNotEmpty(pageShowConfig)) {
            JSONObject pageShowFlagJSON = JSONObject.parseObject(pageShowFlag);
            JSONObject pageShowConfigJSON = JSONObject.parseObject(pageShowConfig);
            try {
                if (pageShowFlagJSON.containsKey(oneDTO.getModeId().toString())) {
                    if (pageShowFlagJSON.getBoolean(oneDTO.getModeId().toString())) {
                        QcModuleDetailDTO qcModuleDetailDTO = createQcModuleDetailDTO(pageShowConfigJSON, hospitalId, oneDTO.getModeId());
                        oneDTO.getModuleDetail().get(0).add(0,qcModuleDetailDTO);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private QcModuleDetailDTO createQcModuleDetailDTO(JSONObject pageShowConfigJSON, Long hospitalId, Long modeId) {
        QcModuleDetailDTO qcModuleDetailDTO = new QcModuleDetailDTO();
        QuestionDTO questionDTO = new QuestionDTO();
        qcModuleDetailDTO.setQuestionId(modeId*-1);
        qcModuleDetailDTO.setGroupId(pageShowConfigJSON.getInteger("groupId"));

        questionDTO.setId(modeId*-1);
        questionDTO.setName("");
        questionDTO.setVal(pageShowConfigJSON.getString("val"));
        questionDTO.setTagName("");
        questionDTO.setControlType(pageShowConfigJSON.getInteger("controlType"));
        questionDTO.setTagType(pageShowConfigJSON.getInteger("tagType"));
        questionDTO.setHospitalId(hospitalId);
        questionDTO.setModeId(modeId);
        questionDTO.setRetract(pageShowConfigJSON.getInteger("retract"));
        questionDTO.setAddLine(pageShowConfigJSON.getInteger("addLine"));
        questionDTO.setMonoLine(pageShowConfigJSON.getInteger("monoLine"));
        questionDTO.setBold(pageShowConfigJSON.getInteger("bold"));
        questionDTO.setPosition(pageShowConfigJSON.getInteger("position"));
        qcModuleDetailDTO.setQuestionDTO(questionDTO);
        return qcModuleDetailDTO;
    }
}
