<template>
  <IxApplication :appSwitchConfig="appSwitchConfig" theme="classic-dark">
    <IxApplicationHeader :name="appName" :applicationSwitchButton="true">
      <!-- 添加实时显示时间 -->
      <div v-if="appSwitchConfig.currentAppId === 'mis-app'" class="time-display">{{ currentTime }}</div>

      <!-- 确保图标按钮正确显示 -->      
      <el-badge v-if="appSwitchConfig.currentAppId === 'mis-app'" :value="alarmCount" class="item">
        <IxIconButton icon="alarm-bell-filled" variant="secondary" ghost></IxIconButton>
      </el-badge>
      <IxIconButton v-if="appSwitchConfig.currentAppId === 'mis-app'" icon="calendar-filled" variant="secondary" ghost @click="toggleDatetimePicker"></IxIconButton>
      <IxIconButton v-if="appSwitchConfig.currentAppId === 'mis-app'" icon="alarm-clock-filled" variant="secondary" ghost @click="handleReset"></IxIconButton>
    </IxApplicationHeader>

    <IxContent class="mainContent">
      <router-view @update-history="updateHistory" @reset="reset" @send-data="handleDataFromChild"></router-view>
    </IxContent>

    <!-- 添加遮罩层和日期选择器组件 -->
    <div v-if="showDatetimePicker" class="overlay" @click="closeDatetimePicker"></div>
    <div v-if="showDatetimePicker" class="datetime-picker-container">
      <IxDatetimePicker v-if="appSwitchConfig.currentAppId === 'mis-app'" range="false" showSeconds="false" show-time-reference="true" @done="handleDatetimePickerDone" />
      <IxDatePicker v-else range="false" @dateChange="handleDatePickerDone" style="--theme-menu--background: '#232323'"/>
      <button class="close-button" @click="closeDatetimePicker">关闭</button>
    </div>
  </IxApplication>
</template>

<script setup>
import {
  IxApplication,
  IxApplicationHeader,
  IxContent,
  IxContentHeader,
  IxDropdownButton,
  IxDropdownItem,
  IxIconButton,
  IxDatetimePicker,
  IxDatePicker,
} from '@siemens/ix-vue';
import { ref, onMounted, onUnmounted, watch, computed } from 'vue';
import { useAlarmStore } from '@/stores/alarmStore'; // 假设我们有一个 alarmStore

const alarmStore = useAlarmStore(); // 使用 alarmStore
const alarmCount = computed(() => alarmStore.alarmCount); // 从 alarmStore 中获取报警计数

let appSwitchConfig = {
  i18nAppSwitch: '切换应用',
  i18nLoadingApps: '加载应用中...',
  currentAppId: 'mis-app',
  apps: [
    {
      id: 'mis-app',
      name: 'MIS 1.0',
      iconSrc: require('@/assets/genetic-data.svg'),
      url: '/',
      description: '前处理系统',
      target: '_self',
    },
    {
      id: 'other-app',
      name: '点检系统',
      iconSrc: require('@/assets/genetic-data.svg'),
      url: '/#/inspection',
      description: '其他系统描述',
      target: '_self',
      // target: '_blank',
    },
  ],
};

const currentTime = ref('');
const showDatetimePicker = ref(false);
const selectedDatetime = ref('');
const isAutoUpdate = ref(true);
const appName = ref('SIEMENS MIS 1.0 前处理界面');

const updateTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  currentTime.value = `${year}-${month}-${day} ${hours}:${minutes}`;
};

const toggleDatetimePicker = () => {
  showDatetimePicker.value = !showDatetimePicker.value;
};

const handleReset = () => {
  // 触发主页中的 getHistory 方法
  const event = new CustomEvent('reset');
  updateTime();
  window.dispatchEvent(event);
  isAutoUpdate.value = true; // 重置后恢复自动刷新
};

const handleDatetimePickerDone = (event) => {
  selectedDatetime.value = event.detail;
  showDatetimePicker.value = false;
  updateHistoryWithTime(selectedDatetime.value);
  isAutoUpdate.value = false; // 选择完历史时间后停止自动刷新
};

const handleDatePickerDone = (event) => {
  selectedDatetime.value = event.detail;
  showDatetimePicker.value = false;
  updateHistoryWithDate(selectedDatetime.value);
  isAutoUpdate.value = false; // 选择完历史时间后停止自动刷新
};

const updateHistoryWithTime = (datetime) => {
  // 将 datetime 转换为标准的 YYYY-MM-DD HH:mm:ss 格式
  const parsedDate = new Date(datetime.replace(/-/g, '/'));
  if (isNaN(parsedDate.getTime())) {
    console.error('Invalid datetime format:', datetime);
    return;
  }
  const year = parsedDate.getFullYear();
  const month = String(parsedDate.getMonth() + 1).padStart(2, '0');
  const day = String(parsedDate.getDate()).padStart(2, '0');
  const hours = String(parsedDate.getHours()).padStart(2, '0');
  const minutes = String(parsedDate.getMinutes()).padStart(2, '0');
  const seconds = String(parsedDate.getSeconds()).padStart(2, '0');
  const formattedDatetime = `${year}-${month}-${day} ${hours}:${minutes}`;
  // 触发主页中的 getHistory 方法
  const event = new CustomEvent('update-history', { detail: formattedDatetime });

  currentTime.value = formattedDatetime;

  window.dispatchEvent(event);
};

const updateHistoryWithDate = (date) => {
  // 将 date 转换为标准的 YYYY-MM-DD 格式
  const { from } = date;
  const parsedDate = new Date(from);
  if (isNaN(parsedDate.getTime())) {
    console.error('Invalid date format:', from);
    return;
  }
  const year = parsedDate.getFullYear();
  const month = String(parsedDate.getMonth() + 1).padStart(2, '0');
  const day = String(parsedDate.getDate()).padStart(2, '0');
  const formattedDate = `${year}-${month}-${day}`;
  // 触发主页中的 getHistory 方法
  const event = new CustomEvent('update-history', { detail: formattedDate });

  currentTime.value = formattedDate;

  window.dispatchEvent(event);
};

const handleDataFromChild = (data, name) => {
  appName.value = data;
  appSwitchConfig.currentAppId = name;
};

const closeDatetimePicker = () => {
  showDatetimePicker.value = false;
};

onMounted(() => {
  updateTime();
  const interval = setInterval(() => {
    if (showDatetimePicker.value || !isAutoUpdate.value) return; // 如果显示日期时间选择器或停止自动刷新，则不更新时间
    updateTime();
  }, 60000); // 每分钟更新一次
  onUnmounted(() => clearInterval(interval));  // 监听应用切换事件
});
</script>

<style scoped>
ix-application {
  width: 100%;
  /* height: 100vh; */
  /* 设置应用高度为视口高度 */
  background-color: #000028;
  font-family: 'Microsoft YaHei', sans-serif;
  font-size: 1.5rem;
  /* 调大全局字体大小 */
  display: flex;
  /* 使用 flex 布局 */
  flex-direction: column;
  /* 垂直排列子元素 */
}

:deep(ix-application-header) {
  background-color: #23233C !important;
  height: 4rem !important;
  /* 64px 转换为 rem */
  padding: 0 !important;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  display: flex;
  align-items: center;
  flex-shrink: 0;
  /* 防止头部收缩 */
}

.logo-container {
  display: flex;
  align-items: center;
  height: 100%;
  padding: 0.1rem;
}

.logo-text {
  color: #fff;
  font-size: 1.2rem;
  /* 调大 logo 文本字体大小 */
  font-weight: 500;
  letter-spacing: 0.03125rem;
  /* 0.5px 转换为 rem */
  padding: 0.1rem;
}

.time-display {
  color: #fff;
  font-size: 1rem;
  /* 调大时间显示字体大小 */
  margin: 0.5rem 1rem 0 1rem;
  /* 16px 转换为 rem */
  font-weight: bold;
}

:deep(.ix-icon-button) {
  --background-color: transparent;
  --color: #fff;
  height: 4rem;
  /* 64px 转换为 rem */
  width: 4rem;
  /* 64px 转换为 rem */
  border-radius: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.application-name) {
  color: #fff !important;
  font-size: 1.2rem !important;
  /* 调大应用名称字体大小 */
  font-weight: normal !important;
  display: flex;
  align-items: center;
}

:deep(IxContent) {
  width: 100%;
  height: calc(100vh - 4rem);
  padding: 0 !important;
  /* 确保没有内边距 */
  margin: 0 !important;
  position: relative;
  /* 确保 IxDatetimePicker 组件正确显示 */
  flex-grow: 1;
  /* 让内容区域填充剩余空间 */
}

.overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  z-index: 999;
}

.datetime-picker-container {
  position: absolute;
  top: 4rem;
  right: 1rem;
  z-index: 1000;
  background: #23233C;
  padding: 1rem;
  border-radius: 0.5rem;
}

.close-button {
  margin-top: 1rem;
  background: #23233C;
  color: skyblue;
  /* border: none; */
  padding: 0.5rem 1rem;
  border-radius: 0.25rem;
  cursor: pointer;
}

:deep(ix-datetime-picker){
  --theme-menu--background: #23233C;  
  border: 1px solid #fff;
}

:deep(IxApplication) {
  margin: 0;
  /* 确保没有外边距 */
  padding: 0;
  /* 确保没有内边距 */
}

.mainContent {
  padding: 0 !important;
  margin: 0;
  display: flex;
  flex-direction: column;
  background: #000028;
  min-height: 100vh;
  width: 100%;
  overflow-x: hidden;
}

:global(.visible) {
  --theme-modal--background:#23233C !important;
  /* --theme-color-ghost--selected:#23233C !重要; */
}

.item {
  margin-right: 0.5rem;
}

.alarm-count {
    color: red;
    font-size: 1.2rem;
    margin-right: 1rem;
}
</style>