<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'

const userStore = useUserStore()
const route = useRoute()
const router = useRouter()
const headerSearch = useHeaderSearch()

const searchValue = ref('')
// 用于判断是否在搜索后跳转页面，跳转后清空搜索框的值
const isJumpPageBySearch = ref(false)
const handleSearch = () => {
  if (!searchValue.value) {
    return
  }
  // 先判断是否登录
  // 未登录
  if (!localStorage.getItem('username')) {
    $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 handleUserManual = () => {
  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
      }
      // 创建一个 Blob 对象
      const blob = new Blob([res.data], { type: 'application/pdf' })
      const url = URL.createObjectURL(blob)
      // 在新标签页中打开 PDF
      window.open(url, '_blank')
    })
  } 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')
}
</script>

<template>
  <div class="layout-toolbar">
    <VBreadcrumb></VBreadcrumb>
    <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>
      <!-- <span class="font_family icon-icon_notice_b" style="font-size: 18px"></span>
      <span class="font_family icon-icon_language_b" style="font-size: 16px"></span> -->

      <el-popover
        placement="bottom-end"
        :width="256"
        trigger="click"
        popper-class="user-config-popover"
        content="this is content, this is content, this is content"
      >
        <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.username">
            <span style="">{{ userStore.username?.slice(0, 1) }}</span>
          </div>
        </template>
      </el-popover>
      <el-button
        v-if="!userStore.username"
        class="el-button--main"
        style="padding: 8px 10px"
        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.username"
        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>
  </div>
</template>

<style lang="scss" scoped>
.header-avatar {
  width: 24px;
  height: 24px;
  padding: 2px;
  text-align: center;
  border-radius: 50%;
  background-color: var(--color-theme);
  cursor: pointer;
  & > span {
    display: block;
    height: 16px;
    color: #fff;
    font-size: 16px;
    font-weight: 700;
  }
}
.layout-toolbar {
  display: flex;
  justify-content: space-between;
  height: 100%;
}
.right-info {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 24px;
  height: 100%;

  .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;
    }
  }
}
</style>
<style lang="scss">
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 #eeeeed;
    & > .avatar {
      width: 48px;
      height: 48px;
      padding-top: 7px;
      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;
      }
    }
  }
}
</style>
