package org.springblade.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springblade.system.mapper.DataSyncRecordMapper;
import org.springblade.system.pojo.entity.DataSyncRecord;
import org.springblade.system.pojo.enums.DataSync;
import org.springblade.system.service.IDataSyncRecordService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 数据同步记录表 服务实现类
 *
 * @author BladeX
 * @since 2024-09-27
 */
@Service
public class DataSyncRecordServiceImpl extends ServiceImpl<DataSyncRecordMapper, DataSyncRecord> implements IDataSyncRecordService {

	@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
	@Override
	public void saveWithNewTransaction(DataSyncRecord entity) {
		this.save(entity);
	}

	@Override
	public DataSyncRecord getLastSuccessRecord(DataSyncRecord param) {
		// 根据系统编码，数据类型，模式 查询最新一条成功的记录
		return this.getOne(Wrappers.<DataSyncRecord>lambdaQuery()
				.eq(DataSyncRecord::getSystemCode, param.getSystemCode())
				.eq(DataSyncRecord::getDataType, param.getDataType())
				.eq(DataSyncRecord::getMode, param.getMode())
				// 只查成功的
				.eq(DataSyncRecord::getResult, DataSync.Result.SUCCESS.name())
				// 同步时间倒序排列
				.orderByDesc(DataSyncRecord::getSyncTime)
				.last("limit 1")
		);
	}
}
