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

const emergencyInfo = useEmergencyStore();
const { proxy } = getCurrentInstance();
const base_url = '/sgsafe/PlanManagement';

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

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

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

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

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

/* 查询请求 */
const queryFetch = async () => {
  const url = base_url + '/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;
  }
};

/**
 * pinia读取和缓存数据
 */
onMounted(() => {
  if (emergencyInfo.conditionalQueryAttributes) {
    fetchData.value.planName = emergencyInfo.conditionalQueryAttributes;
  }
  basicReset();
  onLoad();
});
onBeforeRouteLeave((to, from, next) => {
  if (to.path === '/planManagement/manifest') {
    emergencyInfo.$patch({
      conditionalQueryAttributes: fetchData.value.planName
    });
  } else {
    emergencyInfo.clearMainDeptInfo();
  }
  next();
});

</script>

<template>
  <div class="page-container">
    <van-sticky>
      <van-nav-bar title="待完成计划">
      </van-nav-bar>

      <van-search
        v-model="fetchData.planName"
        @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 in list" :key="item.id">
            <van-cell :to="{ path: '/planManagement/manifest', query: { plan: JSON.stringify(item) } }"
                      style="margin-right: 10px;">
              <template #title>
                <span class="bold-title" style="margin-right: 10px;">{{ item.planName }}</span>
                <van-tag style="margin-right: 10px;" :type="item.isFinished === '已完成' ? 'success' : 'danger'">{{ item.isFinished }}
                </van-tag>
                <van-tag style="margin-right: 10px;" :type="item.isOverdue === '逾期' ? 'danger' : 'success'">
                  {{ item.isOverdue === '逾期' ? '逾期' : '未逾期' }}
                </van-tag>
              </template>
              <template #label>
                <span style="margin-right: 10px;">开始时间：{{ item.planStartTime }}</span>
                <span>结束时间：{{ item.planEndTime }}</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; /* iOS 平滑滚动 */
}

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

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

</style>
