
// 匹配第一个出现的数字版本号
function extractVersionNum(str) {
  const match = str.match(/(\d+\.\d+(?:\.\d+)?)/);
  return match ? match[1] : '0.0.0';
}

function compareVersion(v1, v2) {
  v1 = extractVersionNum(v1).split('.').map(Number);
  v2 = extractVersionNum(v2).split('.').map(Number);
  for (let i = 0; i < Math.max(v1.length, v2.length); i++) {
    const n1 = v1[i] || 0;
    const n2 = v2[i] || 0;
    if (n1 > n2) return 1;
    if (n1 < n2) return -1;
  }
  return 0;
}

function clearIgnoredVersion() {
  uni.removeStorageSync('ignoredVersion');
  console.log('已清除忽略的版本设置');
}

function getIgnoredVersion() {
  return uni.getStorageSync('ignoredVersion');
}

function setIgnoredVersion(version) {
  uni.setStorageSync('ignoredVersion', version);
  console.log('已设置忽略版本:', version);
}

function checkVersionCompatibility(wgtVersion, baseVersion) {
  console.log('检查版本兼容性:', { wgtVersion, baseVersion });
  const wgtMajor = extractVersionNum(wgtVersion).split('.')[0];
  const baseMajor = extractVersionNum(baseVersion).split('.')[0];
  if (wgtMajor !== baseMajor) {
    console.warn('主版本号不匹配:', { wgtMajor, baseMajor });
    return false;
  }
  if (compareVersion(wgtVersion, baseVersion) <= 0) {
    console.warn('wgt版本不高于基座版本');
    return false;
  }
  return true;
}

function checkStorageSpace() {
  return new Promise((resolve, reject) => {
    // #ifdef APP-PLUS
    if (typeof plus !== 'undefined' && plus.io) {
      plus.io.requestFileSystem(plus.io.PRIVATE_DOC, (fs) => {
        fs.root.getDirectory('temp', { create: true }, (dir) => {
          resolve(true);
        }, (error) => {
          console.error('检查存储空间失败:', error);
          reject(error);
        });
      });
    } else {
      resolve(true);
    }
    // #endif
    // #ifndef APP-PLUS
    resolve(true);
    // #endif
  });
}

function checkUpdate(forceCheck = false) {
  const localVersion = plus.runtime.version;
	
  const localWgtVersion = uni.getStorageSync('wgtVersion') || localVersion;
	console.log(plus.runtime.version, localWgtVersion)
  uni.request({
    url: 'http://49.232.154.205:10900/fadapp-update/version.json?t=' + Date.now(),
    success: (res) => {
      const remoteVersion = res.data.version;
      const wgtUrl = res.data.wgtUrl;
      const currentVersion = compareVersion(localWgtVersion, localVersion) > 0 ? localWgtVersion : localVersion;
      console.log('本地基座版本:', localVersion, '本地wgt版本:', localWgtVersion, '当前对比版本:', currentVersion, '远程版本:', remoteVersion);
      if (compareVersion(remoteVersion, currentVersion) > 0) {
        if (!checkVersionCompatibility(remoteVersion, localVersion)) {
          console.warn('版本不兼容，跳转到浏览器下载新版安装包');
          uni.showModal({
            title: '版本不兼容',
            content: `新版本 ${remoteVersion} 与当前基座版本 ${localVersion} 不兼容，请前往官网下载最新安装包。`,
            showCancel: true,
            confirmText: '去下载',
            cancelText: '取消',
            success: (res) => {
              if (res.confirm) {
								const v = remoteVersion.split(' ')[1]
                const downloadUrl = `http://49.232.154.205:10900/fadapp-update/fad.apk`;
                // #ifdef APP-PLUS
                plus.runtime.openURL(downloadUrl);
                // #endif
                // #ifndef APP-PLUS
                window.open(downloadUrl, '_blank');
                // #endif
              }
            }
          });
          return;
        }
        const ignoredVersion = uni.getStorageSync('ignoredVersion');
        if (!forceCheck && ignoredVersion === remoteVersion) {
          console.log('用户已选择忽略此版本:', remoteVersion);
          return;
        }
        uni.showModal({
          title: '发现新版本',
          content: `检测到新版本（${remoteVersion}），是否立即下载并更新？`,
          confirmText: '立即更新',
          cancelText: '暂不更新',
          showCancel: true,
          success: (modalRes) => {
            if (modalRes.confirm) {
              checkStorageSpace().then(() => {
                uni.showLoading({title: '正在下载更新包...'});
                console.log('开始下载wgt包:', wgtUrl);
                uni.downloadFile({
                  url: wgtUrl,
                  success: (downloadResult) => {
                    uni.hideLoading();
                    console.log('下载结果:', downloadResult);
                    if (downloadResult.statusCode === 200) {
                      console.log('开始安装wgt包:', downloadResult.tempFilePath);
                      plus.io.resolveLocalFileSystemURL(downloadResult.tempFilePath, (entry) => {
                        console.log('文件存在，开始安装');
                        plus.runtime.install(downloadResult.tempFilePath, {force: true}, function() {
                          console.log('wgt包安装成功');
                          uni.setStorageSync('wgtVersion', remoteVersion);
                          uni.showModal({
                            title: '更新完成',
                            content: '应用需要重启才能生效，是否立即重启？',
                            success: function (res) {
                              if (res.confirm) {
                                plus.runtime.restart();
                              }
                            }
                          });
                        }, function(e) {
                          console.error('wgt包安装失败:', e);
                          let errorMsg = '安装失败';
                          if (e && e.message) {
                            errorMsg += ': ' + e.message;
                          }
                          if (e && e.code) {
                            errorMsg += ' (错误代码: ' + e.code + ')';
                          }
                          uni.showModal({
                            title: '安装失败',
                            content: errorMsg + '\n\n可能的原因：\n1. 版本不兼容\n2. 文件损坏\n3. 权限不足\n4. 存储空间不足',
                            showCancel: false,
                            confirmText: '确定'
                          });
                        });
                      }, (error) => {
                        console.error('文件不存在:', error);
                        uni.showModal({
                          title: '安装失败',
                          content: '下载的文件不存在或已损坏',
                          showCancel: false,
                          confirmText: '确定'
                        });
                      });
                    } else {
                      console.error('下载失败，状态码:', downloadResult.statusCode);
                      uni.showModal({
                        title: '下载失败',
                        content: `服务器返回错误，状态码: ${downloadResult.statusCode}`,
                        showCancel: false,
                        confirmText: '确定'
                      });
                    }
                  },
                  fail: (error) => {
                    uni.hideLoading();
                    console.error('下载失败:', error);
                    uni.showModal({
                      title: '下载失败',
                      content: '网络连接异常，请检查网络后重试',
                      showCancel: false,
                      confirmText: '确定'
                    });
                  }
                });
              }).catch((error) => {
                console.error('存储空间检查失败:', error);
                uni.showModal({
                  title: '存储空间不足',
                  content: '设备存储空间不足，无法下载更新包',
                  showCancel: false,
                  confirmText: '确定'
                });
              });
            } else {
              uni.showModal({
                title: '忽略更新',
                content: `是否忽略版本 ${remoteVersion}？忽略后下次启动时将不再提示此版本更新。`,
                confirmText: '忽略此版本',
                cancelText: '下次提醒',
                success: (ignoreRes) => {
                  if (ignoreRes.confirm) {
                    uni.setStorageSync('ignoredVersion', remoteVersion);
                    uni.showToast({title: '已忽略此版本更新'});
                  }
                }
              });
            }
          }
        });
      } else {
        console.log('当前已是最新版本');
      }
    },
    fail: (error) => {
      console.error('检查更新失败:', error);
      uni.showToast({title: '网络异常，请稍后重试'});
    }
  });
}

export default {
  checkUpdate,
  clearIgnoredVersion,
  getIgnoredVersion,
  setIgnoredVersion,
  checkVersionCompatibility,
  checkStorageSpace,
  compareVersion,
  extractVersionNum
};
