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.DeptShortDTO;
import com.diagbot.dto.DeptVitalDTO;
import com.diagbot.dto.QuestionShortDTO;
import com.diagbot.dto.RespDTO;
import com.diagbot.entity.DeptInfo;
import com.diagbot.entity.DeptVital;
import com.diagbot.entity.QuestionInfo;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.enums.QuestionTypeEnum;
import com.diagbot.exception.CommonErrorCode;
import com.diagbot.exception.CommonException;
import com.diagbot.service.DeptVitalService;
import com.diagbot.service.impl.DeptVitalServiceImpl;
import com.diagbot.util.BeanUtil;
import com.diagbot.util.DateUtil;
import com.diagbot.util.EntityUtil;
import com.diagbot.util.UserUtils;
import com.diagbot.vo.DVDetailVO;
import com.diagbot.vo.DeptVitalPageVO;
import com.diagbot.vo.DeptVitalVO;
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.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author:zhaops
 * @time: 2018/11/22 11:45
 */
@Component
public class DeptVitalFacade extends DeptVitalServiceImpl {

    @Autowired
    private QuestionFacade questionFacade;
    @Autowired
    private DeptInfoFacade deptInfoFacade;
    @Autowired
    @Qualifier("deptVitalServiceImpl")
    private DeptVitalService deptVitalService;
    @Autowired
    private UserServiceClient userServiceClient;

    /**
     * 保存查体模板
     *
     * @param deptVitalVO
     * @return
     */
    public Boolean saveDeptVitals(DeptVitalVO deptVitalVO) {
        //先删除该科室原有模板
        UpdateWrapper<DeptVital> deptVitalUpdateWrapper = new UpdateWrapper<>();
        deptVitalUpdateWrapper.eq("dept_id", deptVitalVO.getDeptId()).
                eq("is_deleted", IsDeleteEnum.N.getKey()).
                set("is_deleted", IsDeleteEnum.Y.getKey()).
                set("modifier", UserUtils.getCurrentPrincipleID()).
                set("gmt_modified", DateUtil.now());
        this.update(new DeptVital(), deptVitalUpdateWrapper);

        //查找标签是否存在
        QueryWrapper<QuestionInfo> questionInfoQueryWrapper = new QueryWrapper<>();
        List<Long> vitalIds = deptVitalVO.getDvDetailVOList().stream().map(deDetailVO -> deDetailVO.getVitalId()).collect(Collectors.toList());
        questionInfoQueryWrapper.in("id", vitalIds).
                eq("type", QuestionTypeEnum.Vital.getKey()).
                eq("is_deleted", IsDeleteEnum.N.getKey());
        List<QuestionInfo> questionInfoList = questionFacade.list(questionInfoQueryWrapper);

        Map<Long, QuestionInfo> questionInfoMap = EntityUtil.makeEntityMap(questionInfoList, "id");
        for (Long vital : vitalIds) {
            if (questionInfoMap.get(vital) == null) {
                throw new CommonException(CommonErrorCode.NOT_EXISTS, "id=" + vital + "的查体标签不存在");
            }
        }

        //插入新模板
        List<DeptVital> deptVitalList = Lists.newArrayList();
        Date now = DateUtil.now();
        String userId = UserUtils.getCurrentPrincipleID();
        for (DVDetailVO dvDetailVO : deptVitalVO.getDvDetailVOList()) {
            DeptVital deptVital = new DeptVital();
            deptVital.setDeptId(deptVitalVO.getDeptId());
            deptVital.setVitalId(dvDetailVO.getVitalId());
            deptVital.setOrderNo(dvDetailVO.getOrderNo());
            deptVital.setCreator(userId);
            deptVital.setGmtCreate(now);
            deptVital.setModifier(userId);
            deptVital.setGmtModified(now);
            deptVitalList.add(deptVital);
        }

        deptVitalService.saveBatch(deptVitalList);
        return true;
    }

    /**
     * 删除科室查体模板标签
     *
     * @param deptVitalVO
     * @return
     */
    public Boolean delDeptVitalList(DeptVitalVO deptVitalVO) {
        UpdateWrapper<DeptVital> deptVitalUpdateWrapper = new UpdateWrapper<>();
        List<Long> vitalIds = deptVitalVO.getDvDetailVOList().stream().map(deDetailVO -> deDetailVO.getVitalId()).collect(Collectors.toList());
        deptVitalUpdateWrapper.eq("dept_id", deptVitalVO.getDeptId()).
                in("vital_id", vitalIds).
                eq("is_deleted", IsDeleteEnum.N.getKey()).
                set("is_deleted", IsDeleteEnum.Y.getKey()).
                set("modifier", UserUtils.getCurrentPrincipleID()).
                set("gmt_modified", DateUtil.now());
        this.update(new DeptVital(), deptVitalUpdateWrapper);
        return true;
    }

    /**
     * 删除科室查体模板标签-全删除
     *
     * @param deptId
     * @return
     */
    public Boolean delAllDeptVitalList(Long deptId) {
        UpdateWrapper<DeptVital> deptVitalUpdateWrapper = new UpdateWrapper<>();
        deptVitalUpdateWrapper.eq("dept_id", deptId).
                eq("is_deleted", IsDeleteEnum.N.getKey()).
                set("is_deleted", IsDeleteEnum.Y.getKey()).
                set("modifier", UserUtils.getCurrentPrincipleID()).
                set("gmt_modified", DateUtil.now());
        this.update(new DeptVital(), deptVitalUpdateWrapper);
        return true;
    }

    /**
     * 根据部门获取查体模板
     *
     * @param deptId
     * @return
     */
    public DeptVitalDTO getModuleByDeptId(Long deptId) {
        DeptVitalDTO deptVitalDTO = new DeptVitalDTO();
        DeptInfo deptInfo = deptInfoFacade.getById(deptId);
        if (deptInfo == null) {
            throw new CommonException(CommonErrorCode.NOT_EXISTS, "科室不存在");
        } else if (deptInfo.getIsDeleted().equals(IsDeleteEnum.Y.getKey())) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "科室已删除");
        }
        BeanUtil.copyProperties(deptInfo, deptVitalDTO);

        //已关联查体
        QueryWrapper<DeptVital> deptVitalQueryWrapper = new QueryWrapper<>();
        deptVitalQueryWrapper.eq("dept_id", deptId).
                eq("is_deleted", IsDeleteEnum.N.getKey()).
                orderByAsc("order_no");
        List<DeptVital> deptVitalList = this.list(deptVitalQueryWrapper);
        List<Long> vitalIds = deptVitalList.stream()
                .map(deptVitals -> deptVitals.getVitalId())
                .collect(Collectors.toList());
        if (vitalIds.size() > 0) {
            List<QuestionInfo> vitalList = Lists.newArrayList(questionFacade.listByIds(vitalIds));
            List<QuestionShortDTO> vitals = BeanUtil.listCopyTo(vitalList, QuestionShortDTO.class);
            deptVitalDTO.setVitals(vitals);
        }

        //未关联查体
        QueryWrapper<QuestionInfo> unSelectedVitalQueryWrapper = new QueryWrapper<>();
        unSelectedVitalQueryWrapper.eq("is_deleted", IsDeleteEnum.N.getKey()).
                eq("sub_type", 0).
                eq("type", QuestionTypeEnum.Vital.getKey());
        if (vitalIds.size() > 0) {
            unSelectedVitalQueryWrapper.notIn("id", vitalIds);
        }
        List<QuestionInfo> unSelectedVitalList = questionFacade.list(unSelectedVitalQueryWrapper);
        List<QuestionShortDTO> unSelectedVitals = BeanUtil.listCopyTo(unSelectedVitalList, QuestionShortDTO.class);
        deptVitalDTO.setUnSelectedVitals(unSelectedVitals);
        return deptVitalDTO;
    }


    /**
     * 获取科室模板分页信息
     *
     * @param deptVitalPageVO
     * @return
     */
    public IPage<DeptVitalDTO> getDeptVitalPageByMap(DeptVitalPageVO deptVitalPageVO) {
        IPage<DeptVitalDTO> page = this.getDeptVitalPage(deptVitalPageVO);
        List<DeptVitalDTO> deptVitalDTOList = page.getRecords();
        List<String> userIds = deptVitalDTOList.stream().map(deptVitalDTO -> deptVitalDTO.getOperator()).collect(Collectors.toList());
        RespDTO<Map<String, String>> data = userServiceClient.getUserInfoByIds(userIds);
        Map<String, String> userInfos = data.data;
        for (DeptVitalDTO deptVitalDTO : deptVitalDTOList) {
            if (userInfos.get(deptVitalDTO.getOperator()) != null) {
                deptVitalDTO.setOperatorName(userInfos.get(deptVitalDTO.getOperator()));
            }
        }
        page.setRecords(deptVitalDTOList);
        return page;
    }

    /**
     * 获取科室下拉列表
     *
     * @return
     */
    public List<DeptShortDTO> getDeptShortList(List<Long> deptIds) {
        QueryWrapper<DeptInfo> deptInfoQueryWrapper = new QueryWrapper<>();
        deptInfoQueryWrapper.eq("is_deleted", IsDeleteEnum.N.getKey()).
                notIn("id", deptIds);
        List<DeptInfo> deptInfoList = deptInfoFacade.list(deptInfoQueryWrapper);
        List<DeptShortDTO> deptShortDTOList = BeanUtil.listCopyTo(deptInfoList, DeptShortDTO.class);
        return deptShortDTOList;
    }

    /**
     * 获取科室下拉列表-新增
     *
     * @return
     */
    public List<DeptShortDTO> getDeptShortLisCreate() {
        QueryWrapper<DeptVital> deptVitalQueryWrapper = new QueryWrapper<>();
        deptVitalQueryWrapper.eq("is_deleted", IsDeleteEnum.N.getKey()).
                select("dept_id").
                groupBy("dept_id");
        List<DeptVital> deptVitalList = this.list(deptVitalQueryWrapper);
        List<Long> deptIds = deptVitalList.stream().map(deptVital -> deptVital.getDeptId()).collect(Collectors.toList());
        return getDeptShortList(deptIds);
    }

    /**
     * 获取科室下拉列表-修改
     *
     * @return
     */
    public List<DeptShortDTO> getDeptShortLisModify(Long expId) {
        QueryWrapper<DeptVital> deptVitalQueryWrapper = new QueryWrapper<>();
        deptVitalQueryWrapper.eq("is_deleted", IsDeleteEnum.N.getKey()).
                select("dept_id").
                groupBy("dept_id");
        List<DeptVital> deptVitalList = this.list(deptVitalQueryWrapper);
        List<Long> deptIds = deptVitalList.stream().map(deptVital -> deptVital.getDeptId()).collect(Collectors.toList());
        if (deptIds.contains(expId)) {
            deptIds.remove(expId);
            deptIds.size();
        }
        return getDeptShortList(deptIds);
    }
}