package thyyxxk.webserver.service.jimubaobiao;

import com.baomidou.dynamic.datasource.annotation.DS;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.dao.his.jimubaobiao.JiMuBaoBiaoDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.querydata.BaoBiaoChaXun;
import thyyxxk.webserver.utils.ResultVoUtil;
import thyyxxk.webserver.utils.StringUtil;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 描述： 积木报表
 * </p>
 *
 * @author xc
 * @date 2021-09-02 10:21
 */
@Service
@Slf4j
@DS("jimu")
public class JiMuBaoBiaoService {

    private final JiMuBaoBiaoDao dao;

    public JiMuBaoBiaoService(JiMuBaoBiaoDao dao) {
        this.dao = dao;
    }


    /**
     * 住院超 30 天
     *
     * @return 返回积木报表链接
     */
    public ResultVo<Map<String, List<BaoBiaoChaXun>>> zhuYuanShiJianChao(String startTime, String endTime) {
        if (StringUtil.isBlank(startTime) || StringUtil.isBlank(endTime)) {
            return ResultVoUtil.fail(ExceptionEnum.NULL_POINTER);
        }
        Map<String, List<BaoBiaoChaXun>> map = new HashMap<>();
        map.put("huanZheChao30", dao.huanZheZhuYuanChao(Timestamp.valueOf(startTime), Timestamp.valueOf(endTime)));

        List<BigDecimal> huanZheZhuYuanTianShu = dao.huanZheRuYuanJianGe(Timestamp.valueOf(startTime), Timestamp.valueOf(endTime));
        // 患者的全部住院天数
        BigDecimal sum = new BigDecimal(0);
        for (BigDecimal integer : huanZheZhuYuanTianShu) {
            sum = sum.add(integer);
        }
        // 患者总人数 totalNumberOfPatients
        BigDecimal huanZheRenShu = dao.huanZheRenShu(Timestamp.valueOf(startTime), Timestamp.valueOf(endTime));
        // 患者的平均住院天数
        BigDecimal pingJunZhuYuanTianShu = sum.divide(huanZheRenShu, 2, RoundingMode.HALF_UP);
        List<BaoBiaoChaXun> list = new ArrayList<>();
        list.add(new BaoBiaoChaXun("总住院天数", sum, "天"));
        list.add(new BaoBiaoChaXun("患者的总人数", huanZheRenShu, "人"));
        list.add(new BaoBiaoChaXun("平均住院天数", pingJunZhuYuanTianShu, "天"));
        map.put("pingJunZhuYuan", list);

        log.info("开始时间：{}，结束时间：{}", startTime, endTime);
        return ResultVoUtil.success(map);
    }

}
