<script setup lang="ts">
import DownloadKLNPortal from './components/DownloadKLNPortal.vue'
import ChangePasswordDialog from './components/ChangePasswordDialog.vue'
import LogoutDialog from './components/LogoutDialog.vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/modules/user'
import { useHeaderSearch } from '@/stores/modules/headerSearch'
import { onBeforeRouteUpdate } from 'vue-router'
import { useLoadingState } from '@/stores/modules/loadingState'
import { useThemeStore } from '@/stores/modules/theme'
import { useNotificationMessage } from '@/stores/modules/notificationMessage'
import NotificationDrawer from './components/NotificationDrawer.vue'
import TrainingCard from './components/TrainingCard.vue'
import emitter from '@/utils/bus'

const notificationMsgStore = useNotificationMessage()
const themeStore = useThemeStore()
const userStore = useUserStore()
const route = useRoute()
const router = useRouter()
const headerSearch = useHeaderSearch()

const trainingCardRef = ref()

// 切换系统主题颜色
const toggleThemeMode = (theme: string) => {
  themeStore.toggleTheme(theme, true)
}

const searchValue = ref('')
// 用于判断是否在搜索后跳转页面，跳转后清空搜索框的值
const isJumpPageBySearch = ref(false)
const handleSearch = () => {
  if (!searchValue.value) {
    return
  }
  // 先判断是否登录
  // 未登录
  if (!userStore.isLogin) {
    $api.getPublicTrackingDetail({ reference_number: searchValue.value }).then((res) => {
      if (res.code === 200) {
        const { data } = res
        if (route.path === '/public-tracking') {
          isJumpPageBySearch.value = false
        } else {
          isJumpPageBySearch.value = true
        }
        if (data.msg === 'No matches') {
          headerSearch.setSearchData({
            searchValue: searchValue.value,
            searchResult: 'error'
          })
          router.push({
            name: 'Public Tracking'
          })
        } else if (data.msg === 'Multiple results') {
          headerSearch.setSearchData({
            searchValue: searchValue.value,
            searchResult: 'multiple'
          })
          router.push({
            name: 'Public Tracking'
          })
        } else {
          sessionStorage.setItem('publicTrackingData', JSON.stringify(data.data))
          router.push(`/public-tracking/detail?searchNo=${searchValue.value}`)
        }
      }
    })
  } else {
    const trackingTableLoadingState = useLoadingState()
    trackingTableLoadingState.setTrackingTableLoading(true)
    // 已登录
    $api
      .getTrackingTableData({
        _textSearch: searchValue.value
      })
      .then((res) => {
        if (res.code === 200) {
          // 如果是在tracking页面搜索，那么isJumpPageBySearch不用置为true，跳转路由后直接清空搜索框
          if (route.path === '/tracking') {
            isJumpPageBySearch.value = false
          } else {
            isJumpPageBySearch.value = true
          }
          headerSearch.setSearchData({
            searchValue: searchValue.value,
            searchResult: '',
            trackingData: res.data
          })
          router.push({
            name: 'Tracking'
          })
        }
      })
      .finally(() => {
        trackingTableLoadingState.setTrackingTableLoading(false)
      })
  }
}
onBeforeRouteUpdate((to, from, next) => {
  if (isJumpPageBySearch.value) {
    isJumpPageBySearch.value = false
  } else {
    searchValue.value = ''
  }
  next()
})

const downloadKLNPortalRef = ref()
const handleDownload = () => {
  downloadKLNPortalRef.value.openDialog()
}

const changePasswordDialogRef = ref()
const handleChangePassword = () => {
  changePasswordDialogRef.value.openDialog()
}

const userManualLoading = ref(false)
const handleUserManual = () => {
  userManualLoading.value = true
  try {
    $api
      .getUserGuide()
      .then(async (res) => {
        if (res.status !== 200) {
          ElMessageBox.alert('The request failed. Please try again later', 'Prompt', {
            confirmButtonText: 'OK',
            confirmButtonClass: 'el-button--dark'
          })
          return
        }
        if (res.data?.code === 403) {
          sessionStorage.clear()
          emitter.emit('login-out');
          router.push('/login')
          userStore.logout()
          ElMessage.warning({
            message: 'Please log in to use this feature.',
            grouping: true
          })
          return
        }
        // 创建一个 Blob 对象
        const blob = new Blob([res.data], { type: 'application/pdf' })
        const url = URL.createObjectURL(blob)
        // 在新标签页中打开 PDF
        window.open(url, '_blank')
      })
      .finally(() => {
        userManualLoading.value = false
      })
  } catch (error) {
    ElMessageBox.alert('The request failed. Please try again later', 'Prompt', {
      confirmButtonText: 'OK',
      confirmButtonClass: 'el-button--dark'
    })
  }
}

const logoutDialogRef = ref()

const handleLogout = () => {
  logoutDialogRef.value.openDialog()
}

const handleLogin = () => {
  router.push('/login')
}

// 定义是否显示popover的状态
const isPopoverVisible = ref(false)

// 切换popover显示状态的方法
const togglePopover = () => {
  isPopoverVisible.value = !isPopoverVisible.value
}

// 关闭popover的方法
const closePopover = () => {
  isPopoverVisible.value = false
}

const notificationDrawer = ref(false)

onBeforeRouteUpdate((to, from, next) => {
  if (from.name === 'Login' && userStore.isLogin) {
    notificationMsgStore.hasUnreadMessages()
  }
  next()
})
onMounted(() => {
  // 检查是否有新消息 (在页面刷新时重新检查)
  if (userStore.isLogin) {
    notificationMsgStore.hasUnreadMessages()
  }
})
</script>

<template>
  <div
    class="layout-toolbar"
    v-loading.fullscreen.lock="userManualLoading"
    element-loading-text="Loading..."
    element-loading-custom-class="element-loading"
    element-loading-background="rgb(43, 47, 54, 0.7)"
  >
    <VBreadcrumb></VBreadcrumb>
    <TrainingCard ref="trainingCardRef"></TrainingCard>
    <div class="right-info">
      <el-input
        v-model="searchValue"
        size="large"
        @keyup.enter="handleSearch"
        placeholder="Enter Booking/HBL/PO/Container No."
      >
        <template #prefix>
          <span style="margin-top: -1px" class="font_family icon-icon_search_b"></span>
        </template>
      </el-input>
      <div class="notice-icon" v-if="userStore.isLogin">
        <span v-if="notificationMsgStore.hasNewMsg" class="unread-tip-icon"></span>
        <el-button
          style="height: 40px; width: 40px; margin-right: 0px"
          class="el-button--text"
          @click="notificationDrawer = true"
        >
          <span class="font_family icon-icon_notice_b" style="font-size: 18px"></span>
        </el-button>
      </div>
      <!-- 
      <span class="font_family icon-icon_language_b" style="font-size: 16px"></span> -->
      <el-popover
        placement="bottom-end"
        :width="400"
        trigger="click"
        :visible="isPopoverVisible"
        popper-class="toggle-theme-popover"
        @show="isPopoverVisible = true"
        @hide="isPopoverVisible = false"
      >
        <div>
          <!-- Popover content remains the same -->
          <div class="header">
            <span class="title">Themes</span>
            <el-button @click="closePopover" class="close-icon el-button--text">
              <div class="font_family icon-icon_reject_b"></div>
            </el-button>
          </div>
          <div class="tips">
            Customize your workspace by changing the appearance and theme color
          </div>
          <div class="picture-module">
            <div class="item" :class="{ active: themeStore.theme === 'light' }">
              <img @click="toggleThemeMode('light')" src="./images/light.png" alt="" />
              <div v-if="themeStore.theme === 'light'" class="selected-icon">
                <span class="font_family icon-icon_confirm_b"></span>
              </div>
            </div>
            <div class="item" :class="{ active: themeStore.theme === 'dark' }">
              <img @click="toggleThemeMode('dark')" src="./images/dark.png" alt="" />
              <div v-if="themeStore.theme === 'dark'" class="selected-icon">
                <span class="font_family icon-icon_confirm_b"></span>
              </div>
            </div>
          </div>
          <div class="btn-module">
            <div
              class="btn-item"
              @click="toggleThemeMode('light')"
              :class="{ active: themeStore.theme === 'light' }"
            >
              <span class="font_family icon-icon_light_b"></span>Light
            </div>
            <div
              class="btn-item"
              @click="toggleThemeMode('dark')"
              :class="{ active: themeStore.theme === 'dark' }"
            >
              <span class="font_family icon-icon_dark_b"></span>Dark
            </div>
          </div>
        </div>

        <!-- Tooltip is now inside the Popover, and it will only show when the Popover is open -->
        <template #reference>
          <el-tooltip
            popper-class="theme-popper-class"
            effect="dark"
            content="Themes"
            placement="top"
            :offset="4"
            trigger="hover"
          >
            <el-button
              style="height: 40px; width: 40px"
              class="el-button--text"
              @click="togglePopover"
            >
              <span class="font_family icon-icon_themes_b" style="font-size: 16px"></span>
            </el-button>
          </el-tooltip>
        </template>
      </el-popover>

      <el-popover
        placement="bottom-end"
        :width="256"
        trigger="click"
        popper-class="user-config-popover"
      >
        <div class="title">
          <div class="avatar">
            <span>{{ userStore.userName?.slice(0, 1) }}</span>
          </div>
          <span class="name">{{ userStore.userName }}</span>
        </div>
        <div class="options">
          <div class="item" @click="handleChangePassword">
            <span class="font_family icon-icon_password_b"></span>
            Change Password
          </div>
          <div class="item" @click="handleUserManual">
            <span class="font_family icon-icon_manual_b"></span>
            User Manual
          </div>
          <div class="item" @click="handleLogout">
            <span class="font_family icon-icon_export_b"></span>
            Logout
          </div>
        </div>
        <template #reference>
          <div class="header-avatar" v-if="userStore.isLogin">
            <div>{{ userStore.userName.slice(0, 1) }}</div>
          </div>
        </template>
      </el-popover>
      <el-button
        v-if="!userStore.isLogin"
        class="el-button--main el-button--pain-theme"
        style="padding: 8px 10px; margin-right: 20px; margin-left: 0"
        plain
        @click="handleDownload"
      >
        <span class="font_family icon-icon_download_b" style="margin-right: 4px"></span>
        Download KLN Portal
      </el-button>
      <el-button
        v-if="!userStore.isLogin"
        class="el-button--main"
        style="margin-left: -10px"
        @click="handleLogin"
        >Log in</el-button
      >
    </div>
    <DownloadKLNPortal ref="downloadKLNPortalRef"></DownloadKLNPortal>
    <ChangePasswordDialog ref="changePasswordDialogRef"></ChangePasswordDialog>
    <LogoutDialog ref="logoutDialogRef"></LogoutDialog>
    <NotificationDrawer v-model="notificationDrawer"></NotificationDrawer>
  </div>
</template>

<style lang="scss" scoped>
.header-avatar {
  width: 24px;
  height: 24px;
  margin-left: 8px;
  text-align: center;
  border-radius: 50%;
  background-color: var(--color-theme);
  cursor: pointer;
  & > div {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 24px;
    color: #fff;
    font-size: 16px;
    font-weight: 700;
  }
}
.layout-toolbar {
  display: flex;
  justify-content: space-between;
  position: relative;
  height: 100%;
}
.right-info {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  gap: 8px;
  .el-input {
    height: 32px;
    width: 400px;
    :deep(.el-input__wrapper) {
      padding-left: 8px;
      border-radius: 15px;
      color: var(--color-border);
      background-color: var(--color-table-header-bg);
      .el-input__icon {
        font-size: 16px;
        font-weight: 600;
        color: var(--color-neutral-1);
      }
    }
    :deep(.el-input__inner) {
      height: 32px;
    }
  }

  .notice-icon {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 2px;
    cursor: pointer;
    .unread-tip-icon {
      position: absolute;
      top: 9px;
      right: 8px;
      width: 5px;
      height: 5px;
      border-radius: 50%;
      background-color: var(--color-theme);
    }
  }
}
</style>
<style lang="scss">
div.el-popover.el-popper.toggle-theme-popover {
  width: 400px;
  height: 278px;
  padding: 16px;
  inset: 56px 52.8px auto auto !important;
  .el-popper__arrow {
    display: none;
  }
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
    .title {
      font-size: 18px;
      font-weight: 700;
    }
    .close-icon {
      width: 24px;
      cursor: pointer;
    }
  }
  .tips {
    color: var(--color-neutral-2);
  }
  .picture-module {
    display: flex;
    justify-content: center;
    gap: 6px;
    margin-top: 16px;
    .item {
      position: relative;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 174px;
      height: 108px;
      padding: 8px;
      img {
        width: 154px;
        height: 90px;
        cursor: pointer;
      }
      &.active {
        border: 2px solid var(--color-theme);
        border-radius: 6px;
      }
      .selected-icon {
        position: absolute;
        bottom: 8px;
        left: 50%;
        transform: translateX(-50%);
        height: 16px;
        span {
          height: 16px;
          width: 16px;
          padding: 1px 1px 0 0;
          background-color: var(--color-theme);
          color: #fff;
          border-radius: 50%;
        }
      }
    }
  }
  .btn-module {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 368px;
    height: 40px;
    margin-top: 10px;
    padding: 0 8px;
    background-color: var(--color-toggle-btn-module-bg);
    border-radius: 6px;
    .btn-item {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 4px;
      width: 180px;
      height: 32px;
      border-radius: 6px;
      color: var(--color-neutral-2);
      cursor: pointer;
      &.active {
        background-color: var(--color-toggle-btn-module-active-bg);
        color: var(--color-neutral-1);
      }
    }
  }
}
div.el-popover.el-popper.user-config-popover {
  padding: 8px;
  width: 240px;
  border-radius: 12px;
  .title {
    display: flex;
    align-items: center;
    gap: 8px;
    height: 70px;
    border-bottom: 1px solid var(--color-user-config-title-bottom-border);
    & > .avatar {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 48px;
      height: 48px;
      border-radius: 50%;
      text-align: center;
      background-color: var(--color-theme);
      span {
        display: block;
        color: #fff;
        height: 32px;
        line-height: 32px;
        font-size: 32px;
        font-weight: 700;
      }
    }
  }
  .options {
    .item {
      display: flex;
      align-items: center;
      padding-left: 8px;
      gap: 8px;
      height: 40px;
      line-height: 40px;
      &:hover {
        background-color: var(--color-mune-active-bg);
        border-radius: 6px;
        cursor: pointer;
      }
    }
  }
}
div.el-popper.theme-popper-class {
  padding: 3px 4px;
}
</style>
