<template>
  <view v-if="visible" class="popup-overlay" @click="handleOverlayClick">
    <view class="popup-overlay__content" @click="handleContentClick">
      <view class="popup-container">
        <image src="/static/popup.png" class="popup-bg-image" mode="aspectFit"></image>

        <view class="popup-content">
          <view class="popup-title">
            <text class="title-text">发现新版本</text>
          </view>

          <view class="info-section">
            <text class="info-text">当前版本：{{ currentVersion }}</text>
            <text class="info-text">最新版本：{{ latestInfo!.versionName }}</text>
            <text class="remark-text">更新说明：</text>
            <text class="remark-text">{{ latestInfo!.remark }}</text>
          </view>

          <view v-if="downloading || installing" class="progress-section">
            <view class="progress-container">
              <view class="progress-bar">
                <view class="progress-inner" :style="{ width: progressPercentStr }"></view>
                <view class="progress-glow" :style="{ width: progressPercentStr }"></view>
              </view>
              <view class="progress-info">
                <text class="progress-text" v-if="!installing">下载中 {{ progress }}%</text>
                <text class="progress-text installing" v-else>正在安装...</text>
                <text class="progress-percent">{{ progressPercentStr }}</text>
              </view>
            </view>
            
            <!-- 下载完成动画效果 -->
            <view v-if="downloadCompleted && !installing" class="download-success">
              <image src="/static/icon_success.png" class="success-icon"></image>
              <text class="success-text">下载完成</text>
            </view>
          </view>

          <view class="btn-group">
            <button class="primary-btn" hover-class="hover_btn" @click="handleUpdate">立即更新</button>
            <!-- <button class="secondary-btn" hover-class="hover_btn" @click="handleClose">暂不更新</button>    -->
          </view>
        </view>
      </view>

      <view class="close-button" @click="handleClose">
        <image src="/static/icon_close.png" class="close-icon"></image>
      </view>
    </view>
  </view>
</template>

<script setup lang="uts">
  type UpgradeInfo = {
    versionName: string
    versionCode: number
    downloadUrl: string
    packageType: string
    remark: string
  }

  // 使用 type 而不是 interface 定义对象类型，且可空类型明确
  type AppUpgradeProps = {
    visible: boolean
    closeOnOverlay?: boolean | null
    // 从父组件传入的版本信息对象，例如 { version: string, download_url: string }
    versionInfo?: UTSJSONObject | null
  }

  type AppUpgradeEmits = {
    (e: 'close'): void
    (e: 'start'): void
    (e: 'downloaded'): void
    (e: 'installed'): void
  }

  const props = withDefaults(defineProps<AppUpgradeProps>(), {
    visible: false,
    closeOnOverlay: false
  })

  const emit = defineEmits<AppUpgradeEmits>()

  const currentVersion = ref<string>('')
  const latestInfo = ref<UpgradeInfo | null>(null)
  const downloading = ref<boolean>(false)
  const progress = ref<number>(0)
  const downloadCompleted = ref<boolean>(false)
  const installing = ref<boolean>(false)

  const progressPercentStr = computed((): string => {
    const p = progress.value
    const clamped = p < 0 ? 0 : (p > 100 ? 100 : p)
    return clamped.toString() + '%'
  })

  // 监听进度变化，当达到100%时自动安装
  watch(progress, (newProgress: number): void => {
    if (newProgress >= 100 && downloading.value && !downloadCompleted.value) {
      downloadCompleted.value = true
      // 延迟一点时间让用户看到100%的进度
      setTimeout(() => {
        if (latestInfo.value?.packageType == 'apk') {
          installing.value = true
        }
      }, 500)
    }
  })

  const readCurrentVersion = (): void => {
    const base = uni.getAppBaseInfo()
    const vName = base.appVersion ?? ''
    currentVersion.value = vName
  }

  const inferPackageType = (url: string): string => {
    const lower = url.toLowerCase()
    if (lower.endsWith('.apk')) {
      return 'apk'
    }
    if (lower.endsWith('.wgt')) {
      return 'wgt'
    }
    return ''
  }

  const parseUpgradeInfo = (obj: UTSJSONObject): UpgradeInfo => {
    // 父组件传入的结构：{ version: string, download_url: string }
    const versionName = obj.getString('version') ?? ''
    const downloadUrl = obj.getString('download_url') ?? ''
    const pkgType = inferPackageType(downloadUrl)
    return {
      versionName: versionName,
      versionCode: 0,
      downloadUrl: downloadUrl,
      packageType: pkgType,
      remark: obj.getString('remark') ?? ''
    }
  }

  // 监听外部传入的版本信息并解析
  const versionInfoRef = computed<UTSJSONObject | null>(() => props.versionInfo ?? null)
  watch(versionInfoRef, (nv: UTSJSONObject | null, _ov: UTSJSONObject | null): void => {
    if (nv != null) {
      latestInfo.value = parseUpgradeInfo(nv)
    } else {
      latestInfo.value = null
    }
  }, { immediate: true })

  const handleClose = (): void => {
    downloading.value = false
    downloadCompleted.value = false
    installing.value = false
    progress.value = 0
    emit('close')
  }

  const handleOverlayClick = (): void => {
    if (props.closeOnOverlay == true) {
      handleClose()
    }
  }

  const handleContentClick = (): void => {
    // 阻止关闭
  }

  const handleUpdate = (): void => {
    const info = latestInfo.value
    if (info == null) {
      uni.showToast({ title: '未获取到版本信息', icon: 'none' })
      return
    }

    if (info.downloadUrl.length == 0) {
      uni.showToast({ title: '无效的下载地址', icon: 'none' })
      return
    }

    emit('start')
    downloading.value = true
    progress.value = 0

    // 仅在 App 平台进行下载与安装
    // #ifdef APP
    const task = uni.downloadFile({
      url: info.downloadUrl,
      success: (res) => {
        emit('downloaded')
        // UTS 强类型：使用UTSJSONObject方式访问属性
		console.log('res',res)
        const fp = res['tempFilePath'] as string ?? ''
        if (fp.length == 0) {
          uni.showToast({ title: '下载文件路径异常', icon: 'none' })
          downloading.value = false
          return
        }

        if (info.packageType == 'apk') {
          // 仅 Android 安装 APK
          // #ifdef APP-ANDROID
          uni.installApk({
            filePath: fp,
            success: (_res: any) => {
              emit('installed')
              downloading.value = false
            },
            fail: (_err: any) => {
              uni.showToast({ title: '安装失败', icon: 'none' })
              downloading.value = false
            },
            complete: (_: any) => {}
          })
          // #endif
          // #ifdef APP-IOS
          uni.showToast({ title: 'iOS 不支持 APK 安装', icon: 'none' })
          downloading.value = false
          // #endif
        } else if (info.packageType == 'wgt') {
          // wgt 热更新在 uni-app x 中更推荐使用官方“App 升级中心”
          uni.showToast({ title: '请接入 App 升级中心以安装 wgt', icon: 'none' })
          downloading.value = false
        } else {
          uni.showToast({ title: '未知的包类型', icon: 'none' })
          downloading.value = false
        }
      },
      fail: (_err: any) => {
        uni.showToast({ title: '下载失败', icon: 'none' })
        downloading.value = false
      }
    })

    // 监听下载进度
    const t = task as DownloadTask
        t.onProgressUpdate((result) => {
			// console.log('result',result)
          // 根据 uni-app x 官方文档，OnProgressDownloadResult 包含 progress 属性
          const p = result.progress
          progress.value = p
        })
    // #endif

    // #ifndef APP
    uni.showToast({ title: '仅 App 平台支持安装', icon: 'none' })
    downloading.value = false
    // #endif
  }

  watch((): boolean => props.visible, (nv: boolean): void => {
    if (nv == true) {
      readCurrentVersion()
    } else {
      downloading.value = false
      downloadCompleted.value = false
      installing.value = false
      progress.value = 0
    }
  })

  onMounted(() => {
    readCurrentVersion()
  })

</script>

<style>
  .popup-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 9999;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .popup-overlay__content {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
  }

  .popup-container {
    width: 498.61rpx;
    min-height: 547.92rpx;
    position: relative;
  }

  .popup-bg-image {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
  }

  .popup-content {
    position: relative;
    z-index: 2;
    width: 100%;
    height: 100%;
  }

  .popup-title {
    margin: 80rpx 0 30rpx 55.56rpx;
  }

  .title-text {
    font-size: 36rpx;
    font-weight: bold;
    color: #21061A;
    line-height: 1.2em;
  }

  .info-section {
    margin: 0 0 20rpx 55.56rpx;
  }
  .info-text {
    font-size: 24rpx;
    color: #000000;
    line-height: 1.4em;
    font-weight: 400;
  }
  
  .remark-text {
    margin-top: 20rpx;
    font-size: 28rpx;
    color: #ffffffff;
    line-height: 1.4em;
    font-weight: 400;
  }

  .progress-section {
    margin: 20rpx 55.56rpx;
    width: 380rpx;
  }

  .progress-container {
    width: 100%;
  }

  .progress-bar {
    width: 100%;
    height: 20rpx;
    background: linear-gradient(90deg, #f0f0f0 0%, #e8e8e8 100%);
    border-radius: 10rpx;
    position: relative;
    overflow: hidden;
    box-shadow: inset 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
  }

  .progress-inner {
    height: 20rpx;
    background: linear-gradient(90deg, #FD3C9F 0%, #FF6B9D 50%, #FCA7D3 100%);
    border-radius: 10rpx;
    width: 0%;
    transition: width 0.3s ease-in-out;
    position: relative;
    z-index: 2;
  }

  .progress-glow {
    position: absolute;
    top: 0;
    left: 0;
    height: 20rpx;
    background: linear-gradient(90deg, rgba(253, 60, 159, 0.3) 0%, rgba(255, 107, 157, 0.3) 50%, rgba(252, 167, 211, 0.3) 100%);
    border-radius: 10rpx;
    width: 0%;
    z-index: 1;
  }

  .progress-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 16rpx;
  }

  .progress-text {
    font-size: 24rpx;
    color: #333333;
    font-weight: bold;
  }

  .progress-text.installing {
    color: #FD3C9F;
    font-weight: bold;
  }

  .progress-percent {
    font-size: 24rpx;
    color: #FD3C9F;
    font-weight: bold;
  }

  .download-success {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 20rpx;
    padding: 16rpx;
    background: rgba(253, 60, 159, 0.1);
    border-radius: 12rpx;
    border: 2rpx solid rgba(253, 60, 159, 0.2);
  }

  .success-icon {
    width: 32rpx;
    height: 32rpx;
    margin-right: 12rpx;
  }

  .success-text {
    font-size: 26rpx;
    color: #FD3C9F;
    font-weight: bold;
  }

  .btn-group {
    display: flex;
    justify-content: flex-start;
    margin: 20rpx 0 0 55rpx;
    flex-direction: row;
  }

  .primary-btn {
    width: 194rpx;
    height: 67rpx;
    background: linear-gradient(to bottom, #FD3C9F, #FCA7D3);
    font-weight: bold;
    font-size: 25rpx;
    color: #000000;
    line-height: 67rpx;
    border-radius: 20rpx;
    border: none;
    margin-right: 16rpx;
  }

  .secondary-btn {
    width: 194rpx;
    height: 67rpx;
    background: #fff5fa;
    font-weight: bold;
    font-size: 25rpx;
    color: #000000;
    line-height: 67rpx;
    border-radius: 20rpx;
    border: none;
  }

  .close-button {
    margin-top: 21rpx;
    width: 48rpx;
    height: 48rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.3);
    border-radius: 25rpx;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .close-icon {
    width: 48rpx;
    height: 48rpx;
  }
</style>