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.GetDeptInfoDTO;
import com.diagbot.dto.RespDTO;
import com.diagbot.entity.DeptInfo;
import com.diagbot.entity.QuestionUsual;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.enums.QuestionTypeEnum;
import com.diagbot.exception.CommonErrorCode;
import com.diagbot.exception.CommonException;
import com.diagbot.service.QuestionUsualService;
import com.diagbot.service.impl.QuestionUsualServiceImpl;
import com.diagbot.util.DateUtil;
import com.diagbot.util.ListUtil;
import com.diagbot.util.UserUtils;
import com.diagbot.vo.DeleteQuestionUsualVO;
import com.diagbot.vo.GetDeptInfoVO;
import com.diagbot.vo.GetQuestionIdsByTypeVO;
import com.diagbot.vo.QuestionUsualVO;
import com.google.common.collect.Lists;
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.List;
import java.util.Map;

/**
 * @Description:
 * @author: wangyu
 * @time: 2018/12/3 17:06
 */
@Component
public class QuestionUsualFacade extends QuestionUsualServiceImpl {
    @Autowired
    private DeptInfoFacade deptInfoFacade;
    @Autowired
    private UserServiceClient userServiceClient;
    @Autowired
    @Qualifier("questionUsualServiceImpl")
    private QuestionUsualService questionUsualService;
    @Autowired
    private QuestionFacade questionFacade;

    /**
     * 添加常用标签
     *
     * @param questionUsualVO
     * @return
     */
    public Boolean addQuestionUsual(QuestionUsualVO questionUsualVO) {
        //判断科室是否已被删除
        if(deptIsDeletedStatus(questionUsualVO.getDeptId())){
            throw new CommonException(CommonErrorCode.NOT_EXISTS,
                    "科室已删除");
        }
        List<QuestionUsual> addList = Lists.newArrayList();
        //判断该科室是否添加过常用标签
        QuestionUsual questionUsual = new QuestionUsual();
        String userId = UserUtils.getCurrentPrincipleID();
        List<QuestionUsual> questionUsualList = this.getQuestionUsualByQuestionId(questionUsualVO);
        //如果添加过将原来的标签删除
        if (ListUtil.isNotEmpty(questionUsualList)) {
            UpdateWrapper<QuestionUsual> updateWrapper = new UpdateWrapper();
            updateWrapper.eq("dept_id", questionUsualVO.getDeptId())
                    .set("is_deleted", IsDeleteEnum.Y.getKey())
                    .set("modifier", userId)
                    .set("gmt_modified", DateUtil.now());
            this.update(new QuestionUsual(), updateWrapper);
        }
        //重新添加标签
        for (int i = 0; i < questionUsualVO.getQuestionId().size(); i++) {
            questionUsual = new QuestionUsual();
            questionUsual.setCreator(userId);
            questionUsual.setModifier(userId);
            questionUsual.setGmtCreate(DateUtil.now());
            questionUsual.setGmtModified(DateUtil.now());
            questionUsual.setQuestionId(questionUsualVO.getQuestionId().get(i));
            questionUsual.setDeptId(questionUsualVO.getDeptId());
            questionUsual.setOrderNo(Long.parseLong(String.valueOf(i + 1)));
            addList.add(questionUsual);
        }
        Boolean flag = questionUsualService.saveBatch(addList);
        if (!flag) {
            throw new CommonException(CommonErrorCode.INSERT_DATA_FAILED,
                    "常用症状添加失败");
        }
        return true;
    }

    /**
     * 删除常用标签
     *
     * @param deleteQuestionUsualVO
     * @return
     */
    public Boolean deleteQuestionUsualByDeptId(DeleteQuestionUsualVO deleteQuestionUsualVO) {
        //判断科室是否已被删除
        if(deptIsDeletedStatus(deleteQuestionUsualVO.getDeptId())){
            throw new CommonException(CommonErrorCode.NOT_EXISTS,
                    "科室已删除");
        }
        //查询常用标签是否已被删除
        QueryWrapper<QuestionUsual> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dept_id",deleteQuestionUsualVO.getDeptId());
        List<QuestionUsual> questionUsualList = this.list(queryWrapper);
        List<Long> questionIds = new ArrayList<>();
        Boolean flag = false;
        questionUsualList.stream().forEach(questionUsual -> questionIds.add(questionUsual.getQuestionId()));
        for (QuestionUsual questionUsual:questionUsualList) {
            if(questionUsual.getIsDeleted().equals(IsDeleteEnum.N.getKey())){
                flag = true;
                break;
            }
        }
        if(!flag){
            throw new CommonException(CommonErrorCode.FAIL,
                    "标签已删除");
        }
        //查询出相关类型的标签id
        GetQuestionIdsByTypeVO getQuestionIdsByTypeVO = new GetQuestionIdsByTypeVO();
        getQuestionIdsByTypeVO.setQuestionIds(questionIds);
        getQuestionIdsByTypeVO.setQuestionType(deleteQuestionUsualVO.getType());
        List<Long> questionInfoList = questionFacade.getQuestionIdsByType(getQuestionIdsByTypeVO);
        //如果存在相关类型的数据，就删除
        if(ListUtil.isNotEmpty(questionInfoList)){
            //删除常用标签
            String userId = UserUtils.getCurrentPrincipleID();
            UpdateWrapper<QuestionUsual> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("dept_id", deleteQuestionUsualVO.getDeptId())
                    .in("question_id",questionInfoList)
                    .set("is_deleted", IsDeleteEnum.Y.getKey())
                    .set("modifier", userId)
                    .set("gmt_modified", DateUtil.now());
            this.update(new QuestionUsual(), updateWrapper);
        }
        return true;
    }

    /**
     * 获取科室信息
     *
     * @param getDeptInfoVO
     * @return
     */
    public IPage<GetDeptInfoDTO> getDeptInfos(GetDeptInfoVO getDeptInfoVO) {
        //分页查询科室
        IPage<GetDeptInfoDTO> iPage = deptInfoFacade.getAllDeptInfo(getDeptInfoVO);
        //获取用户信息
        List<String> ids = new ArrayList<>();
        for (GetDeptInfoDTO getDeptInfoDTO : iPage.getRecords()) {
            ids.add(getDeptInfoDTO.getModifier());
        }
        RespDTO<Map<String, String>> respDTO = userServiceClient.getUserInfoByIds(ids);
        if (respDTO == null || !CommonErrorCode.OK.getCode().equals(respDTO.code)) {
            throw new CommonException(CommonErrorCode.RPC_ERROR,
                    "获取用户信息失败");
        }
        //将用户信息放入实体
        for (GetDeptInfoDTO getDeptInfoDTO : iPage.getRecords()) {
            getDeptInfoDTO.setUserName(respDTO.data.get(getDeptInfoDTO.getModifier()));
            getDeptInfoDTO.setTypeName(QuestionTypeEnum.getName(getDeptInfoDTO.getType()));
        }
        return iPage;
    }

    /**
     * 判断科室是否已删除
     * @param deptId
     * @return
     */
    public Boolean deptIsDeletedStatus(Long deptId){
        QueryWrapper<DeptInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_deleted",IsDeleteEnum.Y.getKey());
        queryWrapper.eq("id",deptId);
        return deptInfoFacade.count(queryWrapper) > 0 ? true : false;
    }
}
