package com.diagbot.facade;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.diagbot.dto.GetEntryDefectImproveDeptDTO;
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.SysUserUtils;
import com.diagbot.vo.GetEntryDefectImproveDeptVO;
import com.diagbot.vo.GetEntryDefectImproveVO;
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;


/**
 * @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) {
        GetEntryDefectImproveVO getEntryDefectImproveVO = new GetEntryDefectImproveVO();
        BeanUtil.copyProperties(getEntryDefectImproveDeptVO,getEntryDefectImproveVO);
        entryDefectSet(getEntryDefectImproveVO);
        IPage<GetEntryDefectImproveDeptDTO> records = medClickInfoService.getBaseMapper().getEntryDefectImproveDept(getEntryDefectImproveDeptVO);
        return records;
    }

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

    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()));
    }
}
