<template>
  <div class="constellation-panel">
    <!-- 顶部区域：标题与核心指标 -->
    <div class="header-container">
      <!-- 标题栏 -->
      <div class="section-divider">
        <div class="divider-line"></div>
        <h3 class="section-title">卫星弧段信息</h3>
        <div class="divider-line"></div>
      </div>

      <!-- 轨道参数可视化 -->
      <div class="orbit-visualization">
        <div class="orbit-visualization-container" style="min-height: 41vh;">
          <div class="table-header">
            <el-input placeholder="搜索" size="small" class="search-input" @input="searchSegmentList_up"
              v-model="searchSegmentValue">
              <template #prefix>
                <el-icon class="search-icon">
                  <Search />
                </el-icon>
              </template>
            </el-input>
          </div>

          <el-table :data="rawData_up" size="small" height="440px" class="custom-table">
            <el-table-column prop="segmentId" label="弧段编号" width="100" align="center"></el-table-column>
            <el-table-column prop="satelliteId" label="卫星编号" width="120" align="center"></el-table-column>
            <el-table-column prop="entryTime" label="入境时刻(北京时间)" width="150" align="center"></el-table-column>
            <el-table-column prop="exitTime" label="出境时刻(北京时间)" width="150" align="center">
              <template #default="scope">
                {{ scope.row.exitTime ===
                  "-" ? scope.row.exitTime : compareTime(useAppStoreInstance.subSystemTimeLineEndSelectTime,
                    scope.row.exitTime)?scope.row.exitTime:"-" }}
              </template>
            </el-table-column>
            <el-table-column prop="duration" label="时长(sec)" width="80" align="center">
              <template #default="scope">
                {{ scope.row.duration ===
                  "-" ? scope.row.duration : compareTime(useAppStoreInstance.subSystemTimeLineEndSelectTime,
                    scope.row.exitTime)?scope.row.duration:"-" }}
              </template>
            </el-table-column>
            <el-table-column prop="groundStation" label="地面站" width="90" align="center"></el-table-column>
            <el-table-column prop="trackingType" label="测控类型" width="80" align="center"></el-table-column>
            <!-- <el-table-column prop="operationResult" label="操作结果" width="100" align="center">
          <template #default="scope">
             {{ scope.row.operationResult }}
            
          </template>
        </el-table-column> -->
          </el-table>
        </div>
      </div>
    </div>

    <!-- 地面系统 -->
    <div class="ground-system-section">
      <div class="section-divider">
        <div class="divider-line"></div>
        <h3 class="section-title">卫星告警信息</h3>
        <div class="divider-line"></div>
      </div>

      <!-- 地面站设备数量 -->
      <div class="equipment-panel">
        <div class="orbit-visualization-container">
          <div class="table-header">
            <el-input placeholder="搜索" size="small" class="search-input" @input="searchAlterList"
              v-model="searchAlterValue">
              <template #prefix>
                <el-icon class="search-icon">
                  <Search />
                </el-icon>
              </template>
            </el-input>
          </div>

          <el-table :data="alertData" size="small" height="380px" class="custom-table"
            @row-click="handleAlertDataRowClick">
            <el-table-column prop="alertCode" label="告警码" width="80" align="center"></el-table-column>
            <el-table-column prop="alertName" label="告警名称" width="80" align="center"></el-table-column>
            <el-table-column prop="alertObject" label="告警对象" width="120" align="center"></el-table-column>

            <el-table-column prop="alertLevel" label="告警等级" width="80" align="center">
              <template #default="scope">
                <el-tag :class="`alert-level_${OpposeAlertLevelMap[scope.row.alertLevel]}`">
                  {{ scope.row.alertLevel }}
                </el-tag>
              </template>
            </el-table-column>
            <!-- <el-table-column prop="faultServiceLeve" label="服务故障等级" width="150" align="center"></el-table-column> -->
            <el-table-column prop="alterCreateTime" label="告警产生时间" width="120" align="center"></el-table-column>
            <el-table-column label="告警状态" width="70" align="center" fixed="right">
              <template #default="scope">
                <el-tag :class="`alert-status_${OpposeAlertDataStatusMap[scope.row.alertStatus]}`">
                  <!-- {{ scope.row.alertStatus === '0' ? '未处理' : '已处理' }} -->
                  {{ scope.row.alertStatus }}
                </el-tag>
              </template>
            </el-table-column>

          </el-table>
        </div>
      </div>
    </div>

    <el-dialog v-model="errorDataShowDialogVisible" :show-close="false" :modal="false" modal-penetrable
      :before-close="handleIsErrorDataCloseFn" :destroy-on-close="true"
      style="background: rgba(0, 0, 0, 0);padding: 0;margin: 0;">
      <errorDataShowComponent @handleIsErrorDataCloseFn="handleIsErrorDataCloseFn" :errorDetailItems="errorDetailItems">
      </errorDataShowComponent>
    </el-dialog>
  </div>
</template>

<script setup>
import { nextTick, onMounted, ref } from 'vue';
import errorDataShowComponent from './component/errorDataShowComponent.vue'
import useAppStore from '@/store/module/app'
import { fa } from 'element-plus/es/locales.mjs';


const useAppStoreInstance = useAppStore();

const searchSegmentValue = ref('');
const primitive_rawData_up = ref([
  // {
  //   segmentId: "SS GEN1-74",
  //   satelliteId: "satellite II -52",
  //   entryTime: "2025-09-02 10:00:00",
  //   exitTime: "2025-09-02 10:07:03",
  //   duration: 423,
  //   groundStation: "库尔勒站",
  //   trackingType: "Ku",
  //   operationResult: "帆板展开"
  // }
])
const rawData_up = ref(primitive_rawData_up)

const arcInfoTransform = (data) => {
  //console.log("wodsad--------arcInfoTransform",data,typeof data);
  if (!data || typeof data !== 'object' || Array.isArray(data)) {
    return [];
  }

  // 按时间排序后转为数组
  return Object.entries(data)

    .map(([time, item]) => ({
      orginData: item,
      segmentId: item[0].missionId || '-',
      satelliteId: item[0].satName || '-',
      entryTime: item[0].arcStartTime || '-',
      exitTime: item[0].arcEndTime || '-',
      duration: item[0].arcDuration || '-',
      groundStation: item[0].siteName || '-',
      trackingType: item[0].missionType || '-'
    }));
}




const searchSegmentList_up = () => {

  rawData_up.value = primitive_rawData_up.value.filter(item =>
    item.segmentId.toLowerCase().includes(searchSegmentValue.value.toLowerCase()) ||
    item.satelliteId.toLowerCase().includes(searchSegmentValue.value.toLowerCase()) ||
    item.groundStation.toLowerCase().includes(searchSegmentValue.value.toLowerCase()) ||
    item.trackingType.toLowerCase().includes(searchSegmentValue.value.toLowerCase()) ||
    item.operationResult.toLowerCase().includes(searchSegmentValue.value.toLowerCase())
  )
}




onMounted(() => {
  nextTick(() => {
    watch(() => useAppStoreInstance.subsystemSocketContent, (newValue, oldValue) => {
      //console.log("******************",newValue);

      // if (newValue !== oldValue) {
      primitive_rawData_up.value = arcInfoTransform(newValue.rightTop)
      rawData_up.value = primitive_rawData_up.value
      primitiveAlertData.value = alertInfoTransformFn(newValue.rightBottom)
      alertData.value = primitiveAlertData.value
      //console.log("222222222right2----123-----", primitiveAlertData.value);

      // }

    }, { deep: true, immediate: true });
  })
  // useAppStoreInstance.subsystemSocket.onmessage = (event) => {
  //     const Jsondata = JSON.parse(event.data);
  //     primitive_rawData_up.value = arcInfoTransform(Jsondata.arcSegmentInfoArray)
  //     rawData_up.value = primitive_rawData_up.value
  //     primitiveAlertData.value = alertInfoTransformFn(Jsondata.satelliteAlertInfoArray)
  //     alertData.value = primitiveAlertData.value
  //     //console.log("222222222right2---------",rawData_up.value,Jsondata.arcSegmentInfoArray);
  //     // useAppStoreInstance.setSubsystemSocketContent(Jsondata)
  //   }
})
const alertLevelMap = {
  '1': 'Ⅰ级',
  '2': 'Ⅱ级',
  '3': 'Ⅲ级',
  '4': 'Ⅳ级'
}
const OpposeAlertLevelMap = {
  'Ⅰ级': '1',
  'Ⅱ级': '2',
  'Ⅲ级': '3',
  'Ⅳ级': '4',
}

const OpposeAlertDataStatusMap = ref({
  "手工清除": '2',
  "活动": '1',
  "自动清除": '0',
})
// 卫星告警信息数据（随机生成）
const primitiveAlertData = [
  // { 
  //   alertCode: "500", 
  //   alertName: "电源系统电压异常", 
  //   alertObject: "电源系统", 
  //   alertLevel: "1", 
  //   faultServiceLeve: "F4(灾难性)", 
  //   alterCreateTime: "2025-12-13 10:23:45", 
  //   alertStatus: "0" 
  // },

];


const compareTime = (time1, time2) => {
  //console.log('cao每隔开始compareTime----------', time1, time2);
  // 将时间字符串转换为 Date 对象
  const date1 = new Date(time1);
  // if (time2 === '-') {
  //   time2 = ""
  // }
  if (time2 === null || time2 === "" || time2 === undefined) {
    time2 = new Date(
      new Date(selectedStartTime.value).getTime() + 60 * 1000
    ).toISOString();
    // //console.log('每隔开始compareTime----------', time1, time2);
  }
  const date2 = new Date(time2);

  // 检查时间是否有效
  if (isNaN(date1.getTime()) || isNaN(date2.getTime())) {
    throw new Error("无效的时间格式");
  }

  // 比较时间戳
  if (date1 >= date2) {
    return true;
  } else {
    return false;
  }
};



const alertData = ref(primitiveAlertData)

const AlertDataLevelMap = ref({
  '一级告警': 1,
  '二级告警': 2,
  '三级告警': 3,
  '四级告警': 4,
})
const AlertDataStatusMap = ref({
  "1": '手工清除',
  "0": '活动',
})
const alertInfoTransformFn = (data) => {
  //console.log("wodsad--------alertInfoTransformFn",data,typeof data);
  if (!data || typeof data !== 'object' || Array.isArray(data)) {
    return [];
  }

  // 按时间排序后转为数组
  return Object.entries(data)

    .map(([time, data]) => ({
      orginData: data,
      alertCode: data[0].alarmCode ? data[0].alarmCode : '-',
      alertName: data[0].alarmName ? data[0].alarmName : '-',
      alertObject: data[0].objectName ? data[0].objectName : '-',
      alertLevel: alertLevelMap[AlertDataLevelMap.value[data[0].alarmLevel]] ? alertLevelMap[AlertDataLevelMap.value[data[0].alarmLevel]] : '-',
      // faultServiceLeve: "F4(灾难性)", 
      alterCreateTime: data[0].alarmOccurrenceTime ? data[0].alarmOccurrenceTime : '-',
      alertStatus: data[0].clearStatus ? data[0].clearStatus : '-',
    }));

}




const searchAlterValue = ref('');
const searchAlterList = () => {
  alertData.value = primitiveAlertData.filter(item =>
    item.alertCode.toLowerCase().includes(searchAlterValue.value.toLowerCase()) ||
    item.alertName.toLowerCase().includes(searchAlterValue.value.toLowerCase()) ||
    item.alertObject.toLowerCase().includes(searchAlterValue.value.toLowerCase()) ||

    // item.alertLevel.toLowerCase().includes(searchAlterValue.value.toLowerCase()) ||
    item.faultServiceLeve.toLowerCase().includes(searchAlterValue.value.toLowerCase()) ||
    item.alterCreateTime.toLowerCase().includes(searchAlterValue.value.toLowerCase())
    // item.alertStatus.toLowerCase().includes(searchAlterValue.value.toLowerCase())
  )
}

const errorDataShowDialogVisible = ref(false);
const errorDetailItems = ref([
  // { label: '告警码', value: '-' },
  // { label: '告警名称', value: '-' },
  // { label: '告警对象', value: '-' },
  // { label: '告警服务', value: '-' },
  // { label: '告警等级', value: '-' },
  // { label: '故障服务等级', value: '-' },
  // { label: '告警创建时间', value: '-' },
  // { label: '告警状态', value: row?.alertStatus === '1' ? '已处理' : '未处理' || '-' }
]);
const handleAlertDataRowClick = (row) => {
  console.log(row);
  errorDetailItems.value = [

    { label: '告警码', value: row.alertCode || '-' },
    { label: '告警状态', value: row.alertStatus || '-' },
    { label: '告警名称', value: row.alertName || '-' },
    { label: '告警对象', value: row.alertObject || '-' },
    { label: '告警级别', value: row.alertLevel },
    { label: '告警类型', value: row.elementType || '-' },

    { label: '告警产生时间', value: row.alterCreateTime || '-' },
    // { label: '告警清除时间', value: row?.orginData[0]?.alarmClearTime || '-' },
    { label: '告警清除人', value: row.alarmClearPerson || '-' },
    { label: '告警定位信息', value: row?.orginData[0]?.locationInfo || '-' },
    { label: '告警原因', value: row?.orginData[0]?.manufacturerAlarmCause || '-' },

  ]
  errorDataShowDialogVisible.value = true;
  if (window.ue5) {
    window.ue5("callBackAllDialogFn", String(JSON.stringify({
      type: "SatelliteAlarmInfoDialog",
      status: "open"
    })));
  }
}


const handleIsErrorDataCloseFn = () => {
  errorDataShowDialogVisible.value = false;
  if (window.ue5) {
    window.ue5("callBackAllDialogFn", String(JSON.stringify({
      type: "SatelliteAlarmInfoDialog",
      status: "close"
    })));
  }
}
</script>

<style scoped>
/* 基础样式 */
.constellation-panel {
  color: #e0e7ff;
  padding: 15px;
  border-radius: 8px;
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 20px;
  overflow-y: auto;
  background-color: #010102;
}

/* 顶部容器 */
.header-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

/* 标题栏 */
.section-divider {
  display: flex;
  align-items: center;
  margin: 0px 0 5px 0;
  background-image: url('@/assets/images/lefts/bg_title.png');
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
}

.divider-line {
  flex: 1;
  height: 1px;
  background: linear-gradient(to right, transparent, rgba(59, 130, 246, 0.3), transparent);
}

.section-title {
  font-size: 14px;
  color: #ffffff;
  font-weight: 900;
  padding: 0 15px;
  white-space: nowrap;
  display: flex;
  align-items: center;
}

/* 轨道参数可视化 */
.orbit-visualization {
  /* background: rgba(189, 40, 40, 0.4); */
  border-radius: 8px;
  min-height: 70%;
  overflow-y: auto;
}

/* 表格样式 */
.table-header {
  display: flex;
  justify-content: flex-end;
  /* margin-bottom: 10px; */
  width: 100%;
  height: 30px;
  background-color: #4e37b8;
}

.search-input {
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.95);
  border: 1px solid rgba(59, 130, 246, 0.3);
  border-radius: 4px;
  transition: all 0.3s ease;
}

.search-input:focus-within {
  border-color: rgba(59, 130, 246, 0.6);
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);
}

.search-input :deep(.el-input__wrapper) {
  background-color: transparent;
  border: none;
  box-shadow: none;
}

.search-input :deep(.el-input__inner) {
  background-color: transparent;
  color: #e0f2fe;
  font-size: 15px;
  border: none;
  box-shadow: none;
}

.search-input :deep(.el-input__inner::placeholder) {
  color: rgba(224, 231, 255, 0.7);
}

.search-icon {
  color: #94a3b8;
}

.custom-table {
  background: #000000;
  border: 1px solid rgba(59, 130, 246, 0.3);
  border-radius: 6px;
  height: 100%;
  margin-top: 5px;
  overflow-y: auto;
  font-size: 12px;
  /* margin-right: 20px; */
}

.satellite-icon {
  width: 20px;
  height: 20px;
}

:deep(.custom-table .el-table__header th) {
  background: #000000 !important;
  color: #94a3b8 !important;
  font-size: 12px !important;
  border-bottom: 1px solid rgba(59, 130, 246, 0.3) !important;
}

:deep(.custom-table .el-table__body td) {
  background-color: #000000 !important;
  color: #ffffff !important;
  font-size: 11px !important;
  border-bottom: 1px solid rgba(59, 130, 246, 0.2);
}

:deep(.custom-table .el-table__body tr:hover) {
  background: linear-gradient(to right, #2c4f89 0%, rgb(0, 0, 0)) 100% !important;
}



:deep(.custom-table .el-table__body tr:hover td) {
  background: transparent !important;
}

/* 状态标签样式 */
.status-tag {
  background: #000000;
}

.el-tag {
  border: none;
  font-size: 10px;
}

.status-normal {
  color: #22c55e;
}

.status-normal::before {
  content: '';
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  margin-right: 4px;
  background-color: #22c55e;
}

.status-error {
  color: #ef4444;
}

.status-error::before {
  content: '';
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  margin-right: 4px;
  background-color: #ef4444;
}

.status-warning {
  color: #facc15;
}

.status-warning::before {
  content: '';
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  margin-right: 4px;
  background-color: #facc15;
}

/* 地面系统 */
.ground-system-section {
  display: flex;
  flex-direction: column;
  /* gap: 15px; */
}

.equipment-panel {
  margin-top: 15px;
}

:deep(.el-table__body-wrapper) {
  color: #ffffff;
}

[class*="alert-level_"] {
  color: #ffffff;
}

.alert-level_1 {
  background-color: #ed323e;
}

.alert-level_2 {
  background-color: #eea929;
}

.alert-level_3 {
  background-color: #3270ed;
}

.alert-level_4 {
  background-color: #17a0e0;
}

.alertStatusClassName {
  background-color: #000000;
  background: #000000;
}

[class*="alert-status_"] {
  font-size: 12px;
  /* height:'100px'; */
  background-color: #000000;
}

.alert-status_2 {

  color: #28D86E !important;
  background: black;
}

.alert-status_1 {
  color: red !important;
  background: black;
}

.alert-status_0 {
  color: green !important;
  background: black;
}



:deep(.el-table tr) {
  background: black;
}

:deep(.custom-table .el-table__body tr:hover) {
  background: linear-gradient(to right, #2c4f89 0%, rgb(0, 0, 0)) 100% !important;
}

:deep(.custom-table .el-table__body tr:hover td) {
  background: transparent !important;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 4px;
}

::-webkit-scrollbar-track {
  background: rgba(15, 23, 42, 0.3);
  border-radius: 2px;
}

::-webkit-scrollbar-thumb {
  background: linear-gradient(to bottom, #535353, #535353);
  border-radius: 2px;
  transition: all 0.3s ease;
}

::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(to bottom, rgba(59, 130, 246, 0.4), rgba(96, 165, 250, 0.6));
  box-shadow: 0 0 5px rgba(59, 130, 246, 0.5);
}


































:deep(.el-table--fit .el-table__inner-wrapper:before) {
  width: calc(100%);
  background: black;
}
</style>