package com.testor.module.appUpdate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.testor.biz.file.controller.SysFileController;
import com.testor.module.appUpdate.dao.TSysAppPackageDao;
import com.testor.module.appUpdate.model.domain.TSysAppPackage;
import com.testor.module.appUpdate.service.TSysAppPackageService;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.models.supers.SuperServiceImpl;
import com.tongtech.tfw.backend.core.helper.IdHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author rsq
 * @program zlmy_boot
 * @return
 **/
@Service
public class TSysAppPackageServiceImpl extends SuperServiceImpl<TSysAppPackageDao, TSysAppPackage> implements TSysAppPackageService {

    @Autowired
    private SysFileController sysFileController;

    @Override
    public BaseResponse uploadPackage(MultipartFile file, TSysAppPackage tSysAppPackage) {
        BaseResponse baseResponse = new BaseResponse<>();
        if (file.isEmpty()) {
            baseResponse.setData("上传的文件为空");
            return baseResponse;
        }
        String filePath = sysFileController.upload(file).getData().getFilePath();
        tSysAppPackage.setId(IdHelper.getId32bit());
        tSysAppPackage.setUrl(filePath);
        if (isVersionExist(tSysAppPackage.getVersion())) {
            baseResponse.setData("版本号已存在");
            return baseResponse;
        }
        if (!tSysAppPackage.getVersion().matches("^[0-9]+(\\.[0-9]+){0,2}$")) {
            baseResponse.setData("版本号格式不正确");
            return baseResponse;
        }
        TSysAppPackage data = getLatestVersion().getData();
        if (data != null) {
            int comparisonVersion = comparisonVersion(data.getVersion(), tSysAppPackage.getVersion());
            if (comparisonVersion < 0) {
                baseResponse.setData("上传的版本低于当前最高版本,版本号应当大于：" + data.getVersion());
                return baseResponse;
            }
        }
        boolean save = this.save(tSysAppPackage);
        if (save) {
            baseResponse.setData(tSysAppPackage);
            return baseResponse;
        }
        baseResponse.setData("版本号已存在");
        return baseResponse;
    }

    public boolean isVersionExist(String version) {
        QueryWrapper<TSysAppPackage> wrapper = new QueryWrapper<>();
        wrapper.eq("version", version);
        return list(wrapper).size() > 0;
    }

    @Override
    public BaseResponse<TSysAppPackage> getLatestVersion() {
        BaseResponse<TSysAppPackage> baseResponse = new BaseResponse();
        QueryWrapper<TSysAppPackage> wrapper = new QueryWrapper<>();
        // 使用正则表达式替换非数字字符为空格
        wrapper.orderByDesc("version");
        wrapper.last("limit 1");
        TSysAppPackage data = this.getOne(wrapper);
        baseResponse.setData(data);
        return baseResponse;
    }

    @Override
    public BaseResponse getPackageByVersion(String version) {

        return null;
    }


    /**
     * 比较两个 APK 版本号的大小
     *
     * @param oldVersion 旧版本号
     * @param newVersion 新版本号
     * @return 如果新版本号大于旧版本号，返回 1；如果等于，返回 0；否则返回 -1
     */
    public static int comparisonVersion(String oldVersion, String newVersion) {
        if (oldVersion.equals(newVersion)) {
            return 0;
        }
        String[] oldArr = oldVersion.split("\\.");
        String[] newArr = newVersion.split("\\.");
        int i = 0;
        // 获取最小长度值
        int lenOld = oldArr.length;
        int lenNew = newArr.length;
        int minLength = Math.min(lenOld, lenNew);
        int diff = 0;
        // 循环判断每个位的大小
        while (i < minLength && (diff = Integer.parseInt(newArr[i]) - Integer.parseInt(oldArr[i])) == 0) {
            i++;
        }
        if (diff == 0) {
            // 如果位数不一致，则比较多余位数
            for (int j = i; j < lenNew; j++) {
                if (Integer.parseInt(newArr[j]) > 0) {
                    return 1;
                }
            }
            for (int j = i; j < lenOld; j++) {
                if (Integer.parseInt(oldArr[j]) > 0) {
                    return -1;
                }
            }
            return 0;
        } else {
            return diff > 0 ? 1 : -1;
        }
    }
}
