package com.njzscloud.common.sn.support;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.njzscloud.common.core.ex.Exceptions;
import com.njzscloud.common.sn.contant.SnSection;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;

import java.util.Date;
import java.util.Map;

@Getter
@Setter
@ToString
@Accessors(chain = true)
public class TimeSectionConfig implements SectionConfig {
    private final SnSection sectionName = SnSection.ShiJian;
    /**
     * 时间格式
     */
    private String pattern;
    /**
     * 是否返回时间戳
     */
    private Boolean timestamp;
    /**
     * 时间单位，1 --> 毫秒，1000-->秒，60000 --> 分，3600000 --> 时，86400000 --> 天
     */
    private Integer unit;

    @Override
    public String genExample() {
        return timestamp ? new Date().getTime() / unit + "" : DateUtil.format(new Date(), pattern);
    }

    @Override
    public ISnSection section() {
        return new TimeSection(pattern, timestamp, unit);
    }

    @Override
    public void resolve(Map<String, Object> config) {
        pattern = MapUtil.getStr(config, "pattern");
        timestamp = MapUtil.getBool(config, "timestamp", false);
        unit = MapUtil.getInt(config, "unit");
        if (timestamp) {
            Assert.isTrue(unit != null && (unit == 1 || unit == 1000 || unit == 60000 || unit == 3600000 || unit == 86400000), () -> Exceptions.clierr("时间编码配置错误，字段 unit 只能为 1,1000,60000,3600000,86400000 中的一个"));
            Assert.isTrue(StrUtil.isBlank(pattern), () -> Exceptions.clierr("时间编码配置错误，字段 pattern 与 timestamp 不能同时使用"));

        } else {
            Assert.notBlank(pattern, () -> Exceptions.clierr("时间编码配置错误，未设置字段 pattern"));
            Assert.isTrue(unit == null, () -> Exceptions.clierr("时间编码配置错误，字段 unit 与 pattern 不能同时使用"));
        }
    }
}
