package com.bcxin.autodownloadupload.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bcxin.autodownloadupload.configs.PullConfig;
import com.bcxin.autodownloadupload.dao.mapper.PullRecordMapper;
import com.bcxin.autodownloadupload.dtos.ChangeLogsRequestDto;
import com.bcxin.autodownloadupload.entity.PullRecord;
import com.bcxin.autodownloadupload.service.PullRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

/**
 * description: 拉取记录表service
 * author: linchunpeng
 * date:  2023-04-19 14:08
 */
@Slf4j
@Service
public class PullRecordServiceImpl extends ServiceImpl<PullRecordMapper, PullRecord> implements PullRecordService {


    /**
     * description: 新增拉取记录
     * author: linchunpeng
     * date:  2023-04-21 10:27
     */
    @Override
    public PullRecord createRecord(Long autoFerryTaskId, PullConfig pullConfig, ChangeLogsRequestDto requestDto, int pullType, String regionCode) {
        PullRecord record = new PullRecord();
        if (autoFerryTaskId != null) {
            record.setId(autoFerryTaskId);
        }
        record.setRequestApi(pullConfig.getApi());
        record.setRegionCode(regionCode);
        record.setStartTime(requestDto.getFromTime());
        record.setEndTime(requestDto.getEndTime());
        if (CollectionUtil.isNotEmpty(requestDto.getTables())) {
            record.setTables(String.join(";", requestDto.getTables()));
        }
        record.setRemoveRepeat(requestDto.getIsRemoveRepeat());
        record.setPullType(pullType);
        record.setCreateTime(new Date());
        this.save(record);
        return record;
    }

    /**
     * description: 根据requestId查询拉取记录
     * author: linchunpeng
     * date:  2023-04-25 9:43
     */
    @Override
    public PullRecord getByRequestId(String requestId) {
        QueryWrapper<PullRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("request_id", requestId);

        List<PullRecord> list = this.list(queryWrapper);
        if (CollectionUtil.isEmpty(list)) {
            return null;
        }
        return list.get(list.size()-1);
    }
}
