package org.dromara.system.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.system.domain.SysVersion;
import org.dromara.system.domain.bo.SysVersionBo;
import org.dromara.system.domain.dto.VersionDTO;
import org.dromara.system.domain.vo.SysVersionVo;
import org.dromara.system.mapper.SysVerisonMapper;
import org.dromara.system.service.ISysVerisonService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@RequiredArgsConstructor
@Service
public class SysVerisonServiceImpl extends ServiceImpl<SysVerisonMapper, SysVersion> implements ISysVerisonService {

    private final SysVerisonMapper sysVerisonMapper;

    @Override
    public IPage<SysVersionVo> getList(Page<SysVersion> page, SysVersionBo query) {
        return sysVerisonMapper.getList(page,query);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysVersion updateStatus(Long id, Integer status) {
        // 查询当前版本
        SysVersion sysVersion = sysVerisonMapper.selectById(id);
        if (sysVersion == null) {
            throw new ServiceException("版本不存在");
        }

        if (status == 1) {
            // 禁用同平台其他所有版本
            sysVerisonMapper.disableOtherVersion(sysVersion.getPlatformType(), id);
        }

        //  更新当前版本状态
        sysVersion.setStatus(status);
        sysVerisonMapper.updateById(sysVersion);

        return sysVersion;
    }


    @Override
    public boolean add(SysVersion sysVersion) {
        // 检查是否设置启用状态
        if (sysVersion.getStatus() == 1) {
            // 禁用其他版本
            sysVerisonMapper.disableOtherVersions(sysVersion.getPlatformType());
        }
        return super.save(sysVersion);
    }
}
