<template>
  <view class="page-container">
    <!-- 顶部吸顶区域 -->
    <up-sticky>
      <view class="sticky-header">
        <!-- 状态Tabs -->
        <up-tabs
            v-model="activeStatus"
            :list="statusTabs"
            line-width="40rpx"
            active-color="#1989fa"
            inactive-color="#666"
            :scrollable="true"
            class="status-tabs"
            @click="handleStatusChange"
        ></up-tabs>

        <!-- 搜索框 -->
        <up-search
            v-model="searchValue"
            :placeholder="searchPlaceholder"
            bg-color="#f5f5f5"
            shape="round"
            :show-action="true"
            actionText="搜索"
            :animation="true"
            @search="handleSearch"
            @custom="handleSearch"
            :clearabled="false"
            maxlength="50"
            class="search-input"
        ></up-search>
      </view>
    </up-sticky>

    <!-- 分页列表区域 -->
    <z-paging
        ref="pagingRef"
        v-model="planList"
        @query="queryList"
        :auto-show-system-loading="true"
    >
      <!-- 空数据插槽 -->
      <template #empty>
        <empty-view/>
      </template>
      <view class="common-card-list" style=" padding-top: 170rpx;">
        <up-card
            :border="false"
            :foot-border-top="false"
            v-for="(item,index) in planList"
            :key="`${item.planNo}_${index}`"
        >
          <!-- 自定义标题区域 -->
          <template #head>
              <view class="card-header">
                <view class="common-card-title common-name">{{ item.planName || '无计划名称' }}{{ item.planName || '无计划名称' }}</view>
                <!-- 已失效标识 -->
                <view v-show="item.finishState == 3 "  class="common-invalid-tag">已失效</view>
                <view v-show="item.finishState == 2 "  class="common-finish-tag">已完成</view>
              </view>
          </template>

          <template #body>
            <view class="card-body">
              <view class="u-body-item u-flex">
                <view class="u-body-item-title">计划编码：</view>
                <view class="u-line-1 u-body-value">{{ item.planNo || '-' }}</view>
              </view>
              <view class="u-body-item u-flex">
                <view class="u-body-item-title">养护周期：</view>
                <view class="u-line-1 u-body-value">{{ item.rate || '-' }}
                  {{ uni.$dict.getDictLabel('cycle_id_type', item.cycleId) }}
                </view>
              </view>

              <view class="u-body-item u-flex common-item-center common-justify-between">
                <view class="u-body-item-title">计划完成次数： {{ item.planNum || 0 }}</view>
                <view class="">
                  <up-button
                      type="primary"
                      size="mini"
                      @click="submitRecord(item)"
                      class="submit-record-btn"

                      :disabled="item.finishState == 3"

                  >

                    {{ item.finishState ==3 ? '补交记录' : '提交记录' }}
                  </up-button>

<!--                  :class="{ 'disabled-btn': item.finishState ==3 }"-->
<!--                  <up-button-->
<!--                      v-if="item.finishState ==3"-->
<!--                      type="primary"-->
<!--                      size="mini"-->
<!--                      @click=""-->
<!--                      class="submit-record-btn"-->
<!--                      :disabled="true"-->
<!--                  >-->
<!--                    补交记录-->
<!--                  </up-button>-->

<!--                  <up-button-->
<!--                      v-if="item.finishState !== '3' && item.planFinishNum>0"-->
<!--                      type="primary"-->
<!--                      size="mini"-->
<!--                      @click="gotoFinishPlanDetail(item)"-->
<!--                      class="submit-record-btn"-->
<!--                  >-->
<!--                    提交记录-->
<!--                  </up-button>-->
                </view>
              </view>

              <view class="u-body-item u-flex">
                <view class="u-body-item-title">完成次数：</view>
                <view class="u-line-1 u-body-value">{{ item.planFinishNum || 0 }}</view>
              </view>

              <view class="u-body-item u-flex">
                <view class="u-body-item-title">计划有效期：</view>
                <view class="u-line-1 u-body-value">{{ timeFormat(item.beginTime, 'yyyy-mm-dd') || '-' }} 至
                  {{ timeFormat(item.endTime, 'yyyy-mm-dd') || '-' }}
                </view>
              </view>
            </view>
          </template>
        </up-card>
      </view>
    </z-paging>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { timeFormat } from '@/uni_modules/uview-plus'
import { getRoadDetails } from "@/api/maintain-manage/maintain-manage";
// ========== 基础数据定义 ==========
const statusTabs = ref([
  {name: '待完成', id: '1'},
  {name: '已失效', id: '3'},
  {name: '已完成', id: '2'},
  { name: '已终止', id: '4' }
])
const activeStatus = ref('1')
const searchValue = ref('')
const planList = ref([])
const pagingRef = ref(null)
const roadId = ref('')
const finishState = ref('')
// 搜索占位符
const searchPlaceholder = ref('请输入计划名称')
// ========== 方法定义 ==========
const getUrlParams = (options) => {
  if (options?.roadId) {
    roadId.value = options.roadId
    console.log('从URL获取的roadId：', roadId.value)
  }
  if (options?.finish_state) {
    finishState.value = options.finish_state
    // activeStatus.value = options.finish_state
    console.log('从URL获取的finish_state：', finishState.value)
  }
}
const handleStatusChange = (item) => {
  console.log('切换状态：', item)
  activeStatus.value = item.id
  finishState.value = item.id
  pagingRef.value?.reload()
}
const handleSearch = () => {
  console.log('搜索关键词：', searchValue.value)
  pagingRef.value?.reload()
}
const submitRecord = (item) => {
  // 已失效状态下直接返回，不执行跳转
  if (item.finishState === '3') {
    return
  }
  console.log('提交记录：', item.planFinishNum)
  if (item.planFinishNum == 0) {
    uni.navigateTo({
      url: `/pages-sub/daily/maintain-manage/add-record?finishState=${item.finishState}&planNo=${item.planNo}`
    })
  } else {
    uni.navigateTo({
      url: `/pages-sub/daily/maintain-manage/pending-plan-detail?finishState=${item.finishState}&planNo=${item.planNo}&planTypeId=${item.planTypeId}`
    })
  }
}
const queryList = async (pageNo, pageSize) => {
  try {
    const paramsData = {
      pageNo: pageNo,
      pageSize: pageSize,
      roadId: roadId.value,
      finishState: activeStatus.value,
      planName: searchValue.value.trim()
    }
    console.log('请求参数：', paramsData)
    const res = await getRoadDetails(paramsData)
    console.log(res)
    const listData = res?.list || res || []
    pagingRef.value?.complete(listData)
  } catch (error) {
    console.error('请求失败：', error)
    uni.showToast({title: '加载失败，请重试', icon: 'none'})
    pagingRef.value?.complete(false)
  }
}
// ========== 生命周期 ==========
onLoad((options) => {
  getUrlParams(options)
})
onShow(() => {
  // if (roadId.value) {
  //   pagingRef.value?.reload()
  // }
  pagingRef.value?.reload()
})

</script>

<style scoped lang="scss">
.page-container {
}
// 顶部吸顶区域样式
.sticky-header {
  margin-top: -10rpx;
  background-color: #ffffff;
  padding-bottom: 10rpx;
  border-bottom: 1px solid #eee;

  .search-input {
    margin: 20rpx 20rpx 10rpx !important;
  }
}



</style>