<script lang="tsx" setup>
import request from '@/utils/request'
const router = useRouter()


const loading = ref(true)
const fileLoading = ref(false)
const pdfPreview = ref(false)
const iframeTitle = ref('')
const iframeURL = ref('')
const keywords = ref('')
const isSearch = ref(false)
interface KnowledgeItem {
  file_name: string
  extension: string
  file_url: string
  match_text: string
  file_updated_at: string
  cover_url: string
}

const knowledgeList = ref<KnowledgeItem[]>([])

setTimeout(() => {
  loading.value = false
}, 700)


const stylizingLoading = ref(false)


/**
 * 输入字符串
 */
const inputTextString = ref('')


const refReaderMarkdownPreview = ref<any>()


const handleResetState = () => {
  inputTextString.value = ''

  stylizingLoading.value = false
  refReaderMarkdownPreview.value?.abortReader()
  refReaderMarkdownPreview.value?.resetStatus()
}
handleResetState()

const gotoHome = () => {
  router.push({
    name: 'Home',
    query: {
      tkn_8f9a1c7b3e24fd: 'c154d4a7-dad3-45d0-a11f-07893dd4fbba'
    }
  })
}
function debounce<T extends (...args: any[]) => void>(
  fn: T,
  delay: number
): (...args: Parameters<T>) => void {
  let timer: ReturnType<typeof setTimeout> | null = null
  return (...args: Parameters<T>) => {
    if (timer !== null) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fn(...args) // 不使用 this
    }, delay)
  }
}


const inputSearch = debounce(() => {
  if (!keywords.value) {
    knowledgeList.value = []
    return
  }
  const params = {
    'client_id': `${ Date.now() + 10 }`,
    'prompt': keywords.value
  }
  request.post(`/search`, params).then((res) => {
    isSearch.value = true
    if (res.data.code === 200) {
      knowledgeList.value = res.data.content
    } else {
      window.$ModalMessage.error(res.data.message)
    }
  })
}, 500)

const clear = () => {
  isSearch.value = false
  knowledgeList.value = []
}

const openLink = (link: string, file_name: string) => {
  previewFile(link.split('?')[0], file_name)
}

/**
 * 通用文件预览函数
 * @param fileUrl - 文件的公网 URL 地址
 */
async function previewFile(fileUrl: string, file_name: string) {
  const ext = fileUrl.split('.').pop()?.toLowerCase().split('?')[0] || ''
  const open = (url: string) => {
    location.href = url
  }

  const isOffice = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'].includes(ext)
  const isText = ['txt', 'csv'].includes(ext)

  if (ext === 'pdf') {
    // fileLoading.value = true
    // const disposition = await checkContentDisposition(fileUrl)
    // if (disposition === 'inline') {
    //   fileLoading.value = false
    //   open(fileUrl)
    // } else {
    //   await openPdfAsBlob(fileUrl) // fallback：强制以 blob 打开
    //   fileLoading.value = false
    // }
    iframeTitle.value = file_name
    iframeURL.value = `${ location.origin }/pdfJS/web/viewer.html?file=${ encodeURIComponent(fileUrl) }`
    pdfPreview.value = true
  } else if (isOffice) {
    const encoded = encodeURIComponent(fileUrl)
    open(`https://view.officeapps.live.com/op/view.aspx?src=${ encoded }`)
  } else if (isText) {
    open(fileUrl)
  } else {
    // fallback：不支持的格式可以提示或触发下载
    const a = document.createElement('a')
    a.href = fileUrl
    a.download = ''
    a.click()
  }
}

const closePreview = () => {
  iframeTitle.value = ''
  iframeURL.value = ''
  pdfPreview.value = false
}


</script>

<template>
  <LayoutCenterPanel
    :loading="loading"
  >
    <!-- 内容区域 -->
    <div
      flex="~ col"
      h-full
    >
      <div
        flex="~ justify-between items-center"
      >
        <div class="index-header-block">
          <div class="logo">
            <img
              src="../assets/images/logo.png"
              alt=""
            >
          </div>
          <div class="index-header">
            <div class="saerch-black">
              <div class="saerch-black__input">
                <span class="search-icon">
                  <svg
                    t="1751009112601"
                    class="icon"
                    viewBox="0 0 1024 1024"
                    version="1.1"
                    xmlns="http://www.w3.org/2000/svg"
                    p-id="5234"
                    xmlns:xlink="http://www.w3.org/1999/xlink"
                    width="200"
                    height="200"
                  ><path
                    d="M470.4 912c-112 0-224-41.6-310.4-128C-9.6 611.2-9.6 332.8 160 160c172.8-172.8 451.2-172.8 620.8 0 172.8 172.8 172.8 451.2 0 620.8C697.6 867.2 582.4 912 470.4 912z m0-803.2c-92.8 0-185.6 35.2-256 105.6-140.8 140.8-140.8 374.4 0 515.2 140.8 140.8 374.4 140.8 515.2 0 140.8-140.8 140.8-374.4 0-515.2-70.4-70.4-166.4-105.6-259.2-105.6z"
                    p-id="5235"
                  /><path
                    d="M905.6 976l-160-160c-19.2-19.2-19.2-51.2 0-70.4s51.2-19.2 70.4 0l160 160c19.2 19.2 19.2 51.2 0 70.4-19.2 22.4-51.2 22.4-70.4 0z"
                    p-id="5236"
                  /></svg>
                </span>
                <div class="input-black">
                  <n-input
                    v-model:value="keywords"
                    clearable
                    type="text"
                    placeholder="搜索知识库内容"
                    @input="inputSearch"
                    @clear="clear"
                  />
                </div>
              </div>
              <div
                class="close"
                @click="gotoHome"
              >
                取消
              </div>
            </div>
          </div>
        </div>
      </div>

      <div
        flex="1 ~ col"
        min-h-0
        pb-20
        class="knowledge-black"
      >
        <div
          v-if="knowledgeList.length"
          class="knowledge-scroll"
        >
          <!-- 列表 -->
          <div
            class="knowledge__list"
          >
            <ul
              class="knowledge__list-ul"
            >
              <li
                v-for="(acc, index) in knowledgeList"
                :key="index"
                class="knowledge__list-items"
                @click="openLink(acc.file_url, acc.file_name)"
              >
                <span
                  v-if="acc.cover_url"
                  class="items-img"
                >
                  <img
                    :src="acc.cover_url"
                    alt=""
                  >
                </span>
                <span
                  v-else
                  class="items-img"
                >GOELIA</span>
                <div class="items-info">
                  <h2 v-html="acc.file_name"></h2>
                  <p
                    v-if="acc.match_text"
                    class="desc"
                    v-html="acc.match_text"
                  ></p>
                  <div class="items-info-content">
                    <span class="type">{{ acc.extension }}</span>
                    <span class="line">|</span>
                    <span class="date">{{ acc.file_updated_at }}</span>
                  </div>
                </div>
              </li>
            </ul>
          </div>
        </div>
        <div
          v-if="!knowledgeList.length && isSearch"
          class="no-data"
        >
          未找到相关搜索结果
        </div>
      </div>
    </div>
    <div
      v-if="fileLoading"
      class="loading-block"
    >
      <div class="loading-items">
        <div class="loading-container">
          <div class="loading-overlay__spinner"></div>
        </div>
        <span class="loading-text">文件加载中...</span>
      </div>
    </div>
    <div
      v-if="pdfPreview"
      class="pdf-black"
    >
      <div
        class="header-block-div"
        @click="closePreview()"
      >
        <span class="back"><svg
          xmlns="http://www.w3.org/2000/svg"
          viewBox="0 0 24 24"
          aria-hidden="true"
          focusable="false"
          role="presentation"
          class="icon icon-caret"
        >
          <path d="M 7.75 1.34375 L 6.25 2.65625 L 14.65625 12 L 6.25 21.34375 L 7.75 22.65625 L 16.75 12.65625 L 17.34375 12 L 16.75 11.34375 Z" />
        </svg></span>
        <div class="title-black">
          <span
            class="title"
            v-html="iframeTitle"
          ></span>
          <span class="subtitle">文件预览</span>
        </div>
      </div>
      <iframe
        :src="iframeURL"
        frameborder="0"
      ></iframe>
    </div>
  </LayoutCenterPanel>
</template>

<style lang="scss">
  .index-header-block {
    padding: 0 14px;
    width: 100%;
    .logo {
      padding: 10px 0;
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 0 auto;
      width: 100%;

      img {
        max-width: 140px;
      }
    }
    .index-header {
      margin: 10px 0;
    }
    .index-header .saerch-black{
      display: flex;
      justify-content: space-between;
      align-items: center;
      min-height: 40px;
      gap: 10px;
      width: 100%;

      .saerch-black__input {
        display: flex;
        position: relative;
        background: #EFEFEF;
        border-radius: 8px;
        height: 40px;
        width: 100%;

        .search-icon {
          position: absolute;
          top: 0;
          left: 0;
          width: 40px;
          height: 40px;
          display: flex;
          justify-content: center;
          align-items: center;

          svg {
            width: 16px;
            height: 16px;
          }
        }
        .input-black {
          display: block;
          width: 100%;
          height: 100%;
          padding-left: 40px;

          .n-input {
            height: 100%;
            border: none;
            background: none;
            background-color: transparent;
          }
          .n-input .n-input-wrapper {
            padding: 0;
          }
          .n-input__border,.n-input__state-border {
            display: none;
          }
          .n-input .n-input__suffix, .n-input .n-input__prefix {
            width: 40px;
            margin: 0;
          }
          .n-base-clear > .n-base-clear__clear {
            width: 25px;
            height: 25px;
            font-size: 25px;
          }
          .n-input .n-input__placeholder {
            font-size: 16px;
          }
          .n-input .n-input__suffix .n-base-icon, .n-input .n-input__prefix .n-base-icon {
            font-size: 25px;
          }
          .n-input__input-el {
            border: none;
            background: none;
            display: block;
            width: 100%;
            height: 100%;
            font-size: 16px;
            color: #232323;
            outline: none;
          }
        }
      }
      .close {
        font-size: 14px;
        white-space: nowrap;
        color: #232323;
        height: 40px;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 0 5px;
        cursor: pointer;
        font-size: 16px;
        color: #232323;
      }
    }
  }
  .index-bottom {
    .click-router {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: 100;
    }
  }
  .knowledge-black .no-data {
    font-size: 16px;
    display: flex;
    width: 100%;
    height: 100%;
    justify-content: center;
    align-items: center;
    color: #999;
  }
  .knowledge-black .knowledge-scroll{
    height: 100%;
    overflow: hidden;
    overflow-y: scroll;
  }
  .knowledge__list {
    padding: 14px;

    .knowledge__list-items {
      display: flex;
      align-items: center;
      padding: 10px 0;
      border-bottom: 1px solid #f2f2f2;
      gap: 10px;

      &:last-child {
        border-bottom: none;
      }

      .items-img {
        width: 60px;
        height: 60px;
        flex: 0 0 60px;
        border-radius: 2px;
        background: #f2f2f2;
        color: #dddddd;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 13px;

        img {
          display: block;
          max-width: 100%;
        }
      }
      .items-info {
        width: calc(100% - 70px);
        h2 {
          font-size: 15px;
          line-height: 1.5;
          color: #232323;
          font-weight: normal;
          margin-bottom: 6px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          b {
            font-weight: normal;
            color: #079D55;
          }
        }
        .items-info-content {
          display: flex;
          gap: 8px;
          font-size: 13px;
          line-height: 1.5;
          color: #999;
          align-items: center;
        }
        .desc {
          font-size: 12px;
          margin: 0;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          color: #999;
          line-height: 1.5;
          margin-bottom: 6px;

          br {
            display: none;
          }

          b {
            font-weight: normal;
            color: #079D55;
          }
        }
      }
    }
  }
  .bottom-block .n-input {
    border-radius: 14px;
  }
  .bottom-block .n-input.n-input--textarea .n-input__textarea-el {
    max-height: 60px;
  }
  .loading-block {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 99;
    display: flex;
    justify-content: center;
    align-items: center;
    .loading-items {
      width: 150px;
      height: 120px;
      border-radius: 10px;
      background: #4C4C4C;
      display: flex;
      flex-direction: column;
      justify-content: center;
    }
    .loading-container {
      display: flex;
      justify-content: center;

      .loading-overlay__spinner {
        width: auto;
        position: relative;
        text-align: center;
        font-size: 0;
        display: flex;
        justify-content: center;
        &::before {
          content: "";
          width: 40px;
          height: 40px;
          box-sizing: border-box;
          border-radius: 50%;
          border: 3px solid #ccc;
          border-right-color: #666;
          border-bottom-color: #666;
          border-left-color: #666;
          animation: donutRotate 1s linear infinite;
        }
      }
    }
    .loading-text {
      display: block;
      text-align: center;
      font-size: 16px;
      color: #fff;
      margin-top: 10px;
    }
  }
  @keyframes donutRotate {
      0% {
          transform: rotate(0);
      }

      100% {
          transform: rotate(360deg);
      }
  }
  .pdf-black {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 999;
    background: #fff;
    iframe {
      display: block;
      width: 100%;
      height: calc(100% - 44px);
    }
    .header-block-div {
      display: flex;
      align-items: center;
      gap: 5px;
      cursor: pointer;
      width: 100%;
      display: flex;
      padding-left: 16px;
      padding-right: 16px;
      min-height: 44px;
      align-items: center;

      .title-black {
        display: flex;
        flex-direction: column;
        width: calc(100% - 25px);
      }
    }
    .back {
      display: flex;
      align-items: center;

      svg {
        width: 16px;
        height: 16px;
        transform: rotate(180deg);
      }
    }
    .title {
      font-weight: bold;
      font-size: 14px;
      line-height: 1.5;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      width: 100%;
      display: block;
    }
    .subtitle {
      font-size: 12px;
      color: #999;
      line-height: 1.5;
    }
  }
</style>
