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.dto.AlgorithmDTO;
import com.diagbot.dto.AnalyzeDTO;
import com.diagbot.dto.QcCasesHistoryDTO;
import com.diagbot.dto.QcResultDTO;
import com.diagbot.entity.BehospitalInfo;
import com.diagbot.entity.MedQcresultCases;
import com.diagbot.entity.QcresultDetail;
import com.diagbot.entity.QcresultInfo;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.exception.CommonErrorCode;
import com.diagbot.exception.CommonException;
import com.diagbot.service.impl.MedQcresultCasesServiceImpl;
import com.diagbot.service.impl.QcresultDetailServiceImpl;
import com.diagbot.service.impl.QcresultInfoServiceImpl;
import com.diagbot.util.BeanUtil;
import com.diagbot.util.DateUtil;
import com.diagbot.util.ListUtil;
import com.diagbot.util.StringUtil;
import com.diagbot.util.SysUserUtils;
import com.diagbot.vo.*;
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.Date;
import java.util.List;

/**
 * @Description:
 * @Author:zhaops
 * @time: 2020/4/13 17:22
 */
@Component
public class QcresultInfoFacade extends QcresultInfoServiceImpl {
    @Autowired
    @Qualifier("qcresultDetailServiceImpl")
    private QcresultDetailServiceImpl qcresultDetailServiceImpl;
    @Autowired
    private AlgorithmFacade algorithmFacade;
    @Autowired
    private BehospitalInfoFacade behospitalInfoFacade;
    @Autowired
    private MedCheckInfoFacade medCheckInfoFacade;
    @Autowired
    @Qualifier("medQcresultCasesServiceImpl")
    private MedQcresultCasesServiceImpl medQcresultCasesService;

    /**
     * 修改评分结果信息
     *
     * @param qcresultVO 修改评分结果信息
     * @return 评分的结果
     */
    public AnalyzeDTO changeQcResult(QcresultVO qcresultVO) {
        //入参验证
        if (StringUtil.isBlank(qcresultVO.getBehospitalCode())) {
            throw new CommonException(CommonErrorCode.PARAM_IS_NULL, "病历id不能为空！");
        }
        if (null == qcresultVO.getOptResultAlgVO()) {
            throw new CommonException(CommonErrorCode.PARAM_IS_NULL, "操作条目不能为空！");
        }

        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", qcresultVO.getBehospitalCode()));
        if (behospitalInfos.size() != 1) {
            throw new CommonException(CommonErrorCode.NOT_EXISTS, "该医院下该病历号不存在！");
        }
        //验证是否评估过
        QcresultInfo qcresultInfo
                = this.getOne(
                new QueryWrapper<QcresultInfo>()
                        .eq("is_deleted", IsDeleteEnum.N.getKey())
                        .eq("hospital_id", hospitalId)
                        .eq("behospital_code", qcresultVO.getBehospitalCode()), false);
        if (null == qcresultInfo) {
            throw new CommonException(CommonErrorCode.NOT_EXISTS, "该病历尚未评分，请先评分！");
        }
        //查询质控评分明细信息
        qcresultVO.setHospitalId(hospitalId);
        List<QcresultDetail> qcresultDetails
                = qcresultDetailServiceImpl.list(
                new QueryWrapper<QcresultDetail>()
                        .eq("is_deleted", IsDeleteEnum.N.getKey())
                        .eq("hospital_id", hospitalId)
                        .eq("behospital_code", qcresultVO.getBehospitalCode()));

        //评分
        AlgorithmVO algorithmVO = new AlgorithmVO();
        List<QcResultAlgVO> qcResultAlgVOList
                = BeanUtil.listCopyTo(qcresultDetails, QcResultAlgVO.class);
        algorithmVO.setType(qcresultVO.getType());
        algorithmVO.setOptResultAlgVO(qcresultVO.getOptResultAlgVO());
        algorithmVO.setQcResultAlgVOList(qcResultAlgVOList);
        algorithmVO.setHospitalId(hospitalId);
        algorithmVO.setBehospitalCode(qcresultVO.getBehospitalCode());
        algorithmVO.setIsPlacefile(behospitalInfos.get(0).getIsPlacefile());
        algorithmVO.setDelStatus(qcresultVO.getDelStatus());
        AlgorithmDTO algorithmDTO = algorithmFacade.getAlgorithmRes(algorithmVO);
        //更新质控评分结果信息
        AnalyzeVO analyzeVO = new AnalyzeVO();
        analyzeVO.setHospitalId(hospitalId);
        analyzeVO.setBehospitalCode(qcresultVO.getBehospitalCode());
        analyzeVO.setDelStatus(qcresultVO.getDelStatus());
        Date date = this.saveQcResult(algorithmDTO, algorithmVO, analyzeVO, null, null, false, qcresultInfo);
        //返回参数组装
        AnalyzeDTO analyzeDTO = new AnalyzeDTO();
        analyzeDTO.setBehospitalCode(qcresultVO.getBehospitalCode());
        analyzeDTO.setIsSuccess(true);
        analyzeDTO.setGradeType(2);
        analyzeDTO.setGradeTypeName("人工");
        analyzeDTO.setScoreRes(algorithmDTO.getScore());
        analyzeDTO.setLevel(algorithmDTO.getLevel());
        analyzeDTO.setGradeTime(date);
        return analyzeDTO;
    }

    /**
     * 保存评分结果信息
     *
     * @param algorithmDTO 评分结果
     * @param algorithmVO  操作的条目
     * @param analyzeVO    病历信息
     * @param pageData     大数据解析出来的页面信息
     * @param menuData     菜单信息
     * @param isTask       是否是任务
     * @return 评分的时间
     */
    public Date saveQcResult(AlgorithmDTO algorithmDTO, AlgorithmVO algorithmVO, AnalyzeVO analyzeVO,
                             String pageData, String menuData, Boolean isTask, QcresultInfo qcresultInfoOld) {
        //更新质控评分结果信息
        Long useId = 0L;
        if (!isTask) {
            try {
                useId = Long.valueOf(SysUserUtils.getCurrentPrincipleID());
            } catch (Exception e) {
                //analyze_run运行质控没有登录认证   所以会获取不到
                useId = 952795279527L;
            }
        }
        //获取上一次人工添加的缺陷
        QcresultInfo qcresultInfoup
                = this.getOne(
                new QueryWrapper<QcresultInfo>()
                        .eq("is_deleted", IsDeleteEnum.N.getKey())
                        .eq("hospital_id", analyzeVO.getHospitalId())
                        .eq("behospital_code", analyzeVO.getBehospitalCode()), false);
        Date now = DateUtil.now();
        this.update(new UpdateWrapper<QcresultInfo>()
                .eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq("hospital_id", analyzeVO.getHospitalId())
                .eq("behospital_code", analyzeVO.getBehospitalCode())
                .set("is_deleted", IsDeleteEnum.Y.getKey())
                .set("modifier", useId)
                .set("gmt_modified", now));
        //清空本病历所有历史记录的page_data和menu_data
        this.update(new UpdateWrapper<QcresultInfo>()
                .eq("hospital_id", analyzeVO.getHospitalId())
                .eq("behospital_code", analyzeVO.getBehospitalCode())
                .set("page_data",null)
                .set("menu_data",null));
        //新增记录
        QcresultInfo qcresultInfo = new QcresultInfo();
        if (qcresultInfoOld != null) {
            //新增、删除、修改时的操作
            BeanUtil.copyProperties(qcresultInfoOld, qcresultInfo);
        } else {
            //基本评分是的操作
            qcresultInfo.setHaveHomePage(analyzeVO.getHaveHomePage());
        }
        qcresultInfo.setBehospitalCode(analyzeVO.getBehospitalCode());
        qcresultInfo.setHospitalId(analyzeVO.getHospitalId());
        qcresultInfo.setScoreRes(algorithmDTO.getScore());
        qcresultInfo.setLevel(algorithmDTO.getLevel());
        if (algorithmVO.getType().equals(0)) {
            qcresultInfo.setGradeType(1);
        } else {
            qcresultInfo.setGradeType(2);
        }
        if (StringUtil.isNotBlank(pageData)) {
            qcresultInfo.setPageData(pageData);
        }
        if (StringUtil.isNotBlank(menuData)) {
            qcresultInfo.setMenuData(menuData);
        }

        qcresultInfo.setGmtCreate(now);
        qcresultInfo.setCreator(useId.toString());
        qcresultInfo.setGmtModified(now);
        qcresultInfo.setModifier(useId.toString());
        this.save(qcresultInfo);
        Long newId = qcresultInfo.getId();
        //更新质控评分明细信息
        switch (algorithmVO.getType()) {
            //自动评分
            case 0:
                //删除记录
//                qcresultDetailServiceImpl.remove(new QueryWrapper<QcresultDetail>()
//                        .eq("hospital_id", analyzeVO.getHospitalId())
//                        .eq("behospital_code", analyzeVO.getBehospitalCode()));

                //上一次人工评分条目
                List<QcresultDetail> oldQcresultDetails = null;
                if (qcresultInfoup != null) {
                    oldQcresultDetails = qcresultDetailServiceImpl.list(new QueryWrapper<QcresultDetail>()
                            .eq("hospital_id", analyzeVO.getHospitalId())
                            .eq("qcresult_info_id", qcresultInfoup.getId())
                            .eq("grade_type", "2")
                            .eq("behospital_code", analyzeVO.getBehospitalCode()));
                }

                qcresultDetailServiceImpl.update(new UpdateWrapper<QcresultDetail>()
                        .eq("is_deleted", IsDeleteEnum.N.getKey())
                        .eq("hospital_id", analyzeVO.getHospitalId())
                        .eq("behospital_code", analyzeVO.getBehospitalCode())
                        .set("is_deleted", IsDeleteEnum.Y.getKey()));
                //
                //批量插入新的数据
                List<QcresultDetail> qcresultDetailList = new ArrayList<>();
                if (ListUtil.isNotEmpty(oldQcresultDetails)) {
                    qcresultDetailList.addAll(oldQcresultDetails);
                    qcresultDetailList.forEach(qcresultDetail -> {
                        //原手动添加缺陷绑定新机器评分id
                        qcresultDetail.setQcresultInfoId(newId);
                    });
                }
                List<QcResultAlgVO> qcResultAlgVORes = algorithmVO.getQcResultAlgVOList();
                if (ListUtil.isNotEmpty(qcResultAlgVORes)) {
                    for (QcResultAlgVO qcResultAlgVO : qcResultAlgVORes) {
                        QcresultDetail qcresultDetail = new QcresultDetail();
                        BeanUtil.copyProperties(qcResultAlgVO, qcresultDetail);
                        qcresultDetail.setHospitalId(analyzeVO.getHospitalId());
                        qcresultDetail.setBehospitalCode(analyzeVO.getBehospitalCode());
                        qcresultDetail.setGradeType(1);
                        qcresultDetail.setOptType(1);
                        qcresultDetail.setGmtCreate(now);
                        qcresultDetail.setCreator(useId.toString());
                        qcresultDetail.setGmtModified(now);
                        qcresultDetail.setModifier(useId.toString());
                        qcresultDetail.setInfo(StringUtil.isNotBlank(qcResultAlgVO.getInfo()) ? qcResultAlgVO.getInfo() : "");
                        qcresultDetail.setQcresultInfoId(newId);
                        qcresultDetailList.add(qcresultDetail);
                    }
                }
                qcresultDetailServiceImpl.saveBatch(qcresultDetailList);
                break;
            case 1:
                //新增条目
                QcresultDetail qcresultDetailAdd = new QcresultDetail();
                BeanUtil.copyProperties(algorithmVO.getOptResultAlgVO(), qcresultDetailAdd);
                qcresultDetailAdd.setGradeType(2);
                qcresultDetailAdd.setOptType(1);
                qcresultDetailAdd.setHospitalId(analyzeVO.getHospitalId());
                qcresultDetailAdd.setBehospitalCode(analyzeVO.getBehospitalCode());
                qcresultDetailAdd.setGmtCreate(now);
                qcresultDetailAdd.setCreator(useId.toString());
                qcresultDetailAdd.setGmtModified(now);
                qcresultDetailAdd.setModifier(useId.toString());
                qcresultDetailAdd.setQcresultInfoId(newId);
                qcresultDetailServiceImpl.save(qcresultDetailAdd);
                break;
            case 2:
                //删除条目
                qcresultDetailServiceImpl.remove(new QueryWrapper<QcresultDetail>()
                        .eq("id", algorithmVO.getOptResultAlgVO().getId())
                        .eq("hospital_id", analyzeVO.getHospitalId())
                        .eq("behospital_code", analyzeVO.getBehospitalCode())
                );
                break;
            case 3:
                //修改条目
                qcresultDetailServiceImpl.update(new UpdateWrapper<QcresultDetail>()
                        .eq("id", algorithmVO.getOptResultAlgVO().getId())
                        .eq("is_deleted", IsDeleteEnum.N.getKey())
                        .eq("hospital_id", analyzeVO.getHospitalId())
                        .eq("behospital_code", analyzeVO.getBehospitalCode())
                        .set("msg", algorithmVO.getOptResultAlgVO().getMsg())
                        .set("score", algorithmVO.getOptResultAlgVO().getScore())
                        .set("opt_type", 3)
                        .set("grade_type", 2)
                        .set("modifier", useId)
                        .set("qcresult_info_id", newId)
                        .set("gmt_modified", now)
                        .set("explain_info", algorithmVO.getOptResultAlgVO().getExplainInfo())
                );
                break;
            case 4:
                //获取病历核查人员id，该操作只能是核查员操作
//                Long checkId = medCheckInfoFacade.getOne(new QueryWrapper<MedCheckInfo>()
//                        .eq("is_deleted", IsDeleteEnum.N.getKey())
//                        .eq("hospital_id", analyzeVO.getHospitalId())
//                        .eq("behospital_code", analyzeVO.getBehospitalCode())).getCheckId();
//                if(checkId==null)
//                {
//                    throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "病历没有分配核查人员");
//                }
//                if(!checkId.equals(useId))
//                {
//                    throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "当前用户不是分配的核查人员");
//                }
                //逻辑删除质控明细 0删除
                if (analyzeVO.getDelStatus() == 0) {
                    qcresultDetailServiceImpl.update(new UpdateWrapper<QcresultDetail>()
                            .eq("id", algorithmVO.getOptResultAlgVO().getId())
                            .eq("is_deleted", IsDeleteEnum.N.getKey())
                            .eq("hospital_id", analyzeVO.getHospitalId())
                            .eq("behospital_code", analyzeVO.getBehospitalCode())
                            .set("is_deleted", IsDeleteEnum.Y.getKey())
                            .set("grade_type", 2)
                            .set("opt_type", 2)
                            .set("qcresult_info_id", newId)
                            .set("modifier", useId)
                            .set("gmt_modified", now)
                    );
                }
                //1恢复
                else if (analyzeVO.getDelStatus() == 1) {
                    //该条目是机器插入条目
                    qcresultDetailServiceImpl.update(new UpdateWrapper<QcresultDetail>()
                            .eq("id", algorithmVO.getOptResultAlgVO().getId())
                            .eq("is_deleted", IsDeleteEnum.Y.getKey())
                            .eq("hospital_id", analyzeVO.getHospitalId())
                            .eq("behospital_code", analyzeVO.getBehospitalCode())
                            .set("is_deleted", IsDeleteEnum.N.getKey())
                            .set("grade_type", 2)
                            .set("opt_type", 1)
                            .set("qcresult_info_id", newId)
                            .set("modifier", useId)
                            .set("gmt_modified", now)
                    );
                } else {
                    throw new CommonException(CommonErrorCode.PARAM_IS_ERROR, "delStatus参数错误");
                }
                break;
            default:
                /* DO NOTHING */
                break;
        }

        //如果不是自动评分（是新增修改删除条目）修改评分主表id
        if (algorithmVO.getType() != 0) {
            //修改上一次人工条目 评分主表id
            if (qcresultInfoup != null && qcresultInfoup.getId() != null) {
                qcresultDetailServiceImpl.update(new UpdateWrapper<QcresultDetail>()
                        .eq("qcresult_info_id", qcresultInfoup.getId())
                        .eq("hospital_id", analyzeVO.getHospitalId())
                        .eq("grade_type", 2)
                        .eq("behospital_code", analyzeVO.getBehospitalCode())
                        .set("qcresult_info_id", newId)
                );
            }
            //未删除的 评分主表id
            qcresultDetailServiceImpl.update(new UpdateWrapper<QcresultDetail>()
                    .eq("is_deleted", IsDeleteEnum.N.getKey())
                    .eq("hospital_id", analyzeVO.getHospitalId())
                    .eq("behospital_code", analyzeVO.getBehospitalCode())
                    .set("qcresult_info_id", newId)
            );
        }


        //质控模块评分数据
        //统一为长兴的算法
        //逻辑删除数据
        medQcresultCasesService.update(new UpdateWrapper<MedQcresultCases>()
                .eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq("hospital_id", analyzeVO.getHospitalId())
                .eq("behospital_code", analyzeVO.getBehospitalCode())
                .set("is_deleted", IsDeleteEnum.Y.getKey())
                .set("modifier", useId)
                .set("gmt_modified", now));
        //批量插入新的数据
        List<MedQcresultCases> medQcresultCasesList = new ArrayList<>();
        List<MedQcresultCasesVO> medQcresultCasesVOList = algorithmVO.getMedQcresultCasesVOList();
        if (ListUtil.isNotEmpty(medQcresultCasesVOList)) {
            for (MedQcresultCasesVO medQcresultCasesVO : medQcresultCasesVOList) {
                MedQcresultCases medQcresultCases = new MedQcresultCases();
                BeanUtil.copyProperties(medQcresultCasesVO, medQcresultCases);
                medQcresultCases.setGmtCreate(now);
                medQcresultCases.setCreator(useId.toString());
                medQcresultCases.setGmtModified(now);
                medQcresultCases.setModifier(useId.toString());
                medQcresultCases.setQcresultInfoId(newId);
                medQcresultCasesList.add(medQcresultCases);
            }
            medQcresultCasesService.saveBatch(medQcresultCasesList);
        }
        return now;
    }


    /**
     * 获取评分主表信息
     *
     * @param getDetailVO
     * @return
     */
    public QcResultDTO getByBehospitalCode(GetDetailVO getDetailVO) {
        QcResultDTO res = new QcResultDTO();
        QcresultInfo qcresultInfo = this.getOne(new QueryWrapper<QcresultInfo>()
                .eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq("hospital_id", getDetailVO.getHospitalId())
                .eq("behospital_code", getDetailVO.getBehospitalCode()), false
        );
        if (qcresultInfo != null) {
            BeanUtil.copyProperties(qcresultInfo, res);
        } else {
            return null;
        }
        return res;
    }

    /**
     * 历史评分
     * @param historyAnalyzePageVO
     * @return
     */
    public IPage<QcCasesHistoryDTO> getMedQcresultResultList(HistoryAnalyzePageVO historyAnalyzePageVO){
        return getMedQcresultResult(historyAnalyzePageVO);
    }
}
