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.GetQuestionInfoDTO;
import com.diagbot.dto.QuestionPageDTO;
import com.diagbot.dto.RespDTO;
import com.diagbot.entity.CommonParam;
import com.diagbot.entity.DeptInfo;
import com.diagbot.entity.ModuleDetail;
import com.diagbot.entity.ModuleInfo;
import com.diagbot.entity.QuestionDetail;
import com.diagbot.entity.QuestionInfo;
import com.diagbot.entity.QuestionMapping;
import com.diagbot.entity.wrapper.QuestionMappingWrapper;
import com.diagbot.entity.wrapper.QuestionWrapper;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.enums.TagTypeEnum;
import com.diagbot.exception.CommonErrorCode;
import com.diagbot.exception.CommonException;
import com.diagbot.service.QuestionDetailService;
import com.diagbot.service.QuestionInfoService;
import com.diagbot.service.QuestionMappingService;
import com.diagbot.service.impl.QuestionInfoServiceImpl;
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.GetQuestionInfoVO;
import com.diagbot.vo.GetQuestionUsualByDeptVO;
import com.diagbot.vo.QuestionIndexVO;
import com.diagbot.vo.QuestionPageVO;
import com.diagbot.vo.QuestionSaveVO;
import com.diagbot.vo.QuestionSpecVO;
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.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author:zhaops
 * @time: 2018/11/23 11:37
 */
@Component
public class QuestionInfoFacade extends QuestionInfoServiceImpl {

    @Autowired
    QuestionDetailFacade questionDetailFacade;
    @Autowired
    @Qualifier("questionInfoServiceImpl")
    QuestionInfoService questionInfoService;
    @Autowired
    @Qualifier("questionDetailServiceImpl")
    QuestionDetailService questionDetailService;
    @Autowired
    @Qualifier("questionMappingServiceImpl")
    QuestionMappingService questionMappingService;
    @Autowired
    QuestionMappingFacade questionMappingFacade;
    @Autowired
    ModuleDetailFacade moduleDetailFacade;
    @Autowired
    DeptInfoFacade deptInfoFacade;
    @Autowired
    UserServiceClient userServiceClient;
    @Autowired
    ModuleInfoFacade moduleInfoFacade;


    /**
     * 标签保存
     *
     * @param questionSaveVO
     */
    public void saveOrUpdate(QuestionSaveVO questionSaveVO) {
        QuestionWrapper questionWrapper = questionSaveVO.getQuestionWrapper();
        CommonParam param = initCommonParam();
        saveQuestionInfo(questionWrapper, param);
        switch (questionWrapper.getTagType()) {
            case "1":   //单项，例如：程度、体温
                saveQuestionDetail(questionWrapper, param);
                break;
            case "2":   //组合项，例如：杂音，修改主表和mapping
            case "3":   //组合项，例如：血压
            case "4":   //组合项，例如：咳嗽
                saveQuestionMapping(questionWrapper, param);
                break;
            case "5":   //组合项，例如：有无治疗
                break;
            case "6":  // 组合项，例如：既往史
                break;
            case "7":  //化验
                break;
            case "8":  //模板专用文字,无单独维护
                break;
            default:
                throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "请选择标签显示类型");
        }
    }


    /**
     * 初始化参数
     *
     * @return
     */
    public CommonParam initCommonParam() {
        CommonParam param = new CommonParam();
        //String person = UserUtils.getCurrentPrincipleID(); //TODO person
        String person = "1";
        param.setNow(DateUtil.now());
        param.setPerson(person);
        param.setSaveOrUpdate("save");
        return param;
    }


    /**
     * 保存映射关系
     *
     * @param questionWrapper
     * @param param
     */
    public void saveQuestionMapping(QuestionWrapper questionWrapper, CommonParam param) {
        QuestionInfo questionInfo = param.getQuestionInfo();
        Date now = param.getNow();
        String person = param.getPerson();
        //先删除原明细，再插入新明细
        questionMappingFacade.update(new QuestionMapping(), //删除原映射关系
                new UpdateWrapper<QuestionMapping>()
                        .eq("parent_question", questionInfo.getId())
                        .eq("is_deleted", IsDeleteEnum.N.getKey())
                        .set("gmt_modified", now)
                        .set("modifier", person)
                        .set("is_deleted", IsDeleteEnum.Y.getKey()));
        List<QuestionMappingWrapper> questionMappings = questionWrapper.getQuestionMappings();
        if (ListUtil.isNotEmpty(questionMappings)) {
            //预处理文字标签，之后统一添加映射关系
            Map<String, Long> map = getNameMap(questionMappings, now, person, questionInfo.getType());
            List<QuestionMapping> saveMapping = new ArrayList<>();
            int i = 1;
            for (QuestionMappingWrapper mapping : questionMappings) {
                String text = mapping.getText();
                if (StringUtil.isNotEmpty(text)) {
                    mapping.setSonQuestion(map.get(text));
                }
                QuestionMapping bean = new QuestionMapping();
                BeanUtil.copyProperties(mapping, bean);
                bean.setId(null); //防止前端传参，将前端的id置空自动插入
                bean.setCreator(person);
                bean.setGmtCreate(now);
                bean.setModifier(person);
                bean.setGmtModified(now);
                bean.setParentQuestion(questionInfo.getId());
                bean.setOrderNo(i++);
                saveMapping.add(bean);
            }
            questionMappingService.saveBatch(saveMapping);
        }
    }


    /**
     * 获取name对应map列表，key为name，value为id
     *
     * @param questionMappings
     * @param now
     * @param person
     * @param type
     * @return
     */
    public Map<String, Long> getNameMap(List<QuestionMappingWrapper> questionMappings, Date now, String person, Integer type) {
        List<String> nameList = questionMappings.stream().filter(row -> StringUtil.isNotEmpty(row.getText())).map(row -> row.getText()).collect(Collectors.toList());
        List<QuestionInfo> questionInfos = this.list(new QueryWrapper<QuestionInfo>()
                .eq("type", type)
                .eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq("tag_type", TagTypeEnum.T8.getKey())
                .in("name", nameList)
        );
        Map<String, Long> map = questionInfos.stream().collect(Collectors.toMap(row -> row.getName(), row -> row.getId(), (k1, k2) -> k1));
        List<QuestionInfo> addBatch = new ArrayList<>();
        List<String> nameExist = new ArrayList<>();
        for (String s : nameList) {
            if (map.get(s) == null && !nameExist.contains(s)) {
                nameExist.add(s);
                QuestionInfo bean = new QuestionInfo();
                bean.setModifier(person);
                bean.setCreator(person);
                bean.setGmtCreate(now);
                bean.setGmtModified(now);
                bean.setTagType(String.valueOf(TagTypeEnum.T8.getKey()));
                bean.setTagName(s);
                bean.setName(s);
                bean.setType(type);
                bean.setSubType(1); //描述类型
                addBatch.add(bean);
            }
        }
        questionInfoService.saveBatch(addBatch); //批量插入question
        for (QuestionInfo bean : addBatch) {
            if (map.get(bean.getName()) == null) {
                map.put(bean.getName(), bean.getId());
            }
        }
        return map;
    }


    /**
     * 保存明细
     *
     * @param questionWrapper
     * @param param
     */
    public void saveQuestionDetail(QuestionWrapper questionWrapper, CommonParam param) {
        QuestionInfo questionInfo = param.getQuestionInfo();
        Date now = param.getNow();
        String person = param.getPerson();
        //先删除原明细，再插入新明细
        questionDetailFacade.update(new QuestionDetail(), //删除原明细
                new UpdateWrapper<QuestionDetail>()
                        .eq("question_id", questionInfo.getId())
                        .eq("is_deleted", IsDeleteEnum.N.getKey())
                        .set("gmt_modified", now)
                        .set("modifier", person)
                        .set("is_deleted", IsDeleteEnum.Y.getKey()));
        List<QuestionDetail> questionDetails = questionWrapper.getQuestionDetails();
        if (ListUtil.isNotEmpty(questionDetails)) {
            List<QuestionDetail> saveDetail = new ArrayList<>();
            int i = 1;
            for (QuestionDetail detail : questionDetails) {
                QuestionDetail bean = new QuestionDetail();
                BeanUtil.copyProperties(detail, bean);
                bean.setId(null); //防止前端传参，将前端的id置空自动插入
                bean.setCreator(person);
                bean.setGmtCreate(now);
                bean.setModifier(person);
                bean.setGmtModified(now);
                bean.setQuestionId(questionInfo.getId());
                bean.setOrderNo(i++);
                saveDetail.add(bean);
            }
            questionDetailService.saveBatch(saveDetail);
        }
    }


    /**
     * 保存主表
     *
     * @param questionWrapper
     * @param param
     */
    public void saveQuestionInfo(QuestionWrapper questionWrapper, CommonParam param) {
        QuestionInfo questionInfo = new QuestionInfo();
        if (questionWrapper.getId() != null) {
            questionInfo = this.getOne(new QueryWrapper<QuestionInfo>()
                    .eq("id", questionWrapper.getId())
                    .eq("is_deleted", IsDeleteEnum.N.getKey()));
            if (questionInfo == null) { //校验
                throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "标签不存在");
            }
            param.setSaveOrUpdate("update");
        }
        BeanUtil.copyProperties(questionWrapper, questionInfo);
        List<QuestionInfo> questionInfoList = this.list(new QueryWrapper<QuestionInfo>()
                .eq("tag_name", questionInfo.getTagName())
                .eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq("type", questionInfo.getType())
                .ne("id", questionInfo.getId() == null ? -1 : questionInfo.getId()));
        if (questionInfoList.size() > 0) { //标签type、tagName唯一
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "标签名已存在");
        }
        if ("save".equals(param.getSaveOrUpdate())) {
            questionInfo.setCreator(param.getPerson()); //创建人
            questionInfo.setGmtCreate(param.getNow());//创建时间
        }
        questionInfo.setGmtModified(param.getNow());//修改时间
        questionInfo.setModifier(param.getPerson());//修改人
        param.setQuestionInfo(questionInfo);
        this.saveOrUpdate(questionInfo);
    }


    /**
     * 标签列表
     *
     * @param questionPageVO
     * @return
     */
    public IPage<QuestionPageDTO> getListFac(QuestionPageVO questionPageVO) {
        IPage<QuestionPageDTO> res = this.getList(questionPageVO);
        if (res.getTotal() <= 0) {
            return res;
        }
        List<String> personIds = res.getRecords().stream().map(row -> row.getModifier()).collect(Collectors.toList());
        RespDTO<Map<String, String>> mapRespDTO = userServiceClient.getUserInfoByIds(personIds);
        if (mapRespDTO == null || !"0".equals(mapRespDTO.code)) {
            throw new CommonException(CommonErrorCode.RPC_ERROR, "获取操作人失败");
        }
        for (QuestionPageDTO bean : res.getRecords()) {
            bean.setModifier(mapRespDTO.data.get(bean.getModifier()));
        }
        return res;
    }


    /**
     * 根据id删除标签
     *
     * @param ids
     * @return
     */
    public Boolean deleteByIdsFac(String ids) {
        if (StringUtil.isEmpty(ids)) {
            return true;
        }
        List<String> idList = Arrays.asList(ids.split(","));
        for (String id : idList) {
            // 查询映射关系中是否存在父级
            List<QuestionMapping> questionMappings = questionMappingFacade.list(new QueryWrapper<QuestionMapping>()
                    .eq("is_deleted", IsDeleteEnum.N.getKey())
                    .eq("son_question", id));
            if (ListUtil.isNotEmpty(questionMappings)) {
                List<Long> questionIds = questionMappings.stream().map(row -> row.getParentQuestion()).collect(Collectors.toList());
                List<String> tagName = this.list(new QueryWrapper<QuestionInfo>()
                        .eq("is_deleted", IsDeleteEnum.N.getKey())
                        .in("id", questionIds))
                        .stream().map(row -> "【" + row.getTagName() + "】").collect(Collectors.toList());
                throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "请先删除标签的关联：" + String.join("、", tagName));
            }
            // 查询模板中是否存在
            List<ModuleDetail> moduleDetails = moduleDetailFacade.list(new QueryWrapper<ModuleDetail>()
                    .eq("is_deleted", IsDeleteEnum.N.getKey())
                    .eq("question_id", id));
            if (ListUtil.isNotEmpty(moduleDetails)) {
                List<Long> moduleIds = moduleDetails.stream().map(row -> row.getModuleId()).collect(Collectors.toList());
                List<String> moduleName = moduleInfoFacade.list(new QueryWrapper<ModuleInfo>()
                        .eq("is_deleted", IsDeleteEnum.N.getKey())
                        .in("id", moduleIds))
                        .stream().map(row -> "{" + row.getName() + "}").collect(Collectors.toList());
                throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "请先删除模板的关联：" + String.join("、", moduleName));
            }

            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);
            //删除明细
            questionDetailFacade.deleteByQuestionIdFac(paramMap);
            //删除映射关系
            questionMappingFacade.deleteByIdsFac(paramMap);
        }
        return true;
    }


    /**
     * 检索
     *
     * @param questionIndexVO
     * @return
     */
    public List<QuestionInfo> indexFac(QuestionIndexVO questionIndexVO) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("isDeleted", IsDeleteEnum.N.getKey());
        paramMap.put("age", questionIndexVO.getAge());
        paramMap.put("sexType", questionIndexVO.getSexType());
        paramMap.put("tagName", questionIndexVO.getTagName());
        paramMap.put("type", questionIndexVO.getType());
        paramMap.put("controlType", questionIndexVO.getControlType());
        paramMap.put("notIds", questionIndexVO.getNotIds());
        return this.index(paramMap);
    }


    /**
     * 获取特殊标签（同伴|无）
     *
     * @param questionSpecVO
     * @return
     */
    public List<QuestionInfo> getSpecialFac(QuestionSpecVO questionSpecVO) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("age", questionSpecVO.getAge());
        paramMap.put("sexType", questionSpecVO.getSexType());
        paramMap.put("type", questionSpecVO.getType());
        paramMap.put("notIds", questionSpecVO.getNotIds());
        return this.getSpecial(paramMap);
    }


    /**
     * 根据标签名获取标签信息
     *
     * @param questionInfo
     * @return
     */
    public QuestionInfo getQuestionInfos(QuestionInfo questionInfo) {
        QueryWrapper<QuestionInfo> queryWrapper = new QueryWrapper<QuestionInfo>();
        queryWrapper.eq("is_deleted", "N");
        queryWrapper.eq("type", 1);
        queryWrapper.eq("name", questionInfo.getName());
        return this.getOne(queryWrapper);
    }


    /**
     * 根据标签名获取标签信息
     *
     * @param getQuestionInfoVO
     * @return
     */
    public List<GetQuestionInfoDTO> getQuestiongInfosByName(GetQuestionInfoVO getQuestionInfoVO) {
        List<GetQuestionInfoDTO> getQuestionInfoDTOS = this.getQuestiongInfoByName(getQuestionInfoVO);
        return getQuestionInfoDTOS;
    }


    /**
     * 根据科室id获取常用标签信息
     *
     * @param getQuestionUsualByDeptVO
     * @return
     */
    public List<GetQuestionInfoDTO> getQuestionUsualByDept(GetQuestionUsualByDeptVO getQuestionUsualByDeptVO) {
        //先判断科室是不是已被删除
        QueryWrapper<DeptInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq("id", getQuestionUsualByDeptVO.getDeptId());
        List<DeptInfo> deptInfoList = deptInfoFacade.list(queryWrapper);
        if (ListUtil.isEmpty(deptInfoList)) {
            throw new CommonException(CommonErrorCode.NOT_EXISTS, "科室信息不存在");
        }
        //获取常用标签信息
        List<GetQuestionInfoDTO> getQuestionInfoDTOList = this.getQuestionUsualsByDept(getQuestionUsualByDeptVO);
        return getQuestionInfoDTOList;
    }
}