<template>
  <div class="deviceUpgrade">
    <div class="version">
      <a-badge v-if="otaList && otaList.length" dot title="有新版本">
        {{ currentVersion }}
      </a-badge>
      <template v-else> {{ currentVersion }}</template>
    </div>
    <div v-if="otaList && otaList.length" class="action">
      <a-select
        v-model:value="selectValue"
        placeholder="请选择"
        style="width: 100px"
        size="small"
        :options="otaList"
      />

      <a-button type="link" size="small" :disabled="!selectValue" @click="upgradeHandler"
        >升级</a-button
      >
    </div>
    <div v-else>
      <a-tag :bordered="false" color="green">已是最新版</a-tag>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import * as deviceApi from '@/api/device'
import { filterAndSortOtaList } from '@/utils/ota'

defineOptions({
  name: 'DeviceUpgrade',
})

const emit = defineEmits(['success'])
const props = withDefaults(
  defineProps<{
    version: string
    clintId: string
  }>(),
  {
    version: '',
    clintId: '',
  }
)

const selectValue = ref<string | undefined>(undefined)
const currentVersion = ref<string>(props.version)
const otaList = ref<{ label: string; value: string }[]>([])

const fetchOTAList = async (): Promise<void> => {
  try {
    const resp = await deviceApi.getOtaList()
    if (Array.isArray(resp?.data)) {
      otaList.value = filterAndSortOtaList(resp.data, currentVersion.value).map((item) => ({
        label: item.label,
        value: item.value,
      }))
    } else {
      otaList.value = []
    }
  } catch (err) {
    console.error('获取 OTA 列表失败', err)
    otaList.value = []
  }
}
fetchOTAList()

watch(
  () => props.version,
  (newVersion) => {
    currentVersion.value = newVersion
    fetchOTAList()
  },
  {
    immediate: true,
  }
)

const upgradeHandler = async (): Promise<void> => {
  if (!selectValue.value) return
  try {
    const payload = { clientIds: [props.clintId], ossUrl: selectValue.value }
    await deviceApi.updateOta(payload)
    emit('success')
  } catch (err) {
    console.error('升级失败', err)
  }
}
</script>

<style scoped lang="less">
.deviceUpgrade {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .version {
    font-size: 14px;
  }
  .action {
    display: flex;
    align-items: center;
    gap: 5px;
  }
}
</style>
