package com.izouma.nineth.service;

import com.izouma.nineth.domain.Activity;
import com.izouma.nineth.domain.AppVersion;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.enums.UpdateType;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.AppVersionRepo;
import com.izouma.nineth.utils.JpaUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

@Service
@Slf4j
@AllArgsConstructor
public class AppVersionService {
    private AppVersionRepo appVersionRepo;

    public AppVersion save(AppVersion appVersion) {
        if (appVersion.getId() != null){
            AppVersion version = appVersionRepo.findById(appVersion.getId()).orElseThrow(new BusinessException("修改的版本号不存在"));
            version.setPhoneBrand(appVersion.getPhoneBrand());
            version.setTitle(appVersion.getTitle());
            version.setDescription(appVersion.getDescription());
            version.setIpAddress(appVersion.getIpAddress());
            version.setStartUpdate(appVersion.isStartUpdate());
            appVersionRepo.save(version);
        }
        return appVersionRepo.save(appVersion);
    }

    /**
     * 查看列表
     * @param pageQuery
     * @return
     */
    public Page<AppVersion> all(PageQuery pageQuery) {
        return appVersionRepo.findAll(JpaUtils.toSpecification(pageQuery, AppVersion.class), JpaUtils.toPageRequest(pageQuery));
    }

    public AppVersion checkUpdate(String platForm, String appVersion) {
        Long updateId = appVersionRepo.hasNewVersion(platForm, appVersion);
        //如果是最新版本 则直接返回空
        if (updateId == null){
            return null;
        }
        //检查是否需要强更
        updateId = appVersionRepo.strongUpdateVersion(platForm, appVersion);
        if (updateId != null) {
            //查找最后一个安装包 进行更新
            updateId = appVersionRepo.lastUpdateVersion(platForm);
            AppVersion version = appVersionRepo.findById(updateId).get();
            version.setUpdateType(UpdateType.STRONG_UPDATE);
            return version;
        }else {
            //检查最后一个下载安装包的更新版本
            updateId = appVersionRepo.lastUpdateVersion(platForm);
            AppVersion version = null;
            if (updateId != null){
                version = appVersionRepo.findById(updateId).get();
            }
            //如果版本一致检查有无软更
            if (null == version || version.getVersion().equals(appVersion)){
                updateId = appVersionRepo.lastVersion(platForm);
                if (version != null && updateId.equals(version.getId())) {
                    return null;
                }else {
                    return appVersionRepo.findById(updateId).get();
                }
            }
            //否则返回最后一个版本包进行更新
            return version;
        }
    }

    public void softDelete(Long id) {
        appVersionRepo.softDelete(id);
    }
}
