<template>
  <div class="navbar-container" :style="{ '--limit_width': Limit_Width + 'px', '--limit_height': Limit_Height + 'px' }">
    <!-- 背景装饰光效 -->
    <div class="navbar-glow"></div>

    <div class="navbar-content">
      <!-- 左侧时间和天气信息 -->
      <div class="navbar-left">
        <div class="status-item weather-info">
          <span class="icon">
            <img src="@/assets/images/headers/yuanxin.png" alt="图标" class="weather-icon"
              style="width: 100%; height: 100%;">
          </span>
          <!-- <span class="text">晴 18℃</span> -->
        </div>
        <!-- <div class="status-item time-info">
        
          <span class="text">{{ currentTime }}</span>
        </div> -->
      </div>

      <!-- 中间标题 -->
      <div class="navbar-center">
        <div class="title-container">
          <h1 class="platform-title">千帆星座天地一体化智慧数字孪生应用平台</h1>
          <div class="title-glow"></div>
        </div>
      </div>

      <!-- 右侧功能按钮 -->
      <div class="navbar-right">

        <div class="control-item company-item" @click="handletoLinkClick">
          <img v-if="!imageError" src="@/assets/images/headers/header_style.png" alt="大屏配置" class="company-logo"
            @error="handleImageError">

          <span class="control-label">跳转</span>
        </div>



        <div class="control-item digital-person-item" :class="{ active: digitalPersonShow }">
          <el-switch v-model="digitalPersonShow" />
          <span class="control-label">数字人</span>
        </div>

        <div class="control-item company-item" @click="handleCompanyClick">
          <img v-if="!imageError" src="@/assets/images/headers/header_style.png" alt="大屏配置" class="company-logo"
            @error="handleImageError">
          <!-- <div v-else class="logo-placeholder">DL</div> -->
          <span class="control-label">大屏配置</span>
        </div>
        <div class="control-item rightTime">
          <span class="timeColor">{{ currentTime.split(" ")[0] }}</span>
          <span>{{ currentTime.split(" ")[1] }}</span>
        </div>
      </div>
    </div>

    <el-dialog v-model="screenConfigeDialogVisible" :destroy-on-close="false" :modal="false" width="100"
      :show-close="false" :before-close="handleScreenConfigeClose"
      style=" background-color: rgba(0, 0, 0,0);padding: 0;margin: 0;">
      <screenConfige @handleScreenConfigeClose="handleScreenConfigeClose"></screenConfige>
      <!-- <div style="width: 100px;height: 100px;background-color: blueviolet;"></div> -->
    </el-dialog>



    <!-- <el-dialog
        v-model="digitalPersonShow"
        title="Tips"
        width="500"
        draggable
        overflow
        :modal="false"
        :close-on-click-modal="false"
      >
    </el-dialog> -->
    <div v-if="digitalPersonShow" class="draggable-box" :style="{ left: pos.x + 'px', top: pos.y + 'px' }">
      <span class="title" @mousedown="startDrag">拖拽我（带边界限制）</span>
      <!-- <el-input v-model="value" placeholder="请输入内容" /> -->
      <!-- <Sender v-model="senderValue" variant="updown" clearable allow-speech /> -->

      <el-button type="primary" @click="console.log('value')">提交</el-button>
    </div>
  </div>
</template>

<script setup>

// import { BubbleList, Sender } from 'vue-element-plus-x';
import { ref, onUnmounted, watch, onBeforeMount, onDeactivated, onMounted } from 'vue';
import local from '@/utils/local.js'
import screenConfige from './component/screenConfigeDialog.vue'
import { useRouter } from 'vue-router';
import useAppStore from '@/store/module/app'
import { getRegionPanel, getSignalSitePanel, getGridPanel } from "@/api/Zodiac";


import errorDialog from '@/pages/lefts/component/errorDialog.vue'

const useAppStoreInstance = useAppStore()

// 在 setup 中
const router = useRouter();

// 数字人显示状态
const digitalPersonShow = ref(false);
// 实时更新时间
const currentTime = ref('');
// 图片加载错误状态
const imageError = ref(false);
// 屏幕配置对话框显示状态
const screenConfigeDialogVisible = ref(false);
// 监视digitalPersonShow变化
watch(digitalPersonShow, (newValue) => {
  if (newValue) {
    //console.log('数字人显示');
    local.local.set('digitalPersonShow', 'true');
  } else {
    //console.log('数字人隐藏');
    local.local.set('digitalPersonShow', 'false');
  }
});

const handleScreenConfigeClose = () => {
  screenConfigeDialogVisible.value = false;
  if (window.ue5) {
    window.ue5("callBackAllDialogFn", String(JSON.stringify({
      type: "LargeScreenConfigurationDialog",
      status: "close"
    })));
  }
};
// 格式化日期时间显示
const formatDateTime = () => {
  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');
  const seconds = String(now.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 处理图片加载错误
const handleImageError = (e) => {
  imageError.value = true;
  e.target.style.display = 'none';
};


const toSubSystemFlag = ref(false);
const handletoLinkClick = () => {
  try {

    if (toSubSystemFlag.value) {
      // location.replace('/subsystem');
      router.push('/');
      //console.log("1111111111111111111111111",useAppStoreInstance.isSourceLegendShow);
      useAppStoreInstance.setGlobalisFromTosub(true);
      useAppStoreInstance.setislegendShow(useAppStoreInstance.isSourceLegendShow ? true : false);
      //console.log("11111111111111111111111112",useAppStoreInstance.islegendShow);
      useAppStoreInstance.setiscontrolPanelShow(true);
      useAppStoreInstance.setGlobalSubsystemSelectedTimeRange([]);
    }
    if (!toSubSystemFlag.value) {
      // location.replace('/');
      useAppStoreInstance.setiscontrolPanelShow(false);
      // useAppStoreInstance.setGlobalisFromTosub(true);
      // useAppStoreInstance.setglobalSatelliteSearchID('4096');
      if (!useAppStoreInstance.islegendShow) {
        useAppStoreInstance.setislegendShow(true);
      }
      router.push(
        {
          name: 'subsystem',
          // query: {
          //   startTime:useAppStoreInstance.globalSubsystemSelectedStartTime,
          //   endTime:useAppStoreInstance.globalSubsystemSelectedEndTime,
          //   disabled:true
          // }
        }
      );
    }
    // 执行跳转
    // router.push('/subsystem');
    toSubSystemFlag.value = !toSubSystemFlag.value;
  } catch (error) {
    console.error('跳转前操作出错:', error);
  }
};
const handleCompanyClick = () => {
  // 可以添加点击事件逻辑
  screenConfigeDialogVisible.value = !screenConfigeDialogVisible.value;
  if (window.ue5) {
    window.ue5("callBackAllDialogFn", String(JSON.stringify({
      type: "LargeScreenConfigurationDialog",
      status: "open"
    })));
  }
};
// 组件生命周期管理
let updateTimer;
onBeforeMount(() => {
  digitalPersonShow.value = local.local.get('digitalPersonShow') === 'true';
  // 初始化时间
  currentTime.value = formatDateTime();
  // 每秒更新一次时间
  updateTimer = setInterval(() => {
    currentTime.value = formatDateTime();
  }, 1000);
});


onMounted(async () => {
  // window.addEventListener('message', handleUEMessage);
  // window.addEventListener('emitUIInteraction', handleUEMessage1);
  window.ue.interface.emitUIInteraction = (res) => {
    //    if (window.ue5) {
    //     window.ue5("callBackTimeFn", `ue传递给vue的数据111111111111111111:${JSON.stringify(res)},${JSON.stringify(res.locationReplace)}`)
    // }
    const resData = JSON.parse(res);
    //  if (window.ue5) {
    //     window.ue5("callBackTimeFn", `测试数据111111111111111111:${JSON.stringify(resData)},${JSON.stringify(resData.locationReplace)},${JSON.stringify(resData.locationReplace === 'true')}`)
    // }
    console.log("我是handleUEMessage,收到UE交互:", resData);

    if (resData.locationReplace === 'true') {
      useAppStoreInstance.setiscontrolPanelShow(false);
      useAppStoreInstance.setglobalSatelliteSearchID(resData.SatelliteSearchID || '4097');
      if (!useAppStoreInstance.islegendShow) {
        useAppStoreInstance.setislegendShow(true);
      }
      router.push(
        {
          name: 'subsystem',
          // params: {
          //   userId: 123,
          //   userName: '张三',
          //   timestamp: Date.now()
          // }
        }
      );
      toSubSystemFlag.value = !toSubSystemFlag.value;
    }
    if (resData.locationReplace === 'false') {
      router.push('/');

      //console.log("1111111111111111111111111",useAppStoreInstance.isSourceLegendShow);
      useAppStoreInstance.setGlobalisFromTosub(true);
      useAppStoreInstance.setislegendShow(useAppStoreInstance.isSourceLegendShow ? true : false);
      //console.log("11111111111111111111111112",useAppStoreInstance.islegendShow);
      useAppStoreInstance.setiscontrolPanelShow(true);
      useAppStoreInstance.setGlobalSubsystemSelectedTimeRange([]);
    }
    //  try {
    //   const resData = JSON.parse(res.data);
    //   if (window.ue5) {
    //     window.ue5("callBackTimeFn", `ue传递给vue的数据111111111111111111:${JSON.stringify(res)}`)
    // }
    //   //console.log("Received from UE:", resData);

    //   if (resData.locationReplace === true) {
    //      router.push('/subsystem');
    //   }
    //   if (resData.locationReplace === false) {
    //      router.push('/');
    //   }
    // } catch (parseError) {
    //   console.error("Error parsing JSON:", parseError);
    // }
  }



 await initChartData();



});


onUnmounted(() => {
  // 清理定时器
  clearInterval(updateTimer);
});






const Limit_Height = ref(200);
const Limit_Width = ref(500);
const pos = ref({ x: 0, y: 0 });
let isDragging = false;
let offset = { x: 0, y: 0 };

const startDrag = (e) => {
  isDragging = true;
  offset.x = e.clientX - pos.value.x;
  offset.y = e.clientY - pos.value.y;
  window.addEventListener('mousemove', drag);
  window.addEventListener('mouseup', stopDrag);
};

const drag = (e) => {
  if (!isDragging) return;
  // 限制在窗口范围内（可替换为父容器边界）
  pos.value.x = Math.max(0, Math.min(e.clientX - offset.x, window.innerWidth - Limit_Width.value));
  pos.value.y = Math.max(0, Math.min(e.clientY - offset.y, window.innerHeight - Limit_Height.value));
};

const stopDrag = () => {
  isDragging = false;
  window.removeEventListener('mousemove', drag);
};


const initChartData = async () => { 
// console.log("初始化数据",useAppStoreInstance);
  const [res1,res2,res3] = await Promise.all([getRegionPanel(), getSignalSitePanel(), getGridPanel()])
  useAppStoreInstance.regionPanelData =  res1.code==200?res1.data.map(item=>({value:item,label:item})):[]
  useAppStoreInstance.signalSitePanelData =  res2.code==200?res2.data.map((item)=>({value:item.siteId,label:item.siteName})):[]
  useAppStoreInstance.gridPanelData = res3.code==200?res3.data.map(item=>({value:item.gridCode,label:item.gridName})):[]
};






</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
}



.draggable-box {
  width: var(--limit_width);
  background: #ffffff;
  position: absolute;
  z-index: 9999;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.draggable-box .title {
  cursor: grab;
  background: #d10e0e;
  color: white;
  padding: 10px;
  text-align: center;
  font-weight: bold;
  flex-shrink: 0;
  user-select: none;
  /* 防止拖拽时选中文本 */
}








/* 基础容器样式 */
.navbar-container {
  width: 100%;
  background-color: black;
  min-width: 750px;
  overflow: hidden;
  /* height: 250px; */

  /* box-shadow: 0 2px 15px rgba(0, 15, 45, 0.5); */
}

/* 背景发光效果 */
/* .navbar-glow {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: radial-gradient(circle at center, rgba(30, 144, 255, 0.15) 0%, transparent 70%),
              linear-gradient(to bottom, rgba(0, 30, 80, 0.3) 0%, transparent 100%);
  pointer-events: none;
} */

/* 内容容器 */
.navbar-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 2rem;
  position: relative;
  z-index: 1;
  height: 55px;
  max-width: 1920px;
  margin: 0 auto;
  background: url("@/assets/images/headers/header_bg.png");
  /* padding: 0.6rem 0; */
  position: relative;
  overflow: hidden;
  background-size: 100% 160%;
  /* 或者 cover/auto */
  background-repeat: no-repeat;
  background-position: center;

}

/* 左侧状态信息 */
.navbar-left {
  display: flex;
  align-items: center;
  gap: 1.8rem;
  width: 480px;
  /* background-color: aquamarine; */
}

.status-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: rgba(255, 255, 255, 0.9);
  font-size: 0.9rem;
  padding: 0.3rem 0.6rem;
  border-radius: 4px;
  /* background: rgba(255, 255, 255, 0.05); */
  /* backdrop-filter: blur(5px); */
  /* border: 1px solid rgba(255, 255, 255, 0.08); */
}

.status-item .icon {
  width: 120px;
}

.weather-info .text::after {

  content: '|';
  margin-left: 1.5rem;
  opacity: 0.6;

}

/* 中间标题区域 */
.navbar-center {
  flex: 1;
  display: flex;
  justify-content: center;
  margin: 0 1rem;
  /* width: 500px;
  position: relative;
  left: 80px; */
  /* background-color: antiquewhite; */
}

.title-container {
  position: relative;
}

.platform-title {
  font-size: 1.3rem;
  font-weight: 800;
  color: #ffffff;
  margin: 0;
  letter-spacing: 0.8px;
  text-align: center;
  text-shadow: 0 0 15px rgba(100, 180, 255, 0.5), 0 0 30px rgba(50, 120, 255, 0.3);
  white-space: nowrap;
}

/* 标题发光效果 */
.title-glow {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100%;
  height: 100%;
  background: radial-gradient(circle, rgba(100, 180, 255, 0.3) 0%, transparent 80%);
  filter: blur(10px);
  z-index: -1;
}

/* 右侧控制区域 */
.navbar-right {
  display: flex;
  align-items: center;
  font-size: small;
  width: 480px;
  overflow: hidden;
  padding-top: 10px;
  /* background-color: #d10e0e; */
}

.timeColor {
  color: #ddd;
}

.rightTime {
  border-left: 1px solid #ddd;
  height: 10px;
}

.control-item {
  display: flex;
  align-items: center;
  gap: 0.6rem;
  color: #ffffff;
  cursor: pointer;
  padding: 0.4rem 0.8rem;
  /* border-radius: 6px; */
  transition: all 0.3s ease;
  /* background: rgba(255, 255, 255, 0.05); */
  /* backdrop-filter: blur(5px); */
  /* border: 1px solid rgba(255, 255, 255, 0.08); */
}

/* .control-item:hover {
  background: rgba(255, 255, 255, 0.12);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 20, 60, 0.3);
  border-color: rgba(255, 255, 255, 0.15);
} */

.control-item:active {
  transform: translateY(0);
}

.control-label {
  font-size: 0.95rem;
  font-weight: 400;
  text-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
}

/* 数字人控制项激活状态 */
/* .digital-person-item.active {
  background: rgba(19, 206, 102, 0.15);
  border-color: rgba(19, 206, 102, 0.3);
} */

/* 公司logo样式 */
.company-logo {
  width: 22px;
  height: 22px;
  object-fit: contain;
  border-radius: 3px;
  transition: transform 0.3s ease;
}

.control-item:hover .company-logo {
  transform: scale(1.31);
}

/* 图片加载错误占位符 */
.logo-placeholder {
  width: 22px;
  height: 22px;
  background: rgba(255, 255, 255, 0.15);
  border-radius: 3px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
  color: rgba(255, 255, 255, 0.8);
}

/* 响应式设计 */
@media (max-width: 1440px) {
  .platform-title {
    font-size: 1.15rem;
  }

  .navbar-left {
    gap: 1.5rem;
  }
}

@media (max-width: 1200px) {
  .platform-title {
    font-size: 1.05rem;
  }

  .status-item {
    font-size: 0.85rem;
    gap: 0.4rem;
  }
}

@media (max-width: 992px) {

  /* .navbar-left {
    display: none;
  } */
  .company-item {
    display: none;
  }

  .digital-person-item {
    display: none;
  }

  .navbar-right {
    gap: 1rem;
  }

  .control-item {
    padding: 0.35rem 0.7rem;
  }

  .control-label {
    font-size: 0.9rem;
  }
}

@media (max-width: 768px) {
  .navbar-content {
    padding: 0 1.2rem;
  }

  .platform-title {
    font-size: 0.95rem;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 280px;
  }

  .company-item .control-label {
    display: none;
  }

  .company-item {
    padding: 0.35rem;
  }
}

@media (max-width: 576px) {


  .platform-title {
    overflow: visible;
    text-overflow: unset;
    max-width: none;
    font-size: 0.9rem;
  }

  .navbar-content {
    padding: 0 1rem;
  }
}
</style>