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

const {
  proxy
} = getCurrentInstance()

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

/* 返回上一级页面 */
const router = useRouter()

/* 在线预览实现 */
import {Base64} from "js-base64";
const linShiFid=ref({
  fileId:''
})
const handlePreview = (fileId) => {
  if (fetchData.value.planName) {
    sessionStorage.setItem("planName", fetchData.value.planName)
  }
  if (fetchData.value.regimeScope) {
    sessionStorage.setItem("regimeScope", fetchData.value.regimeScope)
  }
  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({
  planName:'',
  regimeScope: ''
})

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

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

/* 查询请求 */
const queryFetch = async () => {
  fetchData.value.regimeScope = postBackRegimeScope.value
  if (sessionStorage.getItem("planName")) {
    fetchData.value.planName = sessionStorage.getItem("planName")
    sessionStorage.removeItem("planName")
  }
  if (sessionStorage.getItem("regimeScope")) {
    const deptInfo = sessionStorage.getItem("regimeScope")
    fetchData.value.regimeScope = deptInfo
    postBackRegimeScope.value = deptInfo
    currentDeptName.value = deptInfo.split('-')[1]
    sessionStorage.removeItem("regimeScope")
  }
  const url = '/sgsafe/EmergencyPlanMaster/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 showBottom = ref(false)
const currentDeptName = ref('')
const postBackRegimeScope = ref()
import OrganizationalWithLeaf from '@/components/OrganizationalWithLeaf.vue';
import { showFailToast } from 'vant';
const showPickerHandle = () => {
  showBottom.value = true
}

const handleTableDataUserDeptUpdate = async (nodeData) => {
  postBackRegimeScope.value = nodeData
  currentDeptName.value = nodeData.split('-')[1]
  basicReset()
  await onLoad()
  showBottom.value = false
}

const getDeptInfo = (currentDeptInfo) => {
  postBackRegimeScope.value = currentDeptInfo
  currentDeptName.value = currentDeptInfo.split('-')[1]
  basicReset()
  onLoad()
}

</script>

<template>
  <div class="page-container">
    <van-sticky>
      <van-nav-bar title="应急预案" />
      <van-search
        v-model="fetchData.planName"
        @search="onSearch"
        @clear="resetCondition"
        placeholder="请输入应急预案名称"
      />

      <van-field
        v-model="currentDeptName"
        label="当前组织"
        placeholder="请选择组织架构"
        readonly
        right-icon="arrow-down"
        @click="showPickerHandle()"
      />
    </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 in list" :key="item.id" class="card">
            <van-cell @click="handlePreview(item.planFile)" :border="false" is-link>
              <template #title>
                <van-icon name="idcard" />
                <span class="bold-title" style="margin-left: 4px;">{{ item.planName }}</span>
              </template>
              <template #label>
                <div class="label-content">
                  <div>文件编号：{{ item.planNo }}</div>
                  <div>发布日期：{{ item.publishDate }}</div>
                </div>
              </template>
            </van-cell>
          </div>
        </van-list>
      </van-pull-refresh>
    </div>

    <van-popup :close-on-click-overlay="false" :lazy-render="false" v-model:show="showBottom" position="bottom">
      <OrganizationalWithLeaf @init="getDeptInfo" @close="showBottom = false" @update:selected-node="handleTableDataUserDeptUpdate" />
    </van-popup>
  </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;
}

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

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

</style>
