<template>
  <view class="page-container">
    <!-- 顶部固定区域：Tabs + 搜索框 -->
    <view class="top-fixed">
      <u-tabs
          :list="tabList"
          :is-scroll="false"
          :activeStyle="{
          color: '#3c9cff',
          fontWeight: 'bold',
          transform: 'scale(1.05)'
        }"
          :inactiveStyle="{
          color: '#606266',
          transform: 'scale(1)'
        }"
          font-size="28rpx"
          @change="handleTabChange"
      ></u-tabs>

      <up-search
          v-model="searchValue"
          placeholder="请输入道路名称"
          bg-color="#f5f5f5"
          shape="round"
          @search="handleSearch"
          maxlength="50"
          style="margin: 20rpx 20rpx 0"
      ></up-search>
    </view>

    <!-- 修复点1：绑定total + 修正ref名称 + 移除auto=false（改用默认auto=true更易控制） -->
    <z-paging
        ref="paging"
        v-model="planList"
        @query="queryList"

    >
      <template #empty>
        <empty-view/>
      </template>
      <!-- 计划卡片列表 -->
      <view class="card-list">

        <view class="plan-card" v-for="(item, index) in planList" :key="item.batchNo">
          <view class="card-content">
            <view class="row-item">
              <text class="label">道路名称：</text>
              <text class="value up-line-1">{{ item.roadName }}</text>
            </view>
            <view class="row-item">
              <text class="label">所属街道：</text>
              <text class="value up-line-1">{{ item.streetName }}</text>
            </view>
            <view class="row-item flex-between">
              <view>
                <text class="label">养护级别：</text>
                <text class="value">{{ levelMap[item.levelId] || '未知级别' }}</text>
              </view>
              <text class="detail-btn" @click="gotoDetail(item)">计划明细</text>
            </view>
            <view class="row-item">
              <text class="label">计划类型：</text>
              <text class="value up-line-1">{{ planTypeMap[item.planTypeId] || '未知类型' }}</text>
            </view>
            <view class="row-item">
              <text class="label">计划时间：</text>
              <text class="value up-line-1">{{ formatPlanTime(item.beginTime, item.endTime) }}</text>
            </view>
          </view>
        </view>
      </view>

    </z-paging>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { inspectionPlanPage } from "@/api/patrol-manage/patrol-plan";
// Tabs 配置
const tabList = ref([
  {name: '待完成', id: '1'},
  {name: '已失效', id: '3'},
  {name: '已完成', id: '2'}
]);

const activeTab = ref('1');
// 搜索相关
const searchValue = ref('');
// 分页相关
const pageNo = ref(1);
const pageSize = ref(10);
const total = ref(0);
const planList = ref([]);
const paging = ref(null); // 修复点2：ref名称与模板中一致
// 养护级别/计划类型映射
const levelMap = {
  11: '一级养护',
  12: '二级养护',
  13: '三级养护'
};
const planTypeMap = {
  3001: '日常养护',
  3002: '专项养护',
  3003: '应急养护'
};

// 时间格式化
const formatPlanTime = (beginTime, endTime) => {
  if (!beginTime || !endTime) return '暂无';
  const formatDate = (timestamp) => {
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
  };
  return `${formatDate(beginTime)} 至 ${formatDate(endTime)}`;
};
// Tab切换
const handleTabChange = (val) => {
  console.log(val)
  console.log(activeTab.value)
  activeTab.value = val.id
  searchValue.value = ''
  // paging.value.reload()
  // queryList(pageNo, pageSize)
  paging.value.reload()
};
// 搜索/清空搜索
const handleSearch = () => {
  // searchValue.value = '';
  console.log(searchValue.value)
  paging.value.reload()
};
const handleSearchClear = () => {
  // searchValue.value = ''
  paging.value.reload()
};
// 加载数据（核心修复）
const queryList = async (pageNo, pageSize) => {
  try {
    const params = {
      roadName: searchValue.value.trim() || '',
      pageNo: pageNo,
      pageSize: pageSize,
      finishState: activeTab.value
    };
    console.log('请求参数：', params);
    const res = await inspectionPlanPage(params);
    console.log('接口返回：', res);
    paging.value.complete(res.list);
  } catch (error) {
    console.error('加载失败：', error);
    // 修复点4：加载失败调用complete(false)
    paging.value?.complete(false);
    uni.showToast({title: '加载失败，请重试', icon: 'none'});
  }
};
// 跳转明细
const gotoDetail = (item) => {
  uni.navigateTo({
    url: `/pages-sub/daily/patrol-manage/pending-plan-detail/index?batchNo=${item.batchNo}&status=${activeTab.value}`
  });
};
// 修复点5：优化页面生命周期逻辑
onLoad(() => {
  // auto=true时，z-paging会自动触发query，此处可省略手动调用；若需强制初始化，可加：
  // paging.value?.triggerQuery();
});
// 仅在页面从明细页返回时，若有数据则刷新当前tab数据（避免干扰上拉加载）
onShow(() => {
  if (planList.value.length > 0 && pageNo.value === 1) {
    queryList();
  }
});
</script>

<style scoped lang="scss">
/* 样式保持不变，仅补充z-paging容器高度 */
.page-container {
  min-height: 100vh;
  background-color: #f8f8f8;
}

.top-fixed {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  background-color: #fff;
  padding-bottom: 10rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

/* 修复：确保列表容器不被顶部遮挡，且z-paging能识别滚动区域 */
.card-list {
  padding: 170rpx 20rpx 20rpx;
  /* 关键：给z-paging足够的滚动空间 */
}

.plan-card {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 15rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.03);
}

.card-content {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.row-item {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  line-height: 1.5;
}

.flex-between {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.label {
  color: #999;
  width: 140rpx;
  flex-shrink: 0;
}

.value {
  color: #333;
  flex: 1;
}

.detail-btn {
  color: #1989fa;
  font-size: 26rpx;
  padding: 0 10rpx;
}


</style>