<script setup lang="ts">
import { useRouter } from 'vue-router'
import { useHeaderSearch } from '@/stores/modules/headerSearch'
import SlideVerify from './components/SlideVerify.vue'
import CryptoJS from 'crypto-js'
import dayjs from 'dayjs'

const router = useRouter()

const headerSearch = useHeaderSearch()
const searchResult = ref('')

const inputVModel = ref('')
// 从 store 中获取数据并绑定到输入框
const headerSearchdData = computed(() => headerSearch.searchValue)

// 监听 sharedData 的变化并更新 inputValue
headerSearchdData.value && (inputVModel.value = headerSearchdData.value)
searchResult.value = headerSearch.searchResult
headerSearch.clearSearchData()
// 当 sharedData 发生变化时，更新 inputValue
watch(
  () => headerSearchdData.value,
  (newData) => {
    if (newData) {
      inputVModel.value = headerSearchdData.value
      searchResult.value = headerSearch.searchResult
      headerSearch.clearSearchData()
    }
  }
)

const loading = ref(false)
const confirmVerifyStatus = ref('')
const handleSearchNo = () => {
  if (!inputVModel.value) {
    return
  }
  loading.value = true
  $api
    .getPublicTrackingDetail({
      reference_number: inputVModel.value,
      verifcation_code: confirmVerifyStatus.value
    })
    .then((res) => {
      if (res.code === 200) {
        const { data } = res

        if (data.msg === 'No matches') {
          searchResult.value = 'error'
        } else if (data.msg === 'Multiple results') {
          searchResult.value = 'multiple'
        } else {
          sessionStorage.setItem('publicTrackingData', JSON.stringify(data.data))
          router.push(`/public-tracking/detail?searchNo=${inputVModel.value}`)
        }
      } else if (res.code === 400) {
        const { data } = res
        if (data.msg === 'visit limit') {
          isShowSliderVerification.value = true
          nextTick(() => {
            sliderVerificationRef.value?.openDialog()
          })
        }
      }
    })
    .finally(() => {
      loading.value = false
      confirmVerifyStatus.value = ''
    })
}

const sliderVerificationRef = ref()
const isShowSliderVerification = ref(false)
const confirmVerification = () => {
  const pwd = dayjs().unix()
  confirmVerifyStatus.value = encryptPassword(pwd)
  handleSearchNo()
}

const secretKey = 'fT5!R1k$7Mv@4Q9X'
const fixedIv = '1234567890123456' // 固定的初始化向量，长度为16字符

// AES 加密函数
const encryptPassword = (password) => {
  const key = CryptoJS.enc.Utf8.parse(secretKey) // 解析密钥
  const iv = CryptoJS.enc.Utf8.parse(fixedIv) // 解析IV
  const encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(password), key, { iv: iv })
  return encrypted.toString()
}
</script>

<template>
  <div class="public-tracking-search" v-vloading="loading">
    <div class="search-info">
      <div class="title">Tracking</div>
      <el-input
        class="public-tracking-search-input"
        v-model="inputVModel"
        @focus="searchResult = ''"
        @keyup.enter="handleSearchNo"
        placeholder="Enter Booking/HBL/MBL/PO/Container No."
      >
        <template #append>
          <span
            @click="handleSearchNo"
            style="padding: 0 12px; cursor: pointer"
            class="font_family icon-icon_search_b"
          ></span>
        </template>
      </el-input>
      <div class="empty">
        <VEmpty class="error-empty" v-if="searchResult === 'error'">
          <template #suggestion>
            <div class="suggestion-info">
              <p>We support the following references number to find shipment:</p>
              <p>
                · Tracking No./Booking No./HAWB No./MAWB No./PO No./Quote No./Invoice No./Container
                No.
              </p>
            </div>
          </template>
        </VEmpty>
        <VEmpty class="multiple-empty" v-else-if="searchResult === 'multiple'">
          <template #title> Sorry,Multiple results </template>
          <template #result>
            <p class="light">To correctly display the details page,</p>
            <p class="light">please search using the HBL No. Thank you.</p>
          </template>
        </VEmpty>
      </div>
    </div>
    <!-- <SlideVerify ref="slideVerifyRef" @verify-success="confirmVerify"></SlideVerify> -->
    <VSliderVerification
      v-if="isShowSliderVerification"
      @close="confirmVerification"
      ref="sliderVerificationRef"
    ></VSliderVerification>
  </div>
</template>

<style lang="scss" scoped>
.light {
  font-size: 12px;
  line-height: 18px;
  color: var(--color-neutral-3);
}
.public-tracking-search {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  padding-bottom: 160px;
  background: url(../../../../../Login/src/image/bg.png) no-repeat center center;
  background-size: cover;
  z-index: 1;
  height: 100%;
}

.public-tracking-search::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.85); /* 半透明白色背景层 */
  z-index: -1; /* 将伪元素放置在背景图片的下方 */
}

.search-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  & > .title {
    margin-bottom: 24px;
    font-size: 40px;
    font-weight: 700;
    color: var(--color-theme);
  }
  .public-tracking-search-input {
    width: 480px;
    height: 40px;
    :deep(.el-input__wrapper) {
      border-radius: 6px 0 0 6px;
      background-color: var(--color-table-header-bg);
    }
    :deep(.el-input-group__append) {
      padding: 0;
      background-color: black;
      border: 1px solid black;
      border-radius: 0 6px 6px 0;
      box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);
      span {
        color: white;
      }
    }
  }
  .error-empty,
  .multiple-empty {
    width: 480px;
    height: 315px;
    padding: 16px;
    background-color: white;
    border-radius: 12px;
    border: 1px solid var(--color-border);
    .suggestion-info {
      & > p {
        color: var(--color-neutral-1);
      }
    }
  }
  div.multiple-empty {
    height: 236px;
    padding-top: 24px;
  }
}
.public-tracking-search-input {
  :deep(.el-input__wrapper) {
    box-shadow: 0 0 0 1px #2b2f36 inset;
  }
}
</style>
