<script setup>
import { getCurrentInstance, ref } from 'vue';
const { proxy } = getCurrentInstance();

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

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

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

const resetCondition = () => {
  basicReset();
  fetchData.value.lawName = '';
  onLoad();
};

const currentTab = ref('safe');
const handleClick = (tab) => {
  currentTab.value = tab;
  fetchData.value.lawType = tab;
  onRefresh();
};

/* 查询请求 */
const queryFetch = async () => {
  if (sessionStorage.getItem('lawName')) {
    fetchData.value.lawName = sessionStorage.getItem('lawName');
    sessionStorage.removeItem('lawName');
  }
  const url = '/sgsafe/InstitutionLaw/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;
  }
};

/* 在线预览实现 */
import { Base64 } from 'js-base64';
import { showFailToast } from 'vant';
const linShiFid = ref({ fileId: '' });
const handlePreview = (fileId) => {
  if (fetchData.value.lawName) {
    sessionStorage.setItem('lawName', fetchData.value.lawName);
  }
  linShiFid.value.fileId = fileId;
  getTableDataQueryFile();
};
const bucket = ref(import.meta.env.VITE_BUCKET);
const getTableDataQueryFile = () => {
  const url = 'framework/Common/queryFileWithValues';
  let 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
      }));

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

</script>

<template>
  <div class="page-container">
    <van-sticky>
      <van-nav-bar
        title="法律法规"
        @click-left="handleClick('safe')"
        @click-right="handleClick('env')"
      >
        <template #left>
          <div class="custom-tab" :class="{ 'custom-tab--active': currentTab === 'safe' }">安全</div>
        </template>
        <template #right>
          <div class="custom-tab" :class="{ 'custom-tab--active': currentTab === 'env' }">环保</div>
        </template>
      </van-nav-bar>

      <van-search
        v-model="fetchData.lawName"
        @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"
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <div v-for="item in list" :key="item.id" class="card">
            <van-cell @click="handlePreview(item.lawFile)" :border="false" is-link>
              <template #title>
                <van-icon name="idcard" />
                <span class="bold-title" style="margin-left: 4px;">{{ item.lawName }}</span>
              </template>
            </van-cell>
          </div>
        </van-list>
      </van-pull-refresh>
    </div>
  </div>
</template>

<style scoped>
.page-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.scroll-container {
  flex: 1;
  overflow: auto;
  -webkit-overflow-scrolling: touch;
}

.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;
}

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

.custom-tab {
  padding: 8px 0;
  font-size: 14px;
  color: var(--van-gray-7, #646566);
  position: relative;
  cursor: pointer;
}

.custom-tab--active {
  color: var(--van-primary-color, #1989fa);
}

.custom-tab--active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 3px;
  background-color: var(--van-primary-color, #1989fa);
  border-radius: 2px;
}

</style>
