package com.diagbot.facade;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.diagbot.client.MedAppealExamineInfoServiceClientFacade;
import com.diagbot.dto.AnalyzeDTO;

import com.diagbot.dto.ExportGetAppealReviewDTO;
import com.diagbot.dto.ExportGetComplaintRecordDTO;
import com.diagbot.dto.GetAppealReviewDTO;
import com.diagbot.dto.GetComplaintRecordDTO;
import com.diagbot.dto.RespDTO;
import com.diagbot.entity.MedAppealExamineInfo;
import com.diagbot.entity.MedAppealInfo;

import com.diagbot.entity.QcCasesEntry;
import com.diagbot.entity.QcresultDetail;
import com.diagbot.enums.ExampleOperationEnum;
import com.diagbot.enums.ExampleStatusEnum;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.exception.CommonErrorCode;
import com.diagbot.exception.CommonException;
import com.diagbot.service.impl.MedAppealExamineInfoServiceImpl;
import com.diagbot.util.BeanUtil;
import com.diagbot.util.ExcelUtils;
import com.diagbot.util.ListUtil;
import com.diagbot.util.StringUtil;
import com.diagbot.vo.ApprovedVo;
import com.diagbot.vo.GetAppealReviewVO;
import com.diagbot.vo.GetComplaintRecordVO;
import com.diagbot.vo.QcResultAlgVO;
import com.diagbot.vo.QcresultVO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Description:申述记录
 * @Author: songxl
 * @Date 2022/1/5
 */
@Component
public class MedAppealExamineInfoManagementFacade extends MedAppealExamineInfoServiceImpl {
    @Autowired
    private QcresultDetailFacade qcresultDetailFacade;
    @Autowired
    private MedAppealInfoManagementFacade medAppealInfoManagementFacade;
    @Autowired
    private QcresultInfoFacade qcresultInfoFacade;
    @Autowired
    private QcCasesEntryFacade qcCasesEntryFacade;

    /**
     * 审核通过
     *
     * @param approvedVo
     * @return
     */
    public Boolean approved(ApprovedVo approvedVo) {
        LocalDateTime dateTime = LocalDateTime.now();
        QcresultVO qcresultVO = new QcresultVO();
        qcresultVO.setBehospitalCode(approvedVo.getBehospitalCode());
        qcresultVO.setHospitalId(approvedVo.getHospitalId());
        QcResultAlgVO qcResultAlgVO = approvedVo.getQcResultAlgVO();
        Long modeId = approvedVo.getModeId();
        if (modeId != null) {
            QcCasesEntry qcCasesEntry = qcCasesEntryFacade.getOne(new QueryWrapper<QcCasesEntry>()
                    .eq("is_deleted", IsDeleteEnum.N.getKey())
                    .eq("mode_id", modeId)
                    .groupBy("mode_id")
            );
            if(qcCasesEntry!=null) {
                qcResultAlgVO.setCasesId(qcCasesEntry.getCasesId());
            }
        }
        //获取处理方式
        String handling = approvedVo.getExampleOperation();
        if (StringUtil.isNotEmpty(handling) && handling.equals(ExampleOperationEnum.UP_OR_DEL.getKey())) {
            QcresultDetail detail = getQcresultDetail(approvedVo);
            if (detail == null) {
                throw new CommonException(CommonErrorCode.INSERT_DATA_FAILED, "该条目已删除，无法进行审核操作，请走驳回流程。");
            }
            //调用删除接口
            qcresultVO.setDelStatus(0);
            qcresultVO.setType(4);
            qcResultAlgVO.setId(detail.getId());
            qcresultVO.setOptResultAlgVO(qcResultAlgVO);
            AnalyzeDTO analyzeDTORespDTO = qcresultInfoFacade.changeQcResult(qcresultVO);
            if (analyzeDTORespDTO.getIsSuccess()) {
                approvedVo.setQcresultDetailId(detail.getId());
                Boolean appealInfo = updateAppealInfo(approvedVo);
                MedAppealExamineInfo medAppealExamineInfo = new MedAppealExamineInfo();
                medAppealExamineInfo.setExampleOperation(ExampleOperationEnum.UP_OR_DEL.getKey());
                medAppealExamineInfo.setExampleStatus(ExampleStatusEnum.ADOPT_EXAMPLE.getKey());
                medAppealExamineInfo.setMsg(qcresultVO.getOptResultAlgVO().getMsg());
                medAppealExamineInfo.setValue(qcresultVO.getOptResultAlgVO().getScore());
                medAppealExamineInfo.setGmtCreate(dateTime);
                medAppealExamineInfo.setRemark(qcResultAlgVO.getExplainInfo());
                boolean update = this.update(medAppealExamineInfo, new UpdateWrapper<MedAppealExamineInfo>()
                        .eq("is_deleted", IsDeleteEnum.N.getKey())
                        .eq("appeal_info_id", approvedVo.getId())
                        .eq("check_id", approvedVo.getAppealId())
                );
                if (appealInfo && update) {
                    return true;
                } else {
                    throw new CommonException(CommonErrorCode.INSERT_DATA_FAILED, "审核通过失败!");
                }
            } else {
                throw new CommonException(CommonErrorCode.INSERT_DATA_FAILED, "删除失败!");
            }
        }
        if (StringUtil.isNotEmpty(handling) && handling.equals(ExampleOperationEnum.UP_OR_UP.getKey())) {
            QcresultDetail detail = getQcresultDetail(approvedVo);
            if (detail == null) {
                throw new CommonException(CommonErrorCode.INSERT_DATA_FAILED, "该条目已删除，无法进行审核操作，请走驳回流程。");
            }
            //调用修改接口
            qcresultVO.setType(3);
            qcResultAlgVO.setId(detail.getId());
            qcresultVO.setOptResultAlgVO(qcResultAlgVO);
            AnalyzeDTO analyzeDTORespDTO = qcresultInfoFacade.changeQcResult(qcresultVO);
            if (analyzeDTORespDTO.getIsSuccess()) {
                Boolean appealInfo = updateAppealInfo(approvedVo);
                MedAppealExamineInfo medAppealExamineInfo = new MedAppealExamineInfo();
                medAppealExamineInfo.setExampleOperation(ExampleOperationEnum.UP_OR_UP.getKey());
                medAppealExamineInfo.setExampleStatus(ExampleStatusEnum.ADOPT_EXAMPLE.getKey());
                medAppealExamineInfo.setMsg(qcresultVO.getOptResultAlgVO().getMsg());
                medAppealExamineInfo.setValue(qcresultVO.getOptResultAlgVO().getScore());
                medAppealExamineInfo.setGmtCreate(dateTime);
                medAppealExamineInfo.setRemark(qcResultAlgVO.getExplainInfo());
                boolean update = this.update(medAppealExamineInfo, new UpdateWrapper<MedAppealExamineInfo>()
                        .eq("is_deleted", IsDeleteEnum.N.getKey())
                        .eq("appeal_info_id", approvedVo.getId())
                        .eq("check_id", approvedVo.getAppealId())
                );
                if (appealInfo && update) {
                    return true;
                } else {
                    throw new CommonException(CommonErrorCode.INSERT_DATA_FAILED, "审核通过失败!");
                }
            } else {
                throw new CommonException(CommonErrorCode.INSERT_DATA_FAILED, "修改失败!");
            }
        }
        if (StringUtil.isNotEmpty(handling) && handling.equals(ExampleOperationEnum.ADD_EXIST.getKey())) {
            //判断是否已存在该条目
            QcresultDetail qcresultDetail = getQcresultDetail(approvedVo);
            if (qcresultDetail != null) {
                throw new CommonException(CommonErrorCode.IS_EXISTS, "该条目已存在,无法新增，请走驳回流程");
            }
            //调用新增接口
            qcresultVO.setType(1);
            qcresultVO.setOptResultAlgVO(qcResultAlgVO);
            AnalyzeDTO analyzeDTORespDTO = qcresultInfoFacade.changeQcResult(qcresultVO);
            if (analyzeDTORespDTO.getIsSuccess()) {
                QcresultDetail detail = getQcresultDetail(approvedVo);
                MedAppealInfo medAppealInfo = new MedAppealInfo();
                medAppealInfo.setQcresultDetailId(detail.getId());
                medAppealInfo.setWorkFlowNodeId(approvedVo.getWorkFlowNodeId());
                boolean update = medAppealInfoManagementFacade.update(medAppealInfo, new UpdateWrapper<MedAppealInfo>()
                        .eq("is_deleted", IsDeleteEnum.N.getKey())
                        .eq("hospital_id", approvedVo.getHospitalId())
                        .eq("behospital_code", approvedVo.getBehospitalCode())
                        .eq("id", approvedVo.getId())
                );
                MedAppealExamineInfo medAppealExamineInfo = new MedAppealExamineInfo();
                medAppealExamineInfo.setExampleOperation(ExampleOperationEnum.ADD_EXIST.getKey());
                medAppealExamineInfo.setValue(qcresultVO.getOptResultAlgVO().getScore());
                medAppealExamineInfo.setMsg(qcresultVO.getOptResultAlgVO().getMsg());
                medAppealExamineInfo.setExampleStatus(ExampleStatusEnum.ADOPT_EXAMPLE.getKey());
                medAppealExamineInfo.setRemark(qcResultAlgVO.getExplainInfo());
                medAppealExamineInfo.setGmtCreate(dateTime);
                boolean update1 = this.update(medAppealExamineInfo, new UpdateWrapper<MedAppealExamineInfo>()
                        .eq("is_deleted", IsDeleteEnum.N.getKey())
                        .eq("appeal_info_id", approvedVo.getId())
                        .eq("check_id", approvedVo.getAppealId())
                );
                if (update && update1) {
                    return true;
                } else {
                    throw new CommonException(CommonErrorCode.INSERT_DATA_FAILED, "审核通过失败!");
                }
            } else {
                throw new CommonException(CommonErrorCode.INSERT_DATA_FAILED, "新增失败!");
            }
        }
        if (StringUtil.isNotEmpty(handling) && handling.equals(ExampleOperationEnum.RECOVER.getKey())) {
            qcresultVO.setType(4);
            qcresultVO.setDelStatus(1);
            //判断条目是否以恢复
            QcresultDetail qcresultDetail = getQcresultDetail(approvedVo);
            if (qcresultDetail != null) {
                throw new CommonException(CommonErrorCode.IS_EXISTS, "该条目已恢复，无法进行审核操作，请走驳回流程。");
            }

            //调用删除恢复接口
            List<QcresultDetail> qcresultDetails = qcresultDetailFacade.list(new QueryWrapper<QcresultDetail>()
                    .eq("hospital_id", approvedVo.getHospitalId())
                    .eq("behospital_code", approvedVo.getBehospitalCode())
                    .eq("cases_entry_id", approvedVo.getQcResultAlgVO().getCasesEntryId())
                    .eq("is_deleted",IsDeleteEnum.Y.getKey())
                    .eq("grade_type", 2)
                    .orderByDesc("id")
            );
            if(ListUtil.isNotEmpty(qcresultDetails)){
                qcResultAlgVO.setId(qcresultDetails.get(0).getId());
                qcresultVO.setOptResultAlgVO(qcResultAlgVO);
                AnalyzeDTO analyzeDTORespDTO = qcresultInfoFacade.changeQcResult(qcresultVO);
                if (analyzeDTORespDTO.getIsSuccess()) {
                    approvedVo.setQcresultDetailId(qcresultDetails.get(0).getId());
                    Boolean appealInfo = updateAppealInfo(approvedVo);
                    MedAppealExamineInfo medAppealExamineInfo = new MedAppealExamineInfo();
                    medAppealExamineInfo.setExampleOperation(ExampleOperationEnum.RECOVER.getKey());
                    medAppealExamineInfo.setValue(qcresultVO.getOptResultAlgVO().getScore());
                    medAppealExamineInfo.setMsg(qcresultVO.getOptResultAlgVO().getMsg());
                    medAppealExamineInfo.setExampleStatus(ExampleStatusEnum.ADOPT_EXAMPLE.getKey());
                    medAppealExamineInfo.setRemark(qcResultAlgVO.getExplainInfo());
                    medAppealExamineInfo.setGmtCreate(dateTime);
                    boolean update = this.update(medAppealExamineInfo, new UpdateWrapper<MedAppealExamineInfo>()
                            .eq("is_deleted", IsDeleteEnum.N.getKey())
                            .eq("appeal_info_id", approvedVo.getId())
                            .eq("check_id", approvedVo.getAppealId())
                    );
                    if (appealInfo && update) {
                        return true;
                    } else {
                        throw new CommonException(CommonErrorCode.INSERT_DATA_FAILED, "审核通过失败!");
                    }
                } else {
                    throw new CommonException(CommonErrorCode.INSERT_DATA_FAILED, "恢复失败!");
                }
            }
        }
        if (StringUtil.isNotEmpty(handling) && handling.equals(ExampleOperationEnum.ADD_NO_EXIST.getKey())) {
            Boolean appealInfo = updateAppealInfo(approvedVo);
            MedAppealExamineInfo medAppealExamineInfo = new MedAppealExamineInfo();
            medAppealExamineInfo.setExampleOperation(ExampleOperationEnum.ADD_NO_EXIST.getKey());
            medAppealExamineInfo.setExampleStatus(ExampleStatusEnum.ADOPT_EXAMPLE.getKey());
            medAppealExamineInfo.setProcessResult(approvedVo.getProcessResult());
            medAppealExamineInfo.setGmtCreate(dateTime);
            boolean update = this.update(medAppealExamineInfo, new UpdateWrapper<MedAppealExamineInfo>()
                    .eq("is_deleted", IsDeleteEnum.N.getKey())
                    .eq("appeal_info_id", approvedVo.getId())
                    .eq("check_id", approvedVo.getAppealId())
            );
            if (appealInfo && update) {
                return true;
            } else {
                throw new CommonException(CommonErrorCode.INSERT_DATA_FAILED, "审核通过失败!");
            }
        }
        throw new CommonException(CommonErrorCode.NOT_EXISTS, "无此类型处理方式!");
    }
    public Boolean updateAppealInfo(ApprovedVo approvedVo) {
        MedAppealInfo medAppealInfo = new MedAppealInfo();
        medAppealInfo.setQcresultDetailId(approvedVo.getQcresultDetailId());
        medAppealInfo.setWorkFlowNodeId(approvedVo.getWorkFlowNodeId());
        boolean update = medAppealInfoManagementFacade.update(medAppealInfo, new UpdateWrapper<MedAppealInfo>()
                .eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq("hospital_id", approvedVo.getHospitalId())
                .eq("behospital_code", approvedVo.getBehospitalCode())
                .eq("id", approvedVo.getId())
        );
        if (update) {
            return true;
        } else {
            return false;
        }
    }

    //  获取detail条目信息
    public QcresultDetail getQcresultDetail(ApprovedVo approvedVo) {
        QcresultDetail qcresultDetail = qcresultDetailFacade.getOne(new QueryWrapper<QcresultDetail>()
                .eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq("hospital_id", approvedVo.getHospitalId())
                .eq("behospital_code", approvedVo.getBehospitalCode())
                .eq("cases_entry_id", approvedVo.getQcResultAlgVO().getCasesEntryId())
        );
        return qcresultDetail;
    }

    public void getAppealReviewExport(HttpServletResponse response, GetAppealReviewVO getAppealReviewVO, MedAppealExamineInfoServiceClientFacade medAppealExamineInfoServiceClient) {
        getAppealReviewVO.setCurrent(1L);
        getAppealReviewVO.setSize(Long.MAX_VALUE);
        getAppealReviewVO.setSearchCount(false);
        RespDTO<Page<GetAppealReviewDTO>> appealReview = medAppealExamineInfoServiceClient.getAppealReview(getAppealReviewVO);
        //格式转换
        List<ExportGetAppealReviewDTO> out = BeanUtil.listCopyTo(appealReview.data.getRecords(), ExportGetAppealReviewDTO.class);
        String fileName = "申诉审核.xls";
        ExcelUtils.exportExcelUser(out, null, "sheet1", ExportGetAppealReviewDTO.class, fileName, response);
    }

    public void getComplaintRecordExport(HttpServletResponse response, GetComplaintRecordVO getComplaintRecordVO, MedAppealExamineInfoServiceClientFacade medAppealExamineInfoServiceClient) {
        getComplaintRecordVO.setCurrent(1L);
        getComplaintRecordVO.setSize(Long.MAX_VALUE);
        getComplaintRecordVO.setSearchCount(false);
        RespDTO<Page<GetComplaintRecordDTO>> complaintRecord = medAppealExamineInfoServiceClient.getComplaintRecord(getComplaintRecordVO);
        //格式转换
        List<ExportGetComplaintRecordDTO> out = BeanUtil.listCopyTo(complaintRecord.data.getRecords(), ExportGetComplaintRecordDTO.class);
        String fileName = "申诉记录.xls";
        ExcelUtils.exportExcelUser(out, null, "sheet1", ExportGetComplaintRecordDTO.class, fileName, response);
    }
}
