<template>
  <div class="container">
    <div class="container-header">
      <div ref="searchBoxRef" class="search-box">
        <van-search
          v-model="queryParams.keywords"
          class="common-search"
          :left-icon="searchImg"
          :right-icon="closeImg"
          placeholder="请输入搜索内容"
          @search="on_search_keyword"
          @click-right-icon.stop="on_search_cancel"
        />
        <div v-show="showSearch" class="search-list">
          <van-list
            v-model:loading="loading"
            v-model:error="error"
            error-text="请求失败，点击重新加载"
            :finished="finished"
            finished-text="没有更多了"
            :immediate-check="false"
            @load="getSearchList"
          >
            <div
              v-for="(item, index) in searchList"
              :key="index"
              class="item"
              @click="handleClickItem(item)"
            >
              {{ item.name }}
            </div>
          </van-list>
        </div>
      </div>
    </div>
    <div class="notice-bar" v-if="noticeBarState.show">
      <!-- 静态的预警信息 -->
      <div class="notice-item">
        <div class="notice-header">
          <div class="notice-label-box">
            <div :class="['notice-label', get_info_type_color(noticeBarState.latestMessages.msg_type)]">
              {{ noticeBarState.latestMessages.msg_type }}
            </div>
          </div>
          <!-- 查看更多的链接 -->
          <div class="notice-more" @click="goToInformationReception">查看更多 >></div>
        </div>
        <div class="notice-content" @click="handleInfo(noticeBarState.latestMessages)">
          {{ noticeBarState.latestMessages.content }}
        </div>
        <div class="notice-time">{{ noticeBarState.latestMessages.recv_time }}</div>
      </div>
    </div>
    <div class="container-content">
      <div class="padding-content">
        <van-grid :column-num="2">
          <van-grid-item
            v-for="(item, index) in menu"
            :key="index"
            @click="handleClickMenu(item.url)"
          >
            <div class="card">
              <div :class="item.icon" />
              <van-badge :content="item.num" max="99" :show-zero="false">
                <div class="card-title">{{ item.name }}</div>
              </van-badge>
            </div>
          </van-grid-item>
        </van-grid>
        <div class="app_panel">
          <div class="app_panel_title">综合应用</div>
          <div v-for="(item, index) in menu2" :key="index" class="box">
            <div class="box-title">{{ item.name }}</div>
            <div class="box-content">
              <div
                v-for="(item2, index2) in item.children"
                :key="index2"
                class="box-item"
                @click="handleClickMenu(item2.url)"
              >
                <img class="icon" :src="getImageUrl(item2.icon)" alt="" />
                <span>{{ item2.name }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <OnlineRollCall />
  </div>
</template>

<script lang="ts" setup>
import { onClickOutside } from "@vueuse/core";
import { onMounted, onUnmounted, reactive, ref } from "vue";
import { selectTask } from "@/api/emergencyCommandMap/JointDuty";
import searchImg from "@/assets/images/search.png";
import { useRouter } from "vue-router";
import closeImg from "@/assets/images/close.png";
import { getPointInfoComprehensiveSearch } from "@/api/globalMap";
import OnlineRollCall from "@/components/OnlineRollCall/index.vue";
import { MsgCenterList, getUnreadMsgCount } from "@/api/InformationReception/InformationReception";

const router = useRouter();
const noticeBarState = reactive({
  show: false,
  latestMessages: {
    msg_type: '',
    content: '',
    recv_time: ''
  }
});

const goToInformationReception = () => {
  router.push({ name: "InformationReception" });
};

const get_info_type_color = (val) => {
  if(val == "任务消息") {
    return "info_type_2"
  }
  else if(['预警信息', '灾情信息', '灾情信息', '指挥救援', '公众防范'].includes(val)) {
    return "info_type_3"
  }
  return "info_type_0"
}

// 菜单数据
const menu = ref([
  { name: "巡查工作", icon: "icon1", num: 0, url: "inspectionWork" },
  { name: "风险防控", icon: "icon2", num: 0, url: "riskManagement" },
  { name: "数据管理", icon: "icon3", num: 0, url: "rescueManagement" },
  { name: "在线点名", icon: "icon4", num: 0, url: "rollCallRecord2" }
]);

// 综合应用菜单
const menu2 = ref([
  {
    name: "自然灾害风险监测",
    children: [
      { name: '预警态势', icon: 'monitor', url: 'WarningSituation' },
      { name: '大风灾害', icon: 'wind', url: 'GaleDisaster' },
      { name: '森林火灾', icon: 'forestFire', url: 'ForestFireWarn' },
      { name: '台风实况', icon: 'typhoon', url: 'TyphoonPath' },
      { name: '水库监测', icon: 'hydrology', url: 'ReservoirMonitor' },
      { name: '河道监测', icon: 'riverMonitor', url: 'RiverMonitor' }
    ]
  },
  {
    name: "应急事件场景专题",
    children: [
      { name: "防风防汛", icon: "accident", url: "WindAndFloodPrevention" },
      { name: "地质灾害", icon: "nature", url: "GeologicalDisaster" },
      { name: "森林防火", icon: "forestFire2", url: "ForestFirePrevention" },
      { name: "危化品事故", icon: "hazardousChemicals", url: "HazardousChemicals" },
      { name: "非煤矿山", icon: "nonCoalMine", url: "NonCoalMine" },
      { name: "城市应急", icon: "city", url: "CityEmergencyEvent" }
    ]
  }
]);
const handleClickMenu = url => {
  if (!url) return;
  router.push({ name: url });
};
const getImageUrl = name => {
  return new URL(`../../assets/images/index/${name}.png`, import.meta.url).href;
};

// 请求数据
const initData = async() => {
  let res = await MsgCenterList({})
  const data = res.data || [];
  if (data.length > 0) {
    noticeBarState.latestMessages = data[0]
    noticeBarState.show = true;
  }
}
const handleInfo = (item) => {
  router.push(item.detail.detail_url);
  //router.push("/infoDetails?id=" + item.id);
}

// 搜索
const searchBoxRef = ref();
let showSearch = ref();
const total = ref(0);
let loading = ref(false);
let error = ref(false);
let finished = ref(false);
const queryParams = reactive({
  page: 0,
  page_size: 15,
  keywords: ""
});
const searchList = ref([]);
onClickOutside(searchBoxRef, event => {
  showSearch.value = false;
});
const getSearchList = () => {
  if (!queryParams.keywords) {
    return (loading.value = false);
  }
  queryParams.page++;
  getPointInfoComprehensiveSearch(queryParams)
    .then(res => {
      const items = res.data.list || [];
      total.value = res.data.total;
      if (queryParams.page == 1) {
        searchList.value = [];
      }
      items.forEach(val => {
        searchList.value.push(val);
      });
      finished.value = queryParams.page_size * queryParams.page >= total.value;
      showSearch.value = true;
    })
    .catch(() => {
      error.value = true;
      finished.value = false;
    })
    .finally(() => {
      loading.value = false;
    });
};
const on_search_keyword = val => {
  queryParams.keywords = val;
  queryParams.page = 0;
  getSearchList();
};
const on_search_cancel = () => {
  showSearch.value = false;
  queryParams.keywords = "";
  queryParams.page = 0;
  finished.value = false;
  searchList.value = [];
};
const handleClickItem = item => {
  showSearch.value = false;
  queryParams.keywords = "";
  queryParams.page = 0;
  finished.value = false;
  searchList.value = [];
};

// 设置定时器，刷新统计数
const fetchInterval = process.env.NODE_ENV === 'development' ? 60000 : 3000; // 每60秒刷新一次(刷新太频繁影响调试)
let intervalId: any | null = null;
const startFetchingData = () => {
  if (!intervalId) {
    intervalId = setInterval(() => {
      fetchData();
    }, fetchInterval);
  }
};

const stopFetchingData = () => {
  if (intervalId) {
    clearInterval(intervalId);
    intervalId = null;
  }
};

const fetchData = async () => {
  getUnreadMsgCount({"msg_types": "巡查工作,在线点名,风险防控,数据管理"}).then((res)=>{
    menu.value.forEach((v)=>{
      let obj = res.data.find(item=>item.name === v.name);
      if(obj) {
        v.num = obj.num;
      }
    })
  })
}

onMounted(() => {
  initData();

  // 统计数
  nextTick(()=>{
    fetchData();
  });
  startFetchingData();
});
onUnmounted(() => {
  stopFetchingData();
});
</script>

<style lang="scss" scoped>
.container {
  display: block;
  width: 100%;
  height: 100%;
  padding-bottom: 20px;
}
.container-header {
  width: 100%;
  height: 370px;
  background: url("@/assets/images/index/banner2.png") no-repeat;
  background-size: 100% 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  align-items: center;
  padding-bottom: 70px;
  .search-box {
    width: 100%;
    position: relative;
  }
  .van-search {
    width: 100%;
  }
}
.container-content {
  .padding-content {
    padding: 0 16px;
  }
  .van-hairline--top:after {
    border-top-width: 0 !important;
  }
  :deep(.van-grid) {
    .van-grid-item {
      &:nth-child(1) {
        padding-right: 12px;
        padding-bottom: 12px;
      }
      &:nth-child(2) {
        padding-bottom: 12px;
      }
      &:nth-child(3) {
        padding-right: 12px;
      }
      .card {
        width: 100%;
        height: 89px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 9px 15px 9px 0;
        font-size: 14px;
        background: url(@/assets/images/index/cardBg1.png) no-repeat;
        background-size: 100% 100%;
        &:nth-child(2) {
          background: url(@/assets/images/index/cardBg2.png) no-repeat;
          background-size: 100% 100%;
        }
        &:nth-child(3) {
          background: url(@/assets/images/index/cardBg3.png) no-repeat;
          background-size: 100% 100%;
        }
        &:nth-child(4) {
          background: url(@/assets/images/index/cardBg4.png) no-repeat;
          background-size: 100% 100%;
        }
        .card-title {
          font-size: 14px;
          font-weight: bold;
          letter-spacing: 0.78px;
          color: #414f64;
        }
      }
      .icon1 {
        background: url(@/assets/images/index/icon5.png) no-repeat;
      }
      .icon2 {
        background: url(@/assets/images/index/icon6.png) no-repeat;
      }
      .icon3 {
        background: url(@/assets/images/index/icon7.png) no-repeat;
      }
      .icon4 {
        background: url(@/assets/images/index/icon8.png) no-repeat;
      }
      .icon1,
      .icon2,
      .icon3,
      .icon4 {
        width: 50px;
        height: 49px;
        background-size: 100% 100%;
        margin-left: 11px;
      }
    }
    .van-grid-item__content {
      padding: 0;
      background: transparent;
      &::after {
        border: none;
      }
    }
  }
}

.app_panel {
  padding-top: 12px;
  .app_panel_title {
    height: 26px;
    font-weight: bold;
    font-size: 18px;
    color: #414f64;
    letter-spacing: 0;
    margin-bottom: 4px;
  }
  .box {
    width: 100%;
    height: 152px;
    background: url("@/assets/images/index/boxBg.png") no-repeat;
    background-size: 100% 100%;
    margin-bottom: 12px;
    display: flex;
    flex-direction: column;
    &:last-child {
      margin-bottom: 0;
    }
    .box-title {
      font-size: 12px;
      color: #3687fe;
      padding: 3px 6px 0;
    }
    .box-content {
      flex: 1;
      display: flex;
      flex-wrap: wrap;
      padding-top: 3px;
      .box-item {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        min-width: 20%;
        font-size: 12px;
        .icon {
          width: 32px;
          height: 34px;
        }
      }
    }
  }
}
.search-list {
  position: absolute;
  top: 50px;
  left: 0;
  z-index: 9;
  width: 100%;
  height: calc(100vh - 400px);
  overflow-y: auto;
  background-color: #ffffff;
  border-top: 1px solid #eeeeee;
  .item {
    padding: 8px 15px;
    border-bottom: 1px solid #eeeeee;
  }
}
.common-search {
  :deep(.van-search__content) {
    border-radius: 15px;
    border: none !important;
  }
  :deep(.van-field__left-icon) {
    .van-icon__image {
      width: 12px;
      height: 12px;
    }
  }
  :deep(.van-field__right-icon) {
    width: 30px;
    height: 30px;
    padding: 0;
    .van-icon__image {
      width: 30px;
      height: 30px;
    }
  }
}
.notice-bar {
  width: 100%;
  background-color: #f4f8ff;
  padding: 0 10px 10px;
  border-radius: 5px;
  margin-bottom: 10px;
  margin-top: -60px;
  border: 1px solid #EEEEEE;
}

.notice-item {
  margin-bottom: 10px;
  &:last-child {
    margin-bottom: 0;
  }
  .notice-header {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    position: relative;
    margin-bottom: 10px;
  }
}

.notice-label-box {
  position: absolute;
  top: -3px;
  left: 0;
  background-color: #ffffff;
  padding: 5px;
  transform: skewX(-20deg); /* 斜切变形 */
  .notice-label {

    font-size: 14px;
    transform: skewX(20deg);
  }

  .info_type_0 {
    color: #FFAF00;
  }

  .info_type_1 {
    color: #FF1818;
  }

  .info_type_2 {
    color: #2c81ff;
  }

  .info_type_3 {
    color: #FF9F9F;
  }

  .info_type_4 {
    color: #A4D3FF;
  }
}


.notice-content {
  color: #414F64;
  font-size: 14px;
  line-height: 22px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.notice-time {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.45);
  width: 100%;
  text-align: right;
  line-height: 22px;
}

.notice-more {
  margin-top:4px;
  font-size: 14px;
  color: #2C81FF;
  cursor: pointer;
}


</style>
