package com.diagbot.facade;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.diagbot.dto.BehospitalCodeInfo;
import com.diagbot.dto.EntryDefectImproveInnerDoctor;
import com.diagbot.dto.EntryDefectImproveInnerExport;
import com.diagbot.dto.GetEntryDefectImproveDeptDTO;
import com.diagbot.dto.GetEntryInfoDTO;
import com.diagbot.exception.CommonErrorCode;
import com.diagbot.exception.CommonException;
import com.diagbot.service.impl.MedClickInfoServiceImpl;
import com.diagbot.util.DateUtil;
import com.diagbot.util.ExcelUtils;
import com.diagbot.util.ListUtil;
import com.diagbot.util.SysUserUtils;
import com.diagbot.vo.GetEntryDefectImproveDeptVO;
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.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


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

    public IPage<GetEntryDefectImproveDeptDTO> getEntryDefectImproveDept(GetEntryDefectImproveDeptVO getEntryDefectImproveDeptVO) {
        int current = (int) getEntryDefectImproveDeptVO.getCurrent();
        int size = (int) getEntryDefectImproveDeptVO.getSize();
        entryDefectDeptSet(getEntryDefectImproveDeptVO);
        IPage<GetEntryDefectImproveDeptDTO> page = new Page<>();
        List<GetEntryDefectImproveDeptDTO> getEntryDefectImproveDeptDTOList = new ArrayList<>();
        DecimalFormat df = new DecimalFormat("#.00");
        //获取标准缺陷信息
        List<GetEntryInfoDTO> entryInfo = medClickInfoService.getBaseMapper().getEntryInfo();
        //查询基础数据源
        List<EntryDefectImproveInnerExport> records = medClickInfoService.getBaseMapper().getEntryDefectImproveDept(getEntryDefectImproveDeptVO);
        //遍历科室
        for (EntryDefectImproveInnerExport entryDefectImproveInnerExport : records) {
            List<EntryDefectImproveInnerDoctor> entryDefectImproveInnerDoctors = entryDefectImproveInnerExport.getEntryDefectImproveInnerDoctors();
            for (EntryDefectImproveInnerDoctor entryDefectImproveInnerDoctor : entryDefectImproveInnerDoctors) {
                //对科室下医生质控的病历缺陷计数
                Map<String, Long> totalMap = new HashMap<>();
                Map<String, Long> improveleMap = new HashMap<>();
                List<BehospitalCodeInfo> behospitalCodeInfoList = entryDefectImproveInnerDoctor.getBehospitalCodeInfos();
                //多份病历多次质控评分得到质控缺陷总量、待改善总量
                DataAnalysisFacade.unitProcessing(behospitalCodeInfoList, totalMap, improveleMap);
                //按照全院维度进行数据封装
                for (Map.Entry<String, Long> stringLongEntry : totalMap.entrySet()) {
                    GetEntryDefectImproveDeptDTO getEntryDefectImproveDeptDTO = new GetEntryDefectImproveDeptDTO();
                    getEntryDefectImproveDeptDTO.setDeptId(entryDefectImproveInnerExport.getDeptId());
                    getEntryDefectImproveDeptDTO.setDeptName(entryDefectImproveInnerExport.getDeptName());
                    getEntryDefectImproveDeptDTO.setDoctorId(entryDefectImproveInnerDoctor.getDoctorId());
                    getEntryDefectImproveDeptDTO.setDoctorName(entryDefectImproveInnerDoctor.getDoctorName());
                    getEntryDefectImproveDeptDTO.setEntryId(stringLongEntry.getKey());
                    getEntryInfoByDept(entryInfo, stringLongEntry, getEntryDefectImproveDeptDTO);
                    getEntryDefectImproveDeptDTO.setTotalNum(stringLongEntry.getValue());
                    if (improveleMap.containsKey(stringLongEntry.getKey())) {
                        getEntryDefectImproveDeptDTO.setImproveleNum(improveleMap.get(stringLongEntry.getKey()));
                    }
                    getEntryDefectImproveDeptDTO.setHandleNum(getEntryDefectImproveDeptDTO.getTotalNum() - getEntryDefectImproveDeptDTO.getImproveleNum());
                    double handleRatio = 0d;
                    if(getEntryDefectImproveDeptDTO.getTotalNum()!=0 && getEntryDefectImproveDeptDTO.getHandleNum()!=0){
                        handleRatio = getEntryDefectImproveDeptDTO.getHandleNum().doubleValue()*100/getEntryDefectImproveDeptDTO.getTotalNum().doubleValue();
                        String handleStr = df.format(handleRatio)+"%";
                        getEntryDefectImproveDeptDTO.setHandleStr(handleStr);
                    }
                    getEntryDefectImproveDeptDTOList.add(getEntryDefectImproveDeptDTO);
                }
            }
        }
        //(部分模糊查询在此)
        if (ListUtil.isNotEmpty(getEntryDefectImproveDeptDTOList)) {
            if (StringUtils.isNotBlank(getEntryDefectImproveDeptVO.getCasesName()) || StringUtils.isNotBlank(getEntryDefectImproveDeptVO.getEntryName())) {
                getEntryDefectImproveQueryDept(getEntryDefectImproveDeptVO, getEntryDefectImproveDeptDTOList);
            }
        }

        //导出操作
        if (getEntryDefectImproveDeptVO.getExportType() == 1L) {
            size = getEntryDefectImproveDeptDTOList.size();
        }
        page.setSize(size);
        page.setTotal(getEntryDefectImproveDeptDTOList.size());
        page.setCurrent(current);
        //排序操作
        if (ListUtil.isNotEmpty(getEntryDefectImproveDeptDTOList)) {
            getEntryDefectImproveDeptDTOList = sortEntryDefectListByDdept(getEntryDefectImproveDeptDTOList, getEntryDefectImproveDeptVO);
        }
        //分页操作
        List<GetEntryDefectImproveDeptDTO> getEntryDefectImproveDeptDTOS = DataAnalysisFacade.page(getEntryDefectImproveDeptDTOList, size, current);
        page.setRecords(getEntryDefectImproveDeptDTOS);
        return page;
    }

    public void getEntryDefectImproveQueryDept(GetEntryDefectImproveDeptVO getEntryDefectImproveDeptVO, List<GetEntryDefectImproveDeptDTO> getEntryDefectImproveDeptDTOList) {

        Iterator<GetEntryDefectImproveDeptDTO> iterator = getEntryDefectImproveDeptDTOList.iterator();
        while (iterator.hasNext()) {
            boolean mark = true;
            GetEntryDefectImproveDeptDTO kfc = iterator.next();
            if (StringUtils.isNotBlank(getEntryDefectImproveDeptVO.getCasesName()) &&
                    !kfc.getCasesName().contains(getEntryDefectImproveDeptVO.getCasesName())) {
                iterator.remove();
                mark = false;
            }
            if (mark && StringUtils.isNotBlank(getEntryDefectImproveDeptVO.getEntryName()) &&
                    !kfc.getEntryName().contains(getEntryDefectImproveDeptVO.getEntryName())) {
                iterator.remove();
            }
        }
    }

    public void getEntryDefectImproveByDeptExport(HttpServletResponse response, GetEntryDefectImproveDeptVO getEntryDefectImproveDeptVO) {
        getEntryDefectImproveDeptVO.setCurrent(1L);
        getEntryDefectImproveDeptVO.setSize(Long.MAX_VALUE);
        getEntryDefectImproveDeptVO.setSearchCount(false);
        getEntryDefectImproveDeptVO.setExportType(1L);
        IPage<GetEntryDefectImproveDeptDTO> page = getEntryDefectImproveDept(getEntryDefectImproveDeptVO);
        String fileName = "条目缺陷改善统计(科室).xls";
        ExcelUtils.exportExcel(page.getRecords(), null, "sheet1", GetEntryDefectImproveDeptDTO.class, fileName, response, 12.8f);
    }

    private void entryDefectDeptSet(GetEntryDefectImproveDeptVO getEntryDefectImproveDeptVO) {
        if(StringUtils.isBlank(getEntryDefectImproveDeptVO.getDeptName())){
            getEntryDefectImproveDeptVO.setDeptName("--");
        }
        getEntryDefectImproveDeptVO.setCurrent(1L);
        getEntryDefectImproveDeptVO.setSize(Long.MAX_VALUE);
        //入参验证
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date startDate = null;
        Date endDate = null;
        try {
            startDate = simpleDateFormat.parse(getEntryDefectImproveDeptVO.getStartDate());
            endDate = simpleDateFormat.parse(getEntryDefectImproveDeptVO.getEndDate());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (DateUtil.after(startDate, endDate)) {
            throw new CommonException(CommonErrorCode.PARAM_IS_ERROR, "开始时间必须小于结束时间！");
        }
        getEntryDefectImproveDeptVO.setHospitalId(Long.parseLong(SysUserUtils.getCurrentHospitalID()));
    }

    public List<GetEntryDefectImproveDeptDTO> sortEntryDefectListByDdept(List<GetEntryDefectImproveDeptDTO> getEntryDefectImproveDeptDTOS, GetEntryDefectImproveDeptVO getEntryDefectImproveDeptVO) {
        if (StringUtils.isNotBlank(getEntryDefectImproveDeptVO.getAsc())) {
            if ("totalNum".equals(getEntryDefectImproveDeptVO.getAsc())) {
                getEntryDefectImproveDeptDTOS = getEntryDefectImproveDeptDTOS.stream().sorted(Comparator.comparing(GetEntryDefectImproveDeptDTO::getTotalNum)).collect(Collectors.toList());

            }
            if ("handleNum".equals(getEntryDefectImproveDeptVO.getAsc())) {
                getEntryDefectImproveDeptDTOS = getEntryDefectImproveDeptDTOS.stream().sorted(Comparator.comparing(GetEntryDefectImproveDeptDTO::getHandleNum)).collect(Collectors.toList());

            }
            if ("improveleNum".equals(getEntryDefectImproveDeptVO.getAsc())) {
                getEntryDefectImproveDeptDTOS = getEntryDefectImproveDeptDTOS.stream().sorted(Comparator.comparing(GetEntryDefectImproveDeptDTO::getImproveleNum)).collect(Collectors.toList());
            }
        }

        if (StringUtils.isNotBlank(getEntryDefectImproveDeptVO.getDesc())) {
            if ("totalNum".equals(getEntryDefectImproveDeptVO.getDesc())) {
                getEntryDefectImproveDeptDTOS = getEntryDefectImproveDeptDTOS.stream().sorted(Comparator.comparing(GetEntryDefectImproveDeptDTO::getTotalNum).reversed()).collect(Collectors.toList());

            }
            if ("handleNum".equals(getEntryDefectImproveDeptVO.getDesc())) {
                getEntryDefectImproveDeptDTOS = getEntryDefectImproveDeptDTOS.stream().sorted(Comparator.comparing(GetEntryDefectImproveDeptDTO::getHandleNum).reversed()).collect(Collectors.toList());

            }
            if ("improveleNum".equals(getEntryDefectImproveDeptVO.getDesc())) {
                getEntryDefectImproveDeptDTOS = getEntryDefectImproveDeptDTOS.stream().sorted(Comparator.comparing(GetEntryDefectImproveDeptDTO::getImproveleNum).reversed()).collect(Collectors.toList());
            }
        }
        return getEntryDefectImproveDeptDTOS;
    }

    /**
     * @Description: 缺陷信息封装
     * @Param: [entryInfo, stringLongEntry, getEntryDefectImprove]
     * @return: com.diagbot.dto.GetEntryDefectImproveDTO
     * @Author: cy
     * @Date: 2021/12/3
     */
    public GetEntryDefectImproveDeptDTO getEntryInfoByDept(List<GetEntryInfoDTO> entryInfo, Map.Entry<String, Long> stringLongEntry,
                                                           GetEntryDefectImproveDeptDTO getEntryDefectImproveDeptDTO) {
        entryInfo.parallelStream().filter(kfc -> kfc.getEntryId().equals(stringLongEntry.getKey())).forEach(
                obj -> {
                    getEntryDefectImproveDeptDTO.setCasesId(obj.getCasesId());
                    getEntryDefectImproveDeptDTO.setCasesName(obj.getCasesName());
                    getEntryDefectImproveDeptDTO.setEntryName(obj.getEntryName());
                }
        );
        return getEntryDefectImproveDeptDTO;
    }
}
