package com.diagbot.facade;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.diagbot.dto.AnalyzeDTO;
import com.diagbot.dto.GetDefectDeptDTO;
import com.diagbot.dto.GetDefectModeDTO;
import com.diagbot.dto.GetMedDefectFeedbackPageDTO;
import com.diagbot.entity.BehospitalInfo;
import com.diagbot.entity.MedDefectFeedback;
import com.diagbot.entity.QcresultDetail;
import com.diagbot.entity.QcresultInfo;
import com.diagbot.entity.SysUser;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.exception.CommonErrorCode;
import com.diagbot.exception.CommonException;
import com.diagbot.facade.his.FeedbackHosFacade;
import com.diagbot.service.impl.MedDefectFeedbackServiceImpl;
import com.diagbot.util.BeanUtil;
import com.diagbot.util.DateUtil;
import com.diagbot.util.ListUtil;
import com.diagbot.util.SysUserUtils;
import com.diagbot.vo.CCVO;
import com.diagbot.vo.ChangeQcResultVO;
import com.diagbot.vo.GetDefectDeptModeVO;
import com.diagbot.vo.GetMedDefectFeedbackPageVO;
import com.diagbot.vo.QcresultVO;
import com.diagbot.vo.UPdDefectBackByIDVO;
import com.diagbot.vo.his.FeedbackHosVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Description:缺陷反馈模块处理类
 * @author: songxl
 * @time: 2022/4/21 10:03
 */
@Component
public class MedDefectFeedbackFacade extends MedDefectFeedbackServiceImpl {
    @Autowired
    private BehospitalInfoFacade behospitalInfoFacade;
    @Autowired
    private QcresultInfoFacade qcresultInfoFacade;
    @Autowired
    private SysUserFacade sysUserFacade;
    @Autowired
    private QcresultDetailFacade qcresultDetailFacade;
    @Autowired
    private FeedbackHosFacade feedbackHosFacade;
    @Autowired
    private MedDefectFeedbackServiceImpl medDefectFeedbackServiceImpl;



    /**
     * 操作病历
     *
     * @param changeQcResultVO
     * @Return com.diagbot.dto.AnalyzeDTO
     */
    public AnalyzeDTO changeQcResult(ChangeQcResultVO changeQcResultVO) {
        //1.获取病历基本信息
        Long hospitalId = Long.valueOf(SysUserUtils.getCurrentHospitalID());
        //验证病历的存在性
        List<BehospitalInfo> behospitalInfos
                = behospitalInfoFacade.list(
                new QueryWrapper<BehospitalInfo>()
                        .eq("is_deleted", IsDeleteEnum.N.getKey())
                        .eq("hospital_id", hospitalId)
                        .eq("behospital_code", changeQcResultVO.getBehospitalCode()));
        if (ListUtil.isEmpty(behospitalInfos)) {
            throw new CommonException(CommonErrorCode.NOT_EXISTS, "该医院下该病历号不存在！");
        }
        //获取操作用户
        QueryWrapper<SysUser> userQuer = new QueryWrapper<>();
        userQuer.eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq("id", SysUserUtils.getCurrentPrincipleID())
                .eq("status", 1);
        SysUser user = sysUserFacade.getOne(userQuer);
        if (user == null) {
            throw new CommonException(CommonErrorCode.NOT_EXISTS, "操作用户不存在,请联系管理员！");
        }

        //2.调用人工修改病历评分接口
        AnalyzeDTO out = new AnalyzeDTO();
        QcresultVO qcresultVO = new QcresultVO();
        BeanUtil.copyProperties(changeQcResultVO, qcresultVO);
        switch (changeQcResultVO.getOperationType()) {
            case "1"://修改
                qcresultVO.setType(3);
                out = qcresultInfoFacade.changeQcResult(qcresultVO);
                break;
            case "2"://删除
                qcresultVO.setType(4);
                qcresultVO.setDelStatus(0);
                out = qcresultInfoFacade.changeQcResult(qcresultVO);
                break;
            case "3"://新增已有
                qcresultVO.setType(1);
                //判断该缺陷是否存在
                havingCase(qcresultVO);
                out = qcresultInfoFacade.changeQcResult(qcresultVO);
                break;
            case "4"://新增缺失
                //新增缺失拼装返回结果
                //获取病历等级得分
                QcresultInfo qcresultInfo = qcresultInfoFacade
                        .getOne(new QueryWrapper<QcresultInfo>().select("level,score_res")
                                .eq("hospital_id", hospitalId)
                                .eq("behospital_code", qcresultVO.getBehospitalCode())
                                .eq("is_deleted", IsDeleteEnum.N.getKey()));
                out.setBehospitalCode(qcresultVO.getBehospitalCode());
                out.setIsSuccess(true);
                out.setGradeType(2);
                out.setGradeTypeName("人工");
                out.setScoreRes(qcresultInfo.getScoreRes());
                out.setLevel(qcresultInfo.getLevel());
                out.setGradeTime(DateUtil.now());
                break;
            case "5"://恢复
                qcresultVO.setType(4);
                qcresultVO.setDelStatus(1);
                out = qcresultInfoFacade.changeQcResult(qcresultVO);
                break;
            default:
                break;
        }

        //3.人工修改病历成功后
        if (out != null && out.getIsSuccess()) {
            MedDefectFeedback insert = new MedDefectFeedback();
            BeanUtil.copyProperties(changeQcResultVO, insert);
            insert.setDeptId(behospitalInfos.get(0).getBehDeptId());
            insert.setDeptName(behospitalInfos.get(0).getBehDeptName());
            insert.setName(behospitalInfos.get(0).getName());
            //除新增缺失以外都要记录所属条目ID、缺陷详情、分值信息
            if (!"4".equals(changeQcResultVO.getOperationType())) {
                //条目、缺陷详情、分值信息非空判断
                if(changeQcResultVO.getOptResultAlgVO().getCasesEntryId()==null){
                    throw new CommonException(CommonErrorCode.PARAM_IS_ERROR, "所属条目ID为空！");
                }
                if(changeQcResultVO.getOptResultAlgVO().getMsg()==null){
                    throw new CommonException(CommonErrorCode.PARAM_IS_ERROR, "缺陷详情为空！");
                }
                if(changeQcResultVO.getOptResultAlgVO().getScore()==null){
                    throw new CommonException(CommonErrorCode.PARAM_IS_ERROR, "条目分值为空！");
                }
                insert.setCasesEntryId(changeQcResultVO.getOptResultAlgVO().getCasesEntryId());
                insert.setQcresultDetailMsg(changeQcResultVO.getOptResultAlgVO().getMsg());
                insert.setQcresultDetaiScore(changeQcResultVO.getOptResultAlgVO().getScore());
            }
            insert.setHospitalId(hospitalId);
            insert.setGmtCreate(DateUtil.now());
            insert.setCreator(SysUserUtils.getCurrentPrincipleID());
            insert.setSenderCode(SysUserUtils.getCurrentPrincipleID());
            insert.setSenderName(user.getLinkman());
            if(ListUtil.isNotEmpty(changeQcResultVO.getCcs())){
                insert.setCcCodes(changeQcResultVO.getCcs().stream().map(CCVO::getUserId).collect(Collectors.joining(",")));
                insert.setCcNames(changeQcResultVO.getCcs().stream().map(CCVO::getName).collect(Collectors.joining(",")));
            }
            //保存结果
            if (!this.save(insert)) {
                throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "缺陷反馈保存失败！");
            }
            //4.推送给his方
            sendToHis(insert);
        }

        return out;
    }

    private void havingCase(QcresultVO qcresultVO) {
        if (qcresultVO.getOptResultAlgVO().getCasesEntryId() == null) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "条目ID不存在！");
        }
        //判断机器是否有质控出该缺陷或人工添加过该缺陷
        QueryWrapper<QcresultDetail> query = new QueryWrapper();
        query.eq("hospital_id", SysUserUtils.getCurrentHospitalID());
        query.eq("behospital_code", qcresultVO.getBehospitalCode());
        query.eq("cases_entry_id", qcresultVO.getOptResultAlgVO().getCasesEntryId());
        query.and(qw -> qw.eq("grade_type", 2)
                .or().eq("is_deleted", IsDeleteEnum.N.getKey()).eq("grade_type", 1));
        if (ListUtil.isNotEmpty(qcresultDetailFacade.list(query))) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "添加的缺陷条目已存在！");
        }
    }

    /**
     * 推送给his方
     *
     * @param insert
     * @Return void
     */
    private void sendToHis(MedDefectFeedback insert) {
        try {
            FeedbackHosVO feedbackHosVO = new FeedbackHosVO();
            BeanUtil.copyProperties(insert,feedbackHosVO);
            feedbackHosFacade.pushFeedback(feedbackHosVO);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 确认缺陷反馈
     *
     * @param uPdDefectBackByIDVO
     * @Return java.lang.Boolean
     */
    public Boolean updDefectBackByID(UPdDefectBackByIDVO uPdDefectBackByIDVO) {
        MedDefectFeedback entity = new MedDefectFeedback();
        entity.setId(uPdDefectBackByIDVO.getId());
        entity.setStatus("1");
        return this.updateById(entity);
    }

    /**
     * 获取缺陷反馈记录列表-缺陷模块下拉框内容
     *
     * @param
     * @return:
     */
    public List<GetDefectModeDTO> getDefectMode(GetDefectDeptModeVO getDefectDeptModeVO) {
        Long hospitalID = Long.valueOf(SysUserUtils.getCurrentHospitalID());
        getDefectDeptModeVO.setHospitalId(hospitalID);
        List<GetDefectModeDTO> defectDept = this.baseMapper.getDefectMode(getDefectDeptModeVO);
        return defectDept;
    }

    /**
     * 获取缺陷反馈记录列表-科室下拉框内容
     *
     * @param
     * @return:
     */
    public List<GetDefectDeptDTO> getDefectDept(GetDefectDeptModeVO getDefectDeptModeVO) {
        Long hospitalID = Long.valueOf(SysUserUtils.getCurrentHospitalID());
        getDefectDeptModeVO.setHospitalId(hospitalID);
        List<GetDefectDeptDTO> defectDept = this.baseMapper.getDefectDept(getDefectDeptModeVO);
        return defectDept;
    }

    /**
     * 获取缺陷反馈记录列表
     *
     * @param
     * @return:
     */
    public Page<GetMedDefectFeedbackPageDTO> getMedDefectFeedbackPage(GetMedDefectFeedbackPageVO getMedDefectFeedbackPageVO) {
        //更新待确认状态
        updateStatus();
        Page<GetMedDefectFeedbackPageDTO> medDefectFeedbackPage = this.baseMapper.getMedDefectFeedbackPage(getMedDefectFeedbackPageVO);
        return medDefectFeedbackPage;
    }

    /**
     * 更新待确认状态
     *
     * @param
     * @Return void
     */
    private void updateStatus() {
        try {
            //1.获取待确认的反馈缺陷id
            List<Long> ids = this.list(new QueryWrapper<MedDefectFeedback>()
                 .eq("hospital_id",SysUserUtils.getCurrentHospitalID())
                 .eq("status","0")
                 .eq("is_deleted",IsDeleteEnum.N.getKey())).stream()
                 .map(MedDefectFeedback::getId).collect(Collectors.toList());

            if(ListUtil.isNotEmpty(ids)){
                String strIds = Optional.of(ids).orElseGet(ArrayList::new).stream().map(String::valueOf).collect(Collectors.joining(","));
                FeedbackHosVO search = new FeedbackHosVO();
                search.setIds(strIds);
                //2.查his对应反馈缺陷的最新状态
                List<FeedbackHosVO> out = feedbackHosFacade.statusQuery(search).data;
                if(ListUtil.isNotEmpty(out)){
                    List<MedDefectFeedback> updates = new ArrayList<>();
                    out.stream().forEach(feedbackHosVO -> {
                        //获取his已确认的
                        if("1".equals(feedbackHosVO.getMsgStatus())){
                            MedDefectFeedback entity = new MedDefectFeedback();
                            entity.setId(feedbackHosVO.getId());
                            entity.setStatus(feedbackHosVO.getMsgStatus());
                            updates.add(entity);
                        }
                    });
                    //3.更新自己库中状态
                    if(ListUtil.isNotEmpty(updates)){
                        medDefectFeedbackServiceImpl.updateBatchById(updates);
                    }
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
