package com.diagbot.facade;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.diagbot.dto.BehospitalInfoDTO;
import com.diagbot.dto.ExportExcelBehospitalDTO;
import com.diagbot.dto.ExportExcelDTO;
import com.diagbot.dto.GetEntryDefectImproveDTO;
import com.diagbot.dto.GetQcClickDTO;
import com.diagbot.dto.GetQcClickInnerPageDTO;
import com.diagbot.entity.MedClickInfo;
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.MedClickInfoServiceImpl;
import com.diagbot.util.BeanUtil;
import com.diagbot.util.DateUtil;
import com.diagbot.util.ExcelUtils;
import com.diagbot.util.ListUtil;
import com.diagbot.util.StringUtil;
import com.diagbot.util.SysUserUtils;
import com.diagbot.vo.GetEntryDefectImproveInnerVO;
import com.diagbot.vo.GetEntryDefectImproveVO;
import com.diagbot.vo.GetQcClickInnerPageVO;
import com.diagbot.vo.GetQcClickVO;
import com.diagbot.vo.MedClickInfoVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @Description:数据分析
 * @Author: cy
 * @time: 2021/11/16 18:28
 */
@Component
public class DataAnalysisFacade {
    @Autowired
    @Qualifier("medClickInfoServiceImpl")
    private MedClickInfoServiceImpl medClickInfoService;

    @Autowired
    private QcresultInfoFacade qcresultInfoFacade;


    /**
     * @Description:医生质控信息次数
     * @Param: [medClickInfoVO]
     * @return: void
     * @Author: cy
     * @Date: 2021/11/10
     */
    public Boolean addMedClickInfo(MedClickInfoVO medClickInfoVO) {
        MedClickInfo medClickInfo = new MedClickInfo();
        BeanUtil.copyProperties(medClickInfoVO, medClickInfo);
        QcresultInfo qcresultInfo = qcresultInfoFacade.lambdaQuery()
                .eq(QcresultInfo::getHospitalId, medClickInfoVO.getHospitalId())
                .eq(QcresultInfo::getBehospitalCode, medClickInfoVO.getBehospitalCode())
                .eq(QcresultInfo::getIsDeleted, IsDeleteEnum.N.getKey())
                .select(QcresultInfo::getId).one();
        if(null == qcresultInfo || null == qcresultInfo.getId()
        ){
            throw new CommonException(CommonErrorCode.PARAM_IS_ERROR, "内部参数异常");
        }
        medClickInfo.setQcresultInfoId(qcresultInfo.getId());
        medClickInfo.setGmtCreate(new Date());
        return medClickInfoService.save(medClickInfo);
    }

    public List<GetQcClickDTO> getQcClick(GetQcClickVO getQcClickVO) {
        clickPageSet(getQcClickVO);
        List<GetQcClickDTO> records = medClickInfoService.getBaseMapper().getQcClick(getQcClickVO);
        //没有科室过滤时增加全院数据
        if (StringUtil.isBlank(getQcClickVO.getDeptName()) || getQcClickVO.getDeptName().equals("全院")) {
            GetQcClickDTO item = getGlobleTitle(records);
            if (item != null) {
                records.add(0, item);
            }
        }
        return records;
    }


    public void getQcClickByExport(HttpServletResponse response, GetQcClickVO getQcClickVO) {
        List<GetQcClickDTO> records = getQcClick(getQcClickVO);
        String fileName = "临床质控使用统计.xls";
        ExcelUtils.exportExcel(records, null, "sheet1", GetQcClickDTO.class, fileName, response, 12.8f);
    }

    public IPage<GetQcClickInnerPageDTO> getQcClickInnerPage(GetQcClickInnerPageVO getQcClickInnerPageVO) {
        clickInnerPageSet(getQcClickInnerPageVO);
        IPage<GetQcClickInnerPageDTO> records = medClickInfoService.getBaseMapper().getQcClickInnerPage(getQcClickInnerPageVO);
        return records;
    }

    public void getQcClickInnerPageByExport(HttpServletResponse response,GetQcClickInnerPageVO getQcClickInnerPageVO) {
        getQcClickInnerPageVO.setCurrent(1L);
        getQcClickInnerPageVO.setSize(Long.MAX_VALUE);
        getQcClickInnerPageVO.setSearchCount(false);
        IPage<GetQcClickInnerPageDTO> page = getQcClickInnerPage(getQcClickInnerPageVO);
        String fileName = "临床质控使用统计内页.xls";
        ExcelUtils.exportExcel(page.getRecords(), null, "sheet1", GetQcClickInnerPageDTO.class, fileName, response, 12.8f);
    }

    public IPage<GetEntryDefectImproveDTO> getEntryDefectImprove(GetEntryDefectImproveVO getEntryDefectImproveVO) {
        entryDefectSet(getEntryDefectImproveVO);
        IPage<GetEntryDefectImproveDTO> records = medClickInfoService.getBaseMapper().getEntryDefectImprove(getEntryDefectImproveVO);
        return records;
    }

    public void getEntryDefectImproveByExport(HttpServletResponse response,GetEntryDefectImproveVO getEntryDefectImproveVO) {
        getEntryDefectImproveVO.setCurrent(1L);
        getEntryDefectImproveVO.setSize(Long.MAX_VALUE);
        getEntryDefectImproveVO.setSearchCount(false);
        IPage<GetEntryDefectImproveDTO> page = getEntryDefectImprove(getEntryDefectImproveVO);
        String fileName = "条目缺陷改善统计.xls";
        ExcelUtils.exportExcel(page.getRecords(), null, "sheet1", GetEntryDefectImproveDTO.class, fileName, response, 12.8f);
    }


    public IPage<BehospitalInfoDTO> getEntryDefectImproveInner(GetEntryDefectImproveInnerVO getEntryDefectImproveInnerVO) {
        entryDefectInnerSet(getEntryDefectImproveInnerVO);
        IPage<BehospitalInfoDTO> records = medClickInfoService.getBaseMapper().getEntryDefectImproveInner(getEntryDefectImproveInnerVO);
        return records;
    }

    public void getDefectImproveInnerByExport(HttpServletResponse response,GetEntryDefectImproveInnerVO getEntryDefectImproveInnerVO) {
        entryDefectInnerSet(getEntryDefectImproveInnerVO);
        getEntryDefectImproveInnerVO.setCurrent(1L);
        getEntryDefectImproveInnerVO.setSize(Long.MAX_VALUE);
        getEntryDefectImproveInnerVO.setSearchCount(false);
        String fileName = "条目缺陷改善统计病历列表.xls";
        List<ExportExcelDTO> record = medClickInfoService.getBaseMapper().getDefectImproveInnerByExport(getEntryDefectImproveInnerVO);
        record.stream().forEach(kfc->{
            List<ExportExcelBehospitalDTO> excelBehospitalDTOS = kfc.getExcelBehospitalDTOS();
            Double avgScore = excelBehospitalDTOS.stream().parallel().collect(Collectors.averagingDouble(ExportExcelBehospitalDTO::getScore));
            kfc.setAvgScore(avgScore);
        });
        ExcelUtils.exportExcelUser(record, null, "sheet1", ExportExcelDTO.class, fileName, response);
    }

    /**
     * 增加全院记录
     *
     * @param records
     * @return
     */
    public GetQcClickDTO getGlobleTitle(List<GetQcClickDTO> records) {
        GetQcClickDTO item = new GetQcClickDTO();
        if (ListUtil.isEmpty(records)) {
            return null;
        }

        //缺陷总数
        Integer clickTol = records
                .stream()
                .map(GetQcClickDTO::getClickNum)
                .reduce(0, Integer::sum);
        if (clickTol == null) {
            clickTol = 0;
        }
        item.setDeptName("全院");
        item.setClickNum(clickTol);
        return item;
    }

    private void clickPageSet(GetQcClickVO getQcClickVO) {
        //入参验证
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date startDate = null;
        Date endDate = null;
        try {
            startDate = simpleDateFormat.parse(getQcClickVO.getStartDate());
            endDate = simpleDateFormat.parse(getQcClickVO.getEndDate());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (DateUtil.after(startDate,endDate)){
            throw new CommonException(CommonErrorCode.PARAM_IS_ERROR, "开始时间必须小于结束时间！");
        }
        getQcClickVO.setHospitalId(Long.parseLong(SysUserUtils.getCurrentHospitalID()));
    }

    private void clickInnerPageSet(GetQcClickInnerPageVO getQcClickInnerPageVO) {
        //入参验证
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date startDate = null;
        Date endDate = null;
        try {
            startDate = simpleDateFormat.parse(getQcClickInnerPageVO.getStartDate());
            endDate = simpleDateFormat.parse(getQcClickInnerPageVO.getEndDate());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (DateUtil.after(startDate,endDate)){
            throw new CommonException(CommonErrorCode.PARAM_IS_ERROR, "开始时间必须小于结束时间！");
        }
        getQcClickInnerPageVO.setHospitalId(Long.parseLong(SysUserUtils.getCurrentHospitalID()));
    }

    private void entryDefectSet(GetEntryDefectImproveVO getEntryDefectImproveVO) {
        //入参验证
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date startDate = null;
        Date endDate = null;
        try {
            startDate = simpleDateFormat.parse(getEntryDefectImproveVO.getStartDate());
            endDate = simpleDateFormat.parse(getEntryDefectImproveVO.getEndDate());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (DateUtil.after(startDate,endDate)){
            throw new CommonException(CommonErrorCode.PARAM_IS_ERROR, "开始时间必须小于结束时间！");
        }
        getEntryDefectImproveVO.setHospitalId(Long.parseLong(SysUserUtils.getCurrentHospitalID()));
    }

    private void entryDefectInnerSet(GetEntryDefectImproveInnerVO getEntryDefectImproveInnerVO) {
        //入参验证
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date startDate = null;
        Date endDate = null;
        try {
            startDate = simpleDateFormat.parse(getEntryDefectImproveInnerVO.getStartDate());
            endDate = simpleDateFormat.parse(getEntryDefectImproveInnerVO.getEndDate());

        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (DateUtil.after(startDate,endDate)){
            throw new CommonException(CommonErrorCode.PARAM_IS_ERROR, "开始时间必须小于结束时间！");
        }
        if(StringUtils.isNotBlank(getEntryDefectImproveInnerVO.getChTimeStart())
                && StringUtils.isNotBlank(getEntryDefectImproveInnerVO.getChTimeEnd())
        ){
            Date chTimeStartDate = null;
            Date chTimeEndDate = null;
            try {
                chTimeStartDate = simpleDateFormat.parse(getEntryDefectImproveInnerVO.getChTimeStart());
                chTimeEndDate = simpleDateFormat.parse(getEntryDefectImproveInnerVO.getChTimeStart());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if (DateUtil.after(chTimeStartDate,chTimeEndDate)){
                throw new CommonException(CommonErrorCode.PARAM_IS_ERROR, "病历核查开始时间必须小于结束时间！");
            }
        }
        getEntryDefectImproveInnerVO.setHospitalId(Long.parseLong(SysUserUtils.getCurrentHospitalID()));
    }
}
