<template>
  <el-container>
    <el-dialog v-model="updateVisible" :close-on-click-modal="false" :title="$t('header.softwareDownload')">
        <div class="desc line-30 fs-16">{{updateResult.desc}}</div>
    </el-dialog>

    <el-dialog v-model="detailVisible" :title="$t('ota.versionDetail')" width="600px">
        <div v-html="currentVersionDetail" class="version-detail-content te-l"></div>
    </el-dialog>

    <el-main>
      <div class="version-check-container">
        <el-card class="current-version-card fs-14 te-l">
          <p>{{ $t('ota.currentVersion') }}<span class="fs-14"> {{ currentVersion }}</span></p>
          <div class="flex left">
            <p >{{ $t('ota.status') }} <span :class="{ 'text-green': isLatest, 'text-red': !isLatest }">{{ isLatest ? $t('ota.latest') : $t('ota.newVersion') }}</span></p>
            <p class="mar-left-10" v-if="!isLatest"> {{ latest.version }}</p>
            <el-button v-if="!isLatest" class="mar-left-20" type="primary" @click="downloadUpdate">{{ $t('ota.downloadUpdate') }}</el-button>
          </div>
          <p>{{ $t('ota.changelog') }}</p>
          <div v-html="latest.detail"></div>
        </el-card>

        <el-card class="history-versions-card mar-top-10">
          <h3>{{ $t('ota.historyVersions') }}</h3>
          <el-table :data="paginatedVersions" border>
            <el-table-column prop="version" :label="$t('ota.versionNumber')" width="70"></el-table-column>
            <el-table-column prop="release_date" :label="$t('ota.releaseDate')" width="100">
              <template #default="{ row }">{{row.release_date.substr(0,10)}}</template>
            </el-table-column>
            <el-table-column :label="$t('ota.description')">
              <template #default="{ row }">{{row.overview}}</template>
            </el-table-column>
            <el-table-column :label="$t('ota.operation')" width="180">
              <template #default="{ row }">
                  <el-button style="width: 70px;" size="small" @click="downloadSpecificVersion(row.attachment)">{{ $t('common.download') }}</el-button>
                  <el-button style="width: 70px;"  size="small" type="info" @click="showDetail(row)">{{ $t('ota.versionDetail') }}</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination layout="prev, pager, next" :total="totalItems" :page-size="pageSize" v-model:current-page="currentPage" @current-change="handlePageChange" style="margin-top: 15px;" />
        </el-card>
      </div>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElMessage } from 'element-plus';
import client from "@/stores/modules/client";
import icpList from '@/utils/ipc';
import UpdateDialog from '@/components/UpdateDialog'
import { getVersionByRoleType } from '@/apis/other'

const { t } = useI18n()
const currentVersion = ref('0.0.0');
const latest = ref({});
const isLatest = ref(true);
const versions = ref([]);
const currentPage = ref(1);
const pageSize = ref(20);
const totalItems = ref(0);

const paginatedVersions = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  return (versions.value || []).slice(start, start + pageSize.value);
});

const fetchVersions = async () => {
  try {
    const { data } = await getVersionByRoleType({ role_type: 6 })
    versions.value = data;
    if (data.length > 0) {
      latest.value = data[0];
      isLatest.value = compareVersions(currentVersion.value, latest.value.version) >= 0;
    }
    totalItems.value = versions.value.length;
  } catch (error) {
    ElMessage.error(t('ota.downloadFailed'));
  }
};

const compareVersions = (v1, v2) => {
  const parts1 = v1.split('.').map(Number); const parts2 = v2.split('.').map(Number);
  for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
    const num1 = parts1[i] || 0; const num2 = parts2[i] || 0;
    if (num1 > num2) return 1; if (num1 < num2) return -1;
  }
  return 0;
};

const downloadUpdate = () => { downloadSpecificVersion(versions.value[0].attachment) };
const updateVisible = ref(false)
const updateResult = ref({})
const detailVisible = ref(false)
const currentVersionDetail = ref('')

const clientStore = client();

const downloadSpecificVersion = (url) => {
  const urlWithTimestamp = url + (url.includes('?') ? '&' : '?') + '_t=' + new Date().getTime();
  clientStore.ipc.removeAllListeners('app.updater');
  clientStore.ipc.removeAllListeners(icpList.ota.updateVersion);
  clientStore.ipc.send(icpList.ota.updateVersion, urlWithTimestamp);
  clientStore.ipc.on('app.updater', async (event, result) => {
    try {
      let res = JSON.parse(result)
      if([1,3,4].includes(res.status)){ updateResult.value = res; updateVisible.value = true }
      else { updateVisible.value = false; ElMessage.error(t('ota.downloadFailed')) }
    }catch (e) {}
  });
};

const handlePageChange = (page) => { currentPage.value = page; };
const showDetail = (row) => { currentVersionDetail.value = row.detail || t('ota.noDetail'); detailVisible.value = true; };

onMounted(async () => {
  currentVersion.value = '1.0.0' // version from package.json
  fetchVersions();
});
</script>

<style scoped>
.version-detail-content { max-height: 400px; overflow-y: auto; line-height: 1.6; }
</style>
