<script setup>
import { getCurrentInstance, onMounted, ref } from 'vue';
import { onBeforeRouteLeave, useRouter, useRoute } from 'vue-router';
import { useEmergencyStore } from '@/stores/emergencyManager.js';
const emergencyInfo =  useEmergencyStore()

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/EmergencyResourceMaster/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('待办数据异常，请联系管理员!')
  }
}

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

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

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

/* 查询请求 */
const queryFetch = async () => {
  fetchData.value.linkDept = postBackRegimeScope.value
  const url = '/sgsafe/EmergencyResourceMaster/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 ]
      openStates.value = new Array(list.value.length).fill(true);
      pageNum.value++;
    } else {
      list.value = [...list.value,...resultData.value ]
      openStates.value = new Array(list.value.length).fill(true);
      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';
const showPickerHandle = () => {
  showBottom.value = true
}

/**
 * 组织树组件选择后返回方法
 * @param nodeData 用户部门信息(userCode-userName)
 * @returns {Promise<void>} 条件查询
 */
const handleTableDataUserDeptUpdate = async (nodeData) => {
  currentDeptName.value = nodeData.split('-')[1]
  postBackRegimeScope.value = nodeData
  basicReset()
  await onLoad()
  showBottom.value = false
}

/**
 * 组织树组件初始化返回方法
 * @param currentDeptInfo 用户部门信息(userCode-userName)
 */
const cachedDeptCode = ref('')
const getDeptInfo = async (currentDeptInfo) => {
  postBackRegimeScope.value = currentDeptInfo
  currentDeptName.value = currentDeptInfo.split('-')[1]

  /* Pinia初始化属性 */
  if (emergencyInfo.currentDeptCode) {
    postBackRegimeScope.value = emergencyInfo.currentDeptCode + '-' + emergencyInfo.currentDeptName
    currentDeptName.value = emergencyInfo.currentDeptName
    fetchData.value.resourceName = emergencyInfo.conditionalQueryAttributes
  }
  basicReset()
  if (route.query.id) {
    await queryOneById(route.query.id)
  }
  await onLoad()
}

/**
 * 数据传回组织树组件
 */
if (emergencyInfo.currentDeptCode) {
  cachedDeptCode.value = emergencyInfo.currentDeptCode
}

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

/**
 * 路由跳转前，pinia中缓存数据
 */
onBeforeRouteLeave((to, from, next) => {
  /* 跳转子页面赋值 */
  if (to.name === 'MaintenanceRecords' || to.name === 'ResourcesQuery') {
    emergencyInfo.$patch({
      currentDeptCode: postBackRegimeScope.value.split('-')[0],
      currentDeptName: postBackRegimeScope.value.split('-')[1],
      conditionalQueryAttributes: fetchData.value.resourceName
    })
  } else {
    /* 跳转其他页面均清空，避免混乱赋值 */
    emergencyInfo.clearMainDeptInfo()
  }
  next()
})

/**
 * 按钮实现swipe-cell滑动
 */
const openStates  = ref([])
const swipeCellRefs = ref([])
const getSwipeCellRef = (el, index) => {
  if (el) {
    swipeCellRefs.value[index] = el;
  }
}
const openSwipe = (idx) => {
  openStates.value = new Array(list.value.length).fill(true);
  if (idx >= 0 && idx < swipeCellRefs.value.length) {
    openStates.value[idx] = false
    swipeCellRefs.value[idx].open('right')
  }
  document.addEventListener('click',handleDocumentClick)
}

const closeSwipe = (idx) => {
  if (idx >= 0 && idx < swipeCellRefs.value.length) {
    openStates.value[idx] = true
    swipeCellRefs.value[idx].close()
  }
}
/** 滑动监听 **/
const handleSwipeOpen = (idx) =>{
  openStates.value[idx] = false
}

const handleSwipeClose = (idx) =>{
  openStates.value[idx] = true
}

/**
 * 当点击滑动单元格时，开始监听点击事件
 */
const handleDocumentClick = (event) => {
  openStates.value = new Array(list.value.length).fill(true);
}



</script>

<template>
  <div class="page-container">
    <van-sticky>
      <van-nav-bar title="应急物资" />

      <van-search
        v-model="fetchData.resourceName"
        @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">
            <van-swipe-cell
              title-style="color: #007aff"
              class="goods-card"
              :ref="el => getSwipeCellRef(el, idx)"
              @open="handleSwipeOpen(idx)"
              @close="handleSwipeClose(idx)"
            >
              <template #default>
                <div class="swipe-cell-default">
                  <van-cell
                    :to="{ name: 'ResourcesQuery', query: { resourcesInfo: JSON.stringify(item) } }"
                    :class="{ 'selected-cell': idx === 0 && route.query.id }"
                  >
                    <template #title>
                      <span class="bold-title" style="margin-right: 10px">{{ item.resourceName }}</span>
                      <van-tag :type="getTagType(item.state)">{{ getContentState(item.state) }}</van-tag>
                    </template>
                    <template #label>
                      <span style="margin-right: 5px;">审验人：{{ item.linkPerson }}</span>
                      <span>下次审验时间：{{ item.checkNextDate }}</span>
                    </template>
                  </van-cell>
                  <div class="swipe-cell-default-icon">
                    <van-icon v-if="openStates[idx]" name="arrow-double-left" @click.stop="openSwipe(idx)" />
                    <van-icon v-else name="arrow-double-right" @click.stop="closeSwipe(idx)" />
                  </div>
                </div>
              </template>
              <template #right>
                <van-button square style="height: 100%" type="primary" :to="{ name: 'MaintenanceRecords', query: { resourceId: item.id } }">查看保养记录</van-button>
              </template>
            </van-swipe-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 :cached-dept-code="cachedDeptCode" @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;
}

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

.swipe-cell-default {
  display: flex;
  background-color: #ffffff;
  justify-content: center;
  align-items: center;
}

.swipe-cell-default-icon {
  width: 60px;
  display: flex;
  justify-content: center;
}

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

</style>
