<script setup>
import { getCurrentInstance, onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const {
  proxy
} = getCurrentInstance()

/* 通用方法： 重置list数据 */
const basicReset = () => {
  finished.value = false;
  loading.value = true;
  pageNum.value = 1
  list.value = []
}

/* 返回上一级页面 */
const router = useRouter()
const route = useRoute()
const queryOneById = async (id) => {
  const url = '/sgsafe/CardEngineer/queryOneById'
  const param = {
    id: id
  }
  const res = await proxy.$axios.post(url,param)
  if (res.data.code === 0) {
    list.value.push(res.data.data)
  } else {
    showFailToast('待办数据异常，请联系管理员!')
  }
}

/* 在线预览实现 */
import {Base64} from "js-base64";
import { showFailToast } from 'vant';
const linShiFid=ref({
  fileId:''
})
const handlePreview = (fileId) => {
  if (fetchData.value.userDesc) {
    sessionStorage.setItem("userDesc", fetchData.value.userDesc);
  }
  linShiFid.value.fileId= fileId
  getTableDataQueryFile()
}
const bucket = ref(import.meta.env.VITE_BUCKET)
const getTableDataQueryFile = () => {
  var url = 'framework/Common/queryFileWithValues'
  var param = {
    fId: linShiFid.value.fileId,
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == 0) {
      const downloadPath = import.meta.env.VITE_BASE_API + '/framework/Common/downloadFileS3?bucket='+ bucket.value + '&id='
      const fileListWithUrls = response.data.data.map(file => ({
        ...file,
        url: `${downloadPath}${file.id}`, // 添加完整的下载路径
        thumbUrl: `${downloadPath}${file.id}`, // 如果需要缩略图，可以使用相同的路径
        name: file.fileName, // 确保有文件名属性
        status: file.status, // 确保有状态属性
        id: file.id
      }));

      var originUrl = import.meta.env.VITE_PREVIEW_BASE_API + 'framework/Common/downloadFileS3?bucket=' + bucket.value +'&id=' + fileListWithUrls[0].id
      var previewUrl = originUrl + '&fullfilename=' + Date.now() + fileListWithUrls[0].name
      var url = import.meta.env.VITE_PREVIEW_API + 'onlinePreview?url=' + encodeURIComponent(Base64.encode(
        previewUrl)) + '&officePreviewType=pdf'
      window.open(url);
    } else {
      showFailToast('失败！' + response.data.msg)
    }
  })
}

/* 查询数据 */
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const resultData = ref([])
const fetchData = ref({
  userDesc:''
})

const onSearch = () => {
  basicReset()
  onLoad()
}

const resetCondition = () => {
  basicReset()
  fetchData.value = {
    userDesc:''
  }
  onLoad()
}

/* 查询请求 */
const queryFetch = async () => {
  if (sessionStorage.getItem("userDesc")) {
    fetchData.value.userDesc = sessionStorage.getItem("userDesc")
    sessionStorage.removeItem("userDesc")
  }
  const url = '/sgsafe/CardEngineer/query'
  const param = {
    page: pageNum.value,
    rows: pageSize.value,
    params: JSON.stringify(fetchData.value)
  }
  try {
    const res = await proxy.$axios.post(url,param);
    if (res.data.code === 0) {
      total.value = res.data.data.total
      resultData.value = res.data.data.records
    } else {
      console.log('操作失败!' + res.data.msg)
    }
  } catch (error) {
    console.error('请求出错:', error);
  }
};

/* 列表加载与下拉刷新 */
const list = ref([]);
const refreshing = ref(false)
const loading = ref(false)
const finished = ref(false)

const onRefresh = () => {
  basicReset()
  onLoad();
};

const onLoad = async () => {
  if (refreshing.value) {
    list.value = [];
    pageNum.value = 1;
    refreshing.value = false;
  }
  try {
    await  queryFetch();
    if (pageSize.value * pageNum.value < total.value) {
      list.value = [...list.value,...resultData.value ]
      pageNum.value++;
    } else {
      list.value = [...list.value,...resultData.value ]
      finished.value = true;
    }
  } catch (error) {
    console.log(error);
    finished.value = true;
  } finally {
    loading.value = false;
  }
}

const getContentState = (state) => {
  const contentMap = {
    '1': '未审验',
    '2': '待审验',
    '3': '已审验'
  }
  return contentMap[state] || ''
}
const getTagType = (state) => {
  const typeMap = {
    '1': 'danger',
    '2': 'warning',
    '3': 'success'
  };
  return typeMap[state] || ''
}

const getRegistrationCategory = (status) => {
  const contentMap = {
    '1': '煤矿安全',
    '2': '金属非金属矿山安全',
    '3': '化工安全',
    '4': '金属冶炼安全',
    '5': '建筑施工安全',
    '6': '道路运输安全',
    '7': '其他安全（不包括消防安全）',
  }
  return contentMap[status] || ''
}

onMounted(async () => {
  basicReset()
  if (route.query.id) {
    await queryOneById(route.query.id)
  }
  await onLoad()
})

</script>

<template>
  <div class="page-container">
    <van-sticky>
      <van-nav-bar title="安全工程师" />
      <van-search
        v-model="fetchData.userDesc"
        @search="onSearch"
        @clear="resetCondition"
        placeholder="请输入姓名"
      />
    </van-sticky>

    <div class="scroll-container">
      <van-pull-refresh
        v-model="refreshing"
        success-text="刷新成功"
        @refresh="onRefresh"
      >
        <van-list
          class="listDiv"
          :immediate-check="false"
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <div v-for="(item,idx) in list" :key="item.id" class="card">
            <van-cell
              :border="false" is-link
              @click="handlePreview(item.cardFile)"
              :class="{ 'selected-cell': idx === 0 && route.query.id }"
            >
              <template #title>
                <van-icon name="idcard" />
                <span class="bold-title" style="margin-left: 4px;margin-right: 10px">{{ item.userDesc }}</span>
                <van-tag :type="getTagType(item.status)">{{ getContentState(item.status) }}</van-tag>
              </template>
              <template #label>
                <div class="label-content">
                  <span>注册类别：{{ getRegistrationCategory(item.registrationCategory) }}</span>
                  <span>有效期：{{ item.lastDate }}</span>
                </div>
              </template>
            </van-cell>
          </div>
        </van-list>
      </van-pull-refresh>
    </div>
  </div>
</template>

<style scoped>
.page-container {
  height: 100vh; /* 关键：外层容器高度设为视口高度 */
  display: flex;
  flex-direction: column;

}
/*  overflow-y: auto; !* 启用垂直滚动 *!*/


.scroll-container {
  flex: 1;
  overflow: auto;
  -webkit-overflow-scrolling: touch; /* iOS 平滑滚动 */
}

/* 可选：隐藏滚动条（视觉优化） */
.scroll-container::-webkit-scrollbar {
  display: none;
}

.card {
  margin: 10px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  background-color: #fff;
}

.label-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.bold-title {
  font-weight: bold;
  color: #333;
}

.selected-cell {
  background-color: #f5f7fa;
  border-left: 4px solid #1989fa;
  padding-left: 12px;
}
</style>
