<template>
  <div class="mobile-container">
    <van-nav-bar right-text="搜索"
      left-arrow
      @click-left="clickBack"
      @click-right="showSearch = true"
      placeholder
      fixed />
    <!-- 计划列表 -->
    <van-pull-refresh v-model="refreshLoading"
      :pull-distance="100"
      success-text="刷新成功"
      @refresh="onRefresh">
      <van-list v-model:loading="loading"
        :finished="finished"
        :immediate-check="false"
        finished-text="没有更多了"
        @load="onLoad">
        <van-cell-group inset>
          <van-cell :title="item.prdName + '\n料号: ' + item.prdCode"
            v-for="item, index in planList"
            :key="item.id"
            :class="{ 'zebra-row': index % 2 === 1 }">
            <template #label>
              <p>批号：{{ item.manufactureBatchNo }}</p>
              <p>厂家：{{ item.manufacturersName }}</p>
              <p>发货时间：{{ parseTime(item.shipDate, '{y}-{m}-{d}') }}</p>
            </template>
            <template #value>
              <el-link v-if="item.qualityUrl"
                type="primary"
                @click="handleReportClick(item.qualityUrl)">
                {{ getReportLinkText(item.qualityUrl) }}
              </el-link>
              <span v-else>无文件</span>
            </template>
          </van-cell>
        </van-cell-group>
      </van-list>
    </van-pull-refresh>

    <!-- 移动端特殊，覆盖一个 iframe 在当前页顶层显示 pdf 用 -->
    <div class="iframe-wrap"
      v-if="showPdfIframe">
      <iframe :src="pdfUrl"
        width="100%"
        height="100%"
        frameborder="0"
        allow="fullscreen" />
      <!-- 覆盖一层 div，透明的，用于接收点击交互关闭 -->
      <div class="click-cover"
        @click="closeIframe"></div>
    </div>
  </div>
</template>

<script setup>
import { getQualityInsPageList } from '@/api'
import { parseTime } from '@/utils'
import { showImagePreview } from 'vant';
const router = useRouter()

/*************** 导航栏 ***************/
const showSearch = ref(false)
const clickBack = () => {
  router.back()
}
/*************** 刷新+加载 ***************/
const refreshLoading = ref(false)
const onRefresh = async () => {
  refreshLoading.value = true
  await getPlanListFn()
  refreshLoading.value = false
}
// 加载更多
const loading = ref(false)
const finished = ref(false)

const onLoad = async () => {
  if (loading.value || finished.value) return
  loading.value = true
  await getPlanListFn()
  loading.value = false
}

/*************** 计划列表 ***************/
const query = reactive({
  pageNum: 1,
  pageSize: 10,
})
const planList = ref([])
const getPlanListFn = async () => {
  const res = await getQualityInsPageList(query)
  if (res.code === 200) {
    planList.value = res.data.rows || []
    finished.value = res.data.rows.length < res.data.pageSize
  }
}
getPlanListFn()

/*************** 附件类型/预览 ***************/
const showPdfIframe = ref(false)
const pdfUrl = ref('')
// 判断文件类型
const isImageFile = (url) => {
  if (!url) return false
  const imageExtensions = ['.png', '.jpg', '.jpeg', '.webp']
  return imageExtensions.some(ext => url.toLowerCase().includes(ext))
}
const isPdfFile = (url) => {
  if (!url) return false
  return url.toLowerCase().includes('.pdf')
}
const isZipFile = (url) => {
  if (!url) return false
  const zipExtensions = ['.zip', '.rar', '.7z']
  return zipExtensions.some(ext => url.toLowerCase().includes(ext))
}
const getReportLinkText = (url) => {
  if (isImageFile(url)) {
    return '预览图片'
  } else if (isPdfFile(url)) {
    return '查看报告'
  } else if (isZipFile(url)) {
    return '下载压缩包'
  } else {
    return '查看文件'
  }
}

// 处理报告点击事件
const handleReportClick = (url) => {
  if (isImageFile(url)) {
    // 图片文件：预览
    showImagePreview([url])
  } else if (isPdfFile(url)) {
    // PDF文件：打开新链接
    // 把 url 的域名替换掉，改成自己的然后拼接原来的资源路径
    const originDomain = import.meta.env.VITE_APP_OSS_ORIGIN_DOMAIN
    const customDomain = import.meta.env.VITE_APP_OSS_CUSTOM_DOMAIN
    url = url.replace(originDomain, customDomain)
    pdfUrl.value = url
    showPdfIframe.value = true
  } else {
    // 其他文件类型：默认打开新链接
    window.open(url, '_blank')
  }
}
// 关闭 iframe
const closeIframe = () => {
  showPdfIframe.value = false
}


</script>

<style scoped
  lang="scss">

  /* 添加斑马纹样式 */
  .van-cell-group {
    margin: 0;

    .van-cell {
      padding-right: 40px !important;
      padding-left: 40px !important;

      +.zebra-row {
        background-color: #f9f9f9;
      }

      .van-cell__label {
        p {
          margin: 0;
        }
      }
    }
  }

  /* iframe 样式 */
  .iframe-wrap {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.8);
    z-index: 9998;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .click-cover{
    position: absolute;
    top: 56px;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 9999;
  }
</style>