package com.bcxin.autodownloadupload.configs;

import cn.hutool.core.bean.BeanUtil;
import com.bcxin.autodownloadupload.common.utils.DateUtil;
import com.bcxin.autodownloadupload.dtos.ChangeLogsRequestDto;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

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

@Data
@Component
@ConfigurationProperties(prefix = "pull-config")
public class PullConfig {

    //生成sql文件和txt文件的api地址
    private String api;

    //OBS域名
    private String obsUrl;

    //拉取表格配置，放空表示拉取全部
    private String fileSqlCount;

    //从V5下载拉取zip存放地址
    private String v5Path;

    //下载文件是否进行数据库去重
    private Boolean isRemoveRepeat;

    //生成完整zip包存放地址，zip包名称为：V5的拉取id
    private String completedPath;

    //调度任务配置
    private Scheduled scheduled;

    //数据库配置
    private DatasourceConfig datasource;


    //调度任务配置
    @Data
    public static class Scheduled{

        //拉取时间范围配置
        private TimeRange timeRange;

        //目标系统配置
        private String regionCodes;

        //拉取表格配置，放空表示拉取全部
        private List<String> tables;

    }

    //拉取时间范围配置
    @Data
    public static class TimeRange{
        //周一凌晨，拉取前3天的数据，周六周天的凌晨，不进行拉取，其他时间拉取前1天的数据
        private int monday;
        private int tuesday;
        private int wednesday;
        private int thursday;
        private int friday;
        private int saturday;
        private int sunday;
    }

    //datasource配置
    @Data
    public static class DatasourceConfig{
        private String url;
        private String username;
        private String password;
    }

    /**
     * description: 根据配置，获取请求拉取变更记录的对象dto
     * author: linchunpeng
     * date:  2023-04-18 11:15
     */
    public ChangeLogsRequestDto getChangeLogsRequestDto() {
        //根据timeRange生成每次拉取的开始时间和结束时间
        Date now = new Date();
        String week = DateUtil.getWeekEngStrOfDate(now);
        //拉取范围配置
        Map<String, Object> timeRangeMap = BeanUtil.beanToMap(this.getScheduled().getTimeRange());
        //取出时间范围
        int range = Integer.parseInt(timeRangeMap.get(week).toString());
        if (range != 0) {
            ChangeLogsRequestDto dto = new ChangeLogsRequestDto();
            dto.setFromTime(DateUtil.getBeforeNumDayZeroTime(now, range));
            dto.setEndTime(DateUtil.getDateZeroTime(now));
            dto.setRegionCodes(this.getScheduled().getRegionCodes());
            dto.setTables(this.getScheduled().getTables());
            dto.setIsRemoveRepeat(this.getIsRemoveRepeat());
            return dto;
        }
        return null;
    }
}
