<template>
  <div class="left-section">
    <div class="weather-card">
      <div class="weather-item">
        <div class="gradient-text weatherBox1" style="margin-left: 95px">天气</div>
        <div class="weatherBox2">
          <div class="sunnyIcon"></div>
        </div>
      </div>
      <div class="weather-item">
        <div class="gradient-text weatherBox1" style="margin-left: 70px">温度</div>
        <div class="weatherBox2">
          <div class="temperatureIcon"></div>
          <div class="text">{{ temperature }}<span class="text1">℃</span></div>
        </div>
      </div>
      <div class="weather-item">
        <div class="gradient-text weatherBox1" style="margin-left: 110px">湿度</div>
        <div class="weatherBox2">
          <div class="humidityIcon"></div>
          <div class="text">{{ humidity }}<span class="text1">%</span></div>
        </div>
      </div>
      <div class="weather-item">
        <div class="gradient-text weatherBox1" style="margin-left: 18px">风力</div>
        <div class="weatherBox2">
          <div class="windPowerIcon"></div>
          <div class="text">{{ windDirection }} {{ windLevel }}级</div>
        </div>
      </div>
      <div class="weather-item">
        <div class="gradient-text weatherBox1" style="margin-left: 58px">降雨量</div>
        <div class="weatherBox2">
          <div class="rainfall"></div>
          <div class="text">{{ rainfall }}<span class="text1">mm</span></div>
        </div>
      </div>
    </div>
    <div class="event-card">
      <div class="title gradient-text">灾害信息</div>
      <div class="card-content">
        <div class="event-box">
          <div class="event-item">
            <div class="event-icon1"></div>
            <div class="text-box">
              <div class="text1">灾害事件</div>
              <div v-if="eventData.event_title" class="text2">{{ eventData.event_title }}</div>
              <div v-else class="gradient-text" style="font-size: 36px; cursor: pointer">关联事件</div>
            </div>
          </div>
          <div class="event-item">
            <div class="event-icon2"></div>
            <div class="text-box">
              <div class="text1">灾害级别</div>
              <div class="text2">
                <dict-tag v-if="eventData.event_level" :options="mm_event_level" :value="eventData.event_level" />
                <div v-else>暂无数据</div>
              </div>
            </div>
          </div>
          <div class="event-item">
            <div class="event-icon3"></div>
            <div class="text-box">
              <div class="text1">灾害地点</div>
              <div class="text2">{{ eventData.address }}</div>
            </div>
          </div>
        </div>
        <div class="eventBox1">
          <div class="duration-box">
            <div class="icon1"></div>
            <div class="duration-item">
              <div class="gradient-text duration-text">持续时长</div>
              <div class="time-box">
                <span class="time-text">{{ duration.days }}</span>
                <span>天</span>
                <span class="time-text">{{ duration.hours }}</span>
                <span>小时</span>
                <span class="time-text">{{ duration.minutes }}</span>
                <span>分</span>
                <span class="time-text">{{ duration.seconds }}</span>
                <span>秒</span>
              </div>
            </div>
          </div>
          <div class="finish-btn" @click="closeCommand">
            <div class="finish-icon"></div>
            <div class="finish-text">结束处置</div>
          </div>
        </div>
      </div>
    </div>
    <VideoMonitor />
    <CloseCommand
      v-model="closeCommandState.show"
      :title="closeCommandState.title"
      :flag="closeCommandState.flag"
      :event-id="eventId"
      @update:model-value="fetchEventDetail"
    />
    <Communication />
  </div>
</template>
<script lang="ts" setup name="LeftSection">
import { getEventDetail, getWeather } from '@/api/duty/eventing';
import VideoMonitor from '@/views/emergencyCommandMap/LeftSection/VideoMonitor.vue';
import { ref, onMounted, onUnmounted, computed } from 'vue';
import Communication from './Communication.vue';
import CloseCommand from './CloseCommand.vue';

const proxy = getCurrentInstance()?.proxy;
const { mm_event_type, mm_event_level, mm_event_state, region } = toRefs<any>(
  proxy?.useDict('mm_event_type', 'mm_event_level', 'mm_event_state', 'region')
);
const route = useRoute();
const router = useRouter();

const eventId = ref('');

// 天气相关数据
const weatherDescription = ref('');
const temperature = ref('');
const humidity = ref('');
const windDirection = ref('');
const windLevel = ref('');
const rainfall = ref('');

// 灾害事件数据
const eventData = ref({
  event_title: '',
  event_type: '',
  event_level: '',
  address: '',
  event_status: '',
  event_source: '',
  event_time: '',
  report_time: ''
});

// 灾害信息卡片中的持续时间
const duration = computed(() => {
  if (isNaN(elapsedTime.value) || elapsedTime.value < 0) {
    return { days: 0, hours: 0, minutes: 0, seconds: 0 };
  }

  const totalSeconds = Math.floor(elapsedTime.value / 1000);
  const days = Math.floor(totalSeconds / (24 * 3600));
  const hours = Math.floor((totalSeconds % (24 * 3600)) / 3600);
  const minutes = Math.floor((totalSeconds % 3600) / 60);
  const seconds = totalSeconds % 60;

  return { days, hours, minutes, seconds };
});

const closeCommandState = reactive({
  show: false,
  title: '',
  flag: false, // 默认为 false
  eventId: ''
});

const elapsedTime = ref(0);
let intervalId = null;

// 获取天气数据
async function fetchWeatherData() {
  try {
    const response = await getWeather({});
    if (response && response.rows && response.rows.length > 0) {
      const weatherData = response.rows[0];
      weatherDescription.value = weatherData.sk_s;
      temperature.value = weatherData.sk_t;
      humidity.value = weatherData.sk_h;
      windDirection.value = getWindDirection(weatherData.sk_wd);
      windLevel.value = weatherData.sk_wp_level;
      rainfall.value = weatherData.sk_r1h;
    }
  } catch (error) {
    console.error('Failed to fetch weather data:', error);
  }
}

// 根据风向角度获取风向名称
function getWindDirection(angle) {
  const directions = [
    '北',
    '北偏北',
    '北偏东北',
    '东北',
    '东偏东北',
    '东偏东',
    '东',
    '东偏东南',
    '东南',
    '南偏东南',
    '南偏南',
    '南',
    '南偏西南',
    '西南',
    '西偏西南',
    '西偏西',
    '西',
    '西偏西北',
    '西北',
    '北偏西北'
  ];
  const index = Math.floor(((angle + 11.25) % 360) / 22.5);
  return directions[index];
}

const fetchEventDetail = (id: string) => {
  console.log('fetchEventDetail');
  if (id && id !== eventData.value.event_id) {
    // 如果有 id，则正常获取事件详情
    getEventDetail({ event_id: id }).then((res) => {
      eventData.value = res.data;
      // 初始化响应时间
      updateTime();
    });
  }
};

const closeCommand = () => {
  console.log('CloseCommand');
  closeCommandState.title = '结束指挥';
  closeCommandState.eventId = eventId.value;
  closeCommandState.show = true;
};
// 当关闭对话框时，不重置 eventId
watch(closeCommandState.show, (newVal) => {
  if (!newVal) {
    // 对话框关闭时，保持 eventId 的状态
    eventId.value = closeCommandState.eventId;
    // 保持 eventData 的状态
    fetchEventDetail(eventId.value);
  }
});
const updateTime = () => {
  if (eventData.value.event_time && typeof eventData.value.event_time === 'string') {
    const eventTime = new Date(eventData.value.event_time);
    if (!isNaN(eventTime.getTime())) {
      elapsedTime.value = Date.now() - eventTime.getTime();
    } else {
      console.error('Invalid date format:', eventData.value.event_time);
    }
  } else {
    // 如果没有 event_time，则重置响应时间为 0
    elapsedTime.value = 0;
  }
};

onMounted(() => {
  // 从 URL 参数中获取 tempEventId 或 event_id
  const flag = !!route.query.event_id;
  eventId.value = flag ? route.query.event_id : route.query.tempEventId;
  closeCommandState.flag = flag; // 将 flag 赋值给 closeCommandState
  fetchEventDetail(eventId.value);

  fetchWeatherData();
  intervalId = setInterval(updateTime, 1000);
});

onUnmounted(() => {
  if (intervalId) {
    clearInterval(intervalId);
  }
});
</script>

<style lang="scss" scoped>
.left-section {
  width: 1965px;
  height: 100%;
  display: flex;
  flex-direction: column;
  font-size: 36px;
  .weather-card {
    width: 1922px;
    height: 230px;
    background: url('@/assets/images/emergencyCommandMap/weather/weatherBg.png') no-repeat;
    background-size: 100% 100%;
    display: flex;
    align-items: center;
    margin-top: 35px;
    color: #fff;
    .weather-item {
      width: 390px;
      font-size: 48px;
      margin-left: 2px;
      &:first-child {
        width: 295px;
        margin-left: 0;
        padding-left: 15px;
      }
      &:nth-child(3) {
        width: 435px;
      }
      .weatherBox1 {
        position: relative;
        height: 60px;
      }
      .weatherBox2 {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 82px;
        margin-top: 10px;
        .text {
          margin-left: 20px;
          display: flex;
          align-items: flex-end;
          .text1 {
            font-size: 32px;
          }
        }
      }
      .sunnyIcon {
        width: 135px;
        height: 105px;
        background: url('@/assets/images/emergencyCommandMap/weather/sunny.png') no-repeat;
      }
      .temperatureIcon {
        width: 135px;
        height: 105px;
        background: url('@/assets/images/emergencyCommandMap/weather/temperature.png') no-repeat;
      }
      .humidityIcon {
        width: 135px;
        height: 109px;
        background: url('@/assets/images/emergencyCommandMap/weather/humidity.png') no-repeat;
      }
      .windPowerIcon {
        width: 135px;
        height: 116px;
        background: url('@/assets/images/emergencyCommandMap/weather/windPower.png') no-repeat;
      }
      .rainfall {
        width: 135px;
        height: 109px;
        background: url('@/assets/images/emergencyCommandMap/weather/rainfall.png') no-repeat;
      }
    }
  }
  .event-card {
    width: 1965px;
    height: 422px;
    background: url('@/assets/images/emergencyCommandMap/disasterInfo/disasterInfoBg.png') no-repeat;
    background-size: 100% 100%;
    margin-top: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    .title {
      position: absolute;
      top: 12px;
      left: 130px;
      font-size: 60px;
    }
    .card-content {
      margin-top: 60px;
      width: 1904px;
      height: 260px;
      background: url('@/assets/images/emergencyCommandMap/disasterInfo/contentBg.png') no-repeat;
      background-size: 100% 100%;
      padding-left: 120px;
      padding-right: 20px;
      display: flex;
    }
    .eventBox1 {
      display: flex;
      justify-content: right;
      align-items: center;
      font-family: 'BEBAS-1';
      font-size: 38px;
      color: #00e8ff;
      margin-top: -20px;
      .icon1 {
        width: 138px;
        height: 156px;
        background: url('@/assets/images/emergencyCommandMap/disasterInfo/time.png') no-repeat;
        margin-top: -50px;
      }
    }
    .event-box {
      display: flex;
      align-items: flex-start;
      color: #fff;
      flex-wrap: wrap;
      width: 578px;
      .event-item {
        font-size: 38px;
        margin-top: -20px;
        display: flex;
        width: 317px;
        position: relative;
        padding-left: 120px;
        margin-left: -30px;
        &:last-child {
          width: 574px;
        }
        .event-icon1,
        .event-icon2,
        .event-icon3 {
          position: absolute;
          top: 0;
          left: 0;
          flex-shrink: 0;
          width: 149px;
          height: 149px;
        }
        .event-icon1 {
          background: url('@/assets/images/emergencyCommandMap/disasterInfo/icon1.png');
        }
        .event-icon2 {
          height: 150px;
          background: url('@/assets/images/emergencyCommandMap/disasterInfo/icon2.png');
        }
        .event-icon3 {
          background: url('@/assets/images/emergencyCommandMap/disasterInfo/icon3.png');
        }
        .text-box {
          margin-top: 35px;
          .text1 {
            font-size: 32px;
            line-height: 32px;
            color: #a7ccdf;
          }
          .text2 {
            font-size: 36px;
            line-height: 36px;
            color: #ffffff;
          }
        }
      }
    }
  }
  .duration-box {
    width: 662px;
    height: 140px;
    margin-top: 160px;
    margin-left: 22px;
    background: url('@/assets/images/emergencyCommandMap/disasterInfo/durationBg.png');
    display: flex;
    .text {
      font-size: 44px;
    }
    .duration-item {
      margin-top: -22px;
      margin-left: 10px;
    }
    .time-box {
      font-size: 30px;
      color: #ffffff;
      margin-top: -10px;
      .time-text {
        /* 设置字体透明 */
        color: transparent;
        /* 设置线性渐变，从红色渐变到蓝色 */
        background-image: linear-gradient(to bottom, #fff 20%, #f6d6a7 50%, #e48406 100%);
        /* 使用 -webkit-background-clip 属性将背景剪裁至文本形状 */
        -webkit-background-clip: text;
        /* 非Webkit内核浏览器需要使用标准前缀 */
        background-clip: text;
        /* 把当前元素设置为行内块，以便能够应用背景 */
        display: inline-block;
        font-family: 'BEBAS-1';
        font-size: 50px;
        width: 100px;
        text-align: center;
        &:first-child {
          width: 50px;
          text-align: left;
        }
      }
    }
  }
  .finish-btn {
    display: flex;
    flex-direction: column;
    margin-top: -160px;
    justify-content: center;
    cursor: pointer;
    margin-top: 35px;
    margin-left: 80px;
    .finish-icon {
      width: 97px;
      height: 107px;
      background: url('@/assets/images/emergencyCommandMap/disasterInfo/finishBtn.png');
    }
    .finish-text {
      font-size: 30.58px;
      /* 设置字体透明 */
      color: transparent;
      /* 设置线性渐变，从红色渐变到蓝色 */
      background-image: linear-gradient(to bottom, #fff 20%, #ff2f3c 50%, #ff2f3c 100%);
      /* 使用 -webkit-background-clip 属性将背景剪裁至文本形状 */
      -webkit-background-clip: text;
      /* 非Webkit内核浏览器需要使用标准前缀 */
      background-clip: text;
      /* 把当前元素设置为行内块，以便能够应用背景 */
      display: inline-block;
      font-family: 'YouSheBiaoTiHei';
    }
  }
}

@keyframes slide {
  0% {
    transform: translateX(-80%);
  }
  80% {
    transform: translateX(92px);
  }
  80% {
    transform: translateX(0);
  }
}
</style>
