<template>
  <headerBar title="首页">

    <template  #title><div @click="handleSettingClick" v-log="{ describe: { action: '点击首页标题' } }">首页</div></template>
  </headerBar>
  <div class="home-container" v-loading="loading">
    <!-- 背景图片 -->
    <img src="@/assets/images/home/bg.png" alt="背景图片" class="background-image" />

    <!-- 左侧图片区域 -->
    <div class="image-container left-image" @click="goCheck" v-log="{ describe: { action: '点击拍照检查入口' } }">
      <img src="@/assets/images/home/left.jpg" alt="拍摄产品并处理图像" class="zoom-on-hover" />
      <div class="overlay-text">拍摄产品<br>并处理图像</div>
    </div>

    <!-- 右侧图片区域 -->
    <div class="image-container right-image" @click="goShot" v-log="{ describe: { action: '点击仅处理图像入口' } }">
      <img src="@/assets/images/home/right.jpg" alt="仅处理图像" class="zoom-on-hover" />
      <div class="overlay-text" style="line-height: 80px;">仅处理图像</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import headerBar from "@/components/header-bar/index.vue";
import { useRouter } from "vue-router";
import configInfo from '@/stores/modules/config';
import { ref, onMounted } from 'vue';
import axios from 'axios';
import client from "@/stores/modules/client";
import icpList from '@/utils/ipc';
import packageJson from '@/../../package.json';
import { getRouterUrl } from '@/utils/appfun';

const configInfoStore = configInfo();
const router = useRouter();
const loading = ref(true);

// 版本检查相关
const currentVersion = ref(packageJson.version);
const latestVersion = ref('');
const isLatest = ref(true);


import socket from "@/stores/modules/socket";
// 初始化 WebSocket 状态管理
const socketStore = socket();

function socketConnect(){
  socketStore.connectSocket();
}

const goCheck = () => {
  configInfoStore.updateAppModel(1);
  router.push({
    name: 'PhotographyCheck'
  });
};

const goShot = () => {
  socketConnect();
  configInfoStore.updateAppModel(2);
  router.push({
    name: 'PhotographyShot'
  });
};

// 健康检查函数
const checkHealth = async () => {
  try {
    const response = await axios.get('http://127.0.0.1:7074');
    if (response.status === 200) {
      loading.value = false; // 健康检查成功，关闭 loading
    }
  } catch (error) {
    console.error('健康检查失败:', error);
    setTimeout(() => {
      checkHealth(); // 延迟检查
    }, 2000);
    // 可以在这里处理错误，例如显示错误提示
  }
};

const settingClickCount = ref(0);
// 修改headerBar的点击处理函数
function handleSettingClick() {
  console.log('handleSettingClickhandleSettingClick')
  settingClickCount.value++;

  if (settingClickCount.value >= 5) {
    openResourceDirectory()
    settingClickCount.value = 0;
  }

  setTimeout(() => {
    settingClickCount.value = 0;
  }, 3000); // 3秒内未再次点击则重置计数器
}

const clientStore = client();

function openResourceDirectory() {
  clientStore.ipc.removeAllListeners(icpList.utils.shellFun);
  let params = {
    action: 'openPath',
    params: configInfoStore.appConfig.userDataPath.replaceAll('/', '\\')
  };
  clientStore.ipc.send(icpList.utils.shellFun, params);
}

// 版本号比较函数
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;
};

// 打开OTA窗口
const openOTA = () => {
  const { href } = router.resolve({
    name: 'ota'
  });

  clientStore.ipc.removeAllListeners(icpList.utils.openMain);
  let params = {
    title: '版本更新',
    width: 900,
    height: 700,
    frame: true,
    id: 'ota',
    url: getRouterUrl(href)
  };
  clientStore.ipc.send(icpList.utils.openMain, params);
};

// 获取版本信息并检查更新
const checkForUpdates = 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;
    }

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

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

      // 如果发现新版本，自动打开OTA窗口
      if (!isLatest.value) {
        openOTA();
      }
    }
  } catch (error) {
    console.error('检查版本更新失败:', error);
    // 静默处理错误，不影响用户体验
  }
};





// 在组件挂载时执行健康检查和版本检查
onMounted(() => {
  checkHealth();
  // 延迟执行版本检查，避免影响健康检查
  setTimeout(() => {
    checkForUpdates();
  }, 1000);
});
</script>


<style lang="scss" scoped>
.home-container {
  position: relative;
  width: 100%;
  height: 100vh;
  overflow: hidden;
}

.background-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  z-index: -1;
}

.image-container {
  position: absolute;
  cursor: pointer;
  width: 400px; /* 设置宽度 */
  height: 400px; /* 设置高度 */
  overflow: hidden;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.6); /* 添加阴影效果 */

  .zoom-on-hover {
    transition: transform 0.3s ease;
    width: 100%; /* 确保图片充满容器 */
    height: 100%; /* 确保图片充满容器 */
    object-fit: cover; /* 裁剪图片以适应容器 */
  }

  &:hover .zoom-on-hover {
    transform: scale(1.1);
  }

}

.left-image {
  top: 50%;
  right: 50%;
  transform: translateY(-50%);
  margin-right: 50px;
}

.right-image {
  top: 50%;
  left: 50%;
  transform: translateY(-50%);
  margin-left: 50px;
}

.overlay-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: white;
  font-size: 24px;
  text-align: center;
  z-index: 1;
  background-color: rgba(0, 0, 0, 0.5);
  padding: 10px 40px;
  line-height: 50px;
  min-height: 80px;
  min-width: 250px;
}
</style>
