<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/CardSpecialWork/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";
const linShiFid=ref({
  fileId:''
})
const handlePreview = (fileId) => {
  if (fetchData.value.userDesc) {
    sessionStorage.setItem("userDesc", fetchData.value.userDesc);
  }
  if (fetchData.value.deptCode) {
    sessionStorage.setItem("deptCode", fetchData.value.deptCode)
  }
  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:'',
  deptCode: ''
})

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

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

const getDeptNameByDeptCode = async (deptCode) => {
  const url = '/sgsafe/SafeDepartment/getDeptByDeptCode'
  const param = {
    deptCode: deptCode
  }
  const res = await proxy.$axios.get(url,param)
  if (res.data.code === 0) {
    return res.data.data.deptName
  } else {
    showFailToast('数据异常，请联系管理员!')
    return '';
  }
}

/* 查询请求 */
const queryFetch = async () => {
  fetchData.value.deptCode = postBackRegimeScope.value
  if (sessionStorage.getItem("userDesc")) {
    fetchData.value.userDesc = sessionStorage.getItem("userDesc")
    sessionStorage.removeItem("userDesc")
  }
  if (sessionStorage.getItem("deptCode")) {
    const deptInfo = sessionStorage.getItem("deptCode")
    fetchData.value.deptCode = deptInfo
    postBackRegimeScope.value = deptInfo
    currentDeptName.value = await getDeptNameByDeptCode(deptInfo)
    sessionStorage.removeItem("deptCode")
  }
  const url = '/sgsafe/CardSpecialWork/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) => {
  currentDeptName.value = nodeData.split('-')[1]
  postBackRegimeScope.value = nodeData.split('-')[0]
  basicReset()
  await onLoad()
  showBottom.value = false
}

const getDeptInfo = async (currentDeptInfo) => {
  postBackRegimeScope.value = currentDeptInfo.split('-')[0]
  currentDeptName.value = currentDeptInfo.split('-')[1]
  basicReset()
  // 待办中心跳转 =》 将对应记录显示在第一位
  if (route.query.id) {
    await queryOneById(route.query.id)
  }
  await onLoad()
}

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] || ''
}

</script>

<template>
  <div class="page-container">
    <van-sticky>
      <van-nav-bar title="特种作业操作证" />

      <van-search
        v-model="fetchData.userDesc"
        @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,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 style="margin-right: 10px">作业类别：{{ item.jobCategory }}</span>
                  <span style="margin-right: 10px">操作项目：{{ item.actionItems }}</span>
                  <span>下次复审日期：{{ item.nextDate }}</span>
                </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;

}
/*  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>
