<script setup>
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';
import packageJson from '@/../../package.json';
import { ElMessage } from 'element-plus';
import client from "@/stores/modules/client";
import  icpList from '@/utils/ipc'
import socket from "@/stores/modules/socket";
import UpdateDialog from '@/components/UpdateDialog'

const currentVersion = ref(packageJson.version);
const latestVersion = 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;
  const end = start + pageSize.value;
  return (versions.value || []).slice(start, end).reverse();
});

// 获取版本信息
const fetchVersions = async () => {
  try {
    // 添加时间戳避免缓存问题
    const timestamp = new Date().getTime();
    const response = await axios.get('https://ossimg.valimart.net/frontend/html/zhihuiyin/version.json', {
      params: {
        _t: timestamp
      }
    });

    // 确保 response.data 是 JSON 数据
    let data;
    if (typeof response.data === 'string') {
      data = JSON.parse(response.data);
    } else {
      data = response.data;
    }

    versions.value = data;

    if (data.length > 0) {
      const latest = data[data.length - 1];
      latestVersion.value = latest.version;

      // 比较版本号
      isLatest.value = compareVersions(currentVersion.value, latest.version) >= 0;
    }

    // 初始化分页信息
    totalItems.value = versions.value.length;
  } catch (error) {
    console.error('获取版本信息失败:', error);
    ElMessage.error('无法获取版本信息');
  }
};

// 版本号比较函数
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[versions.value.length - 1].url)
};


const updateVisible = ref( false)
const updateResult = ref({})

const clientStore = client();
const socketStore = socket()
// 下载特定版本
const downloadSpecificVersion = (url) => {

  clientStore.ipc.removeAllListeners('app.updater');
  clientStore.ipc.removeAllListeners(icpList.ota.updateVersion);
  clientStore.ipc.send(icpList.ota.updateVersion,url);
  clientStore.ipc.on(icpList.ota.updateVersion, async (event, result) => {
    console.log('==============================')
    console.log('checkUpdate')
    console.log(event)
    console.log(result)

  })

  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
        console.log(updateResult.value)
        console.log(updateVisible.value)
      }else{
        updateVisible.value = false
        ElMessage.error('下载失败')
      }
    }catch (e) {
      console.log(e)
    }


  })



};

// 处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page;
};

onMounted(() => {
  fetchVersions();
});
</script>

<template>
  <el-container>


    <el-dialog
        v-model="updateVisible"
        :close-on-click-modal="false"
        title="软件下载中"
    >
        <div class="desc line-30 fs-16">{{updateResult.desc}}</div>
    </el-dialog>
    <el-main>
      <div class="version-check-container">
        <el-card class="current-version-card">
          <p>当前版本  <span class="fs-14">版本号: {{ currentVersion }}</span></p>

          <p>状态: <span :class="{ 'text-green': isLatest, 'text-red': !isLatest }">{{ isLatest ? '您已经是最新版本' : '发现新版本' }}</span></p>
          <p v-if="!isLatest">新版本: {{ latestVersion }}</p>
          <el-button v-if="!isLatest" type="primary" @click="downloadUpdate" v-log="{ describe: { action: '点击下载最新版本', latestVersion } }">下载更新</el-button>
        </el-card>

        <el-card class="history-versions-card mar-top-10">
          <h3>历史版本</h3>
          <!-- 使用计算属性获取分页数据 -->
          <el-table :data="paginatedVersions" border>
            <el-table-column prop="version" label="版本号" width="70"></el-table-column>
            <el-table-column prop="date" label="发布日期" width="100"></el-table-column>
            <el-table-column label="描述">
              <template #default="{ row }">
                <el-tooltip :content="row.describe" placement="top" :show-when="hover" :width="500">
                  <span class="version-describe" v-html="row.describe"></span>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column label="操作"  width="80">
              <template #default="{ row }">
                <el-button size="small" @click="downloadSpecificVersion(row.url)" v-log="{ describe: { action: '点击下载历史版本', version: row.version, url: row.url } }">下载</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>

<style scoped>
.version-describe {
  display: inline-block;
  width: 100%; /* 根据需要调整 */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
