package cn.iocoder.yudao.framework.common.model;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.StrUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.log4j.Log4j2;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 功能描述: 查询封装
 * <p>
 * 作者: July
 * 日期: 2020-09-16 18:22
 * @author Administrator
 */
@Getter
@Setter
@Log4j2
@ToString
public class QueryRequest extends LinkedHashMap<String, Object> {

    private static final long serialVersionUID = -1900853947106880626L;

    public QueryRequest(Map<String, Object> params) {
        this.putAll(params);
        // 处理包含时间范围的参数请求
        handleTimeParams(params);
    }

    public boolean parseBoolean(String value) {
        if (value == null) { return false; }
        return "true".equalsIgnoreCase(value) || "1".equalsIgnoreCase(value);
    }

    public void handleTimeParams(Map<String, Object> params) {
        String sts = (String) params.getOrDefault("sts", "");
        String ets = (String) params.getOrDefault("ets", "");
        if (StrUtil.isBlank(sts) || StrUtil.isBlank(ets)) { return; }

        LocalDateTime sTime = LocalDateTime.parse(sts, DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN));
        LocalDateTime eTime = LocalDateTime.parse(ets, DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN));
        long days = ChronoUnit.DAYS.between(sTime, eTime);

        this.put("sTime", sTime);
        this.put("eTime", eTime);
        this.put("days", days + 1);

        log.debug(String.format("开始时间: %s 结束时间: %s 间隔天数: %s", sts, ets, days));
    }
}
