<template>
  <div class="mobile-page-container">
    <!-- 任务列表 -->
    <van-nav-bar left-arrow
      @click-left="router.back()">
      <template #right>
        <span class="search-text"
          @click="showSearch = true">搜索</span>
      </template>
    </van-nav-bar>
    <van-pull-refresh v-model="refreshLoading"
      :pull-distance="100"
      success-text="刷新成功"
      @refresh="onRefresh">
      <van-list v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多结果了"
        class="result-list"
        @load="onLoadMore">
        <van-cell-group inset>
          <!-- <van-swipe-cell v-for="(item, index) in resultList"
            :key="index"> -->
          <van-cell v-for="(item, index) in resultList"
            :key="index"
            @click="handleClickStore(item)"
            class="result-item">
            <template #title>
              <div class="item-title">
                <span>{{ item.storeName }}</span>
                <span>{{ parseTime(item.createTime, '{y}-{m}-{d}') }}</span>
              </div>
            </template>
            <template #label>
              <div class="item-company">{{ item.storeCode }}</div>
              <div class="item-address">{{ item.address }}</div>
            </template>
          </van-cell>
          <template #right>
            <van-button square
              type="danger"
              text="删除"
              @click="deleteFn(item, index)" />
          </template>
          <!-- </van-swipe-cell> -->
        </van-cell-group>
      </van-list>
    </van-pull-refresh>
    <!-- 搜索 -->
    <van-popup v-model:show="showSearch"
      position="right"
      class="wrap">
      <van-nav-bar title="筛选条件" />
      <van-field type="text">
        <template #input>
          <van-search v-model="query.storeName"
            placeholder="输入搜索的勤策终端编码/名称"
            @update:model-value="search"
            class="search-bar" />
        </template>
      </van-field>
      <!-- 日期区间 -->
      <van-field type="text"
        :model-value="query.operDate.map(item => parseTime(item, '{y}-{m}-{d}')).join(' - ')"
        label="日期范围："
        readonly
        placeholder="请选择日期范围"
        @click="showCalendar = true" />
      <!-- 重置按钮 -->
      <van-button icon="replay"
        class="reset-btn"
        block
        @click="resetFn">重置</van-button>
    </van-popup>

    <!-- 搜索日期范围组件 -->
    <van-calendar v-model:show="showCalendar"
      :min-date="minDate"
      :max-date="maxDate"
      :default-date="query.operDate"
      allow-same-day
      type="range"
      @confirm="handleConfirm" />
  </div>
</template>

<script setup>

import { getInspectionTaskListAPI } from '@/api'
import { parseTime } from '@/utils'
const router = useRouter();

// 搜索
const showSearch = ref(false) // 搜索抽屉
const showCalendar = ref(false) // 日期选择器

// 当年 1 月 1 日
const minDate = new Date(new Date().getFullYear(), 0, 1)
// 当月最后一天
const maxDate = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate())
// 获取列表
const query = reactive({
  pageNum: 1,
  pageSize: 10,
  // 当月 1 号到当前日期
  operDate: [new Date(new Date().getFullYear(), new Date().getMonth(), 1), maxDate]
})
const resultList = ref([])
const loading = ref(false);
const finished = ref(true);
const refreshLoading = ref(false)
const getInspectionTaskListFn = async () => {
  const res = await getInspectionTaskListAPI({
    ...query,
    operDateStart: parseTime(query.operDate[0], '{y}-{m}-{d}'),
    operDateEnd: parseTime(query.operDate[1], '{y}-{m}-{d}'),
  })
  resultList.value = [...resultList.value, ...res.data.rows]
  finished.value = res.data.total <= resultList.value.length
}
getInspectionTaskListFn()

// 刷新
const onRefresh = async () => {
  refreshLoading.value = true
  query.pageNum = 1
  query.storeName = ''
  resultList.value = []
  await getInspectionTaskListFn()
  refreshLoading.value = false
}
// 更多
const onLoadMore = async () => {
  query.pageNum++
  await getInspectionTaskListFn()
  loading.value = false
}

// 搜索中重置
const resetFn = () => {
  query.pageNum = 1
  query.storeName = ''
  query.operDate = [new Date(new Date().getFullYear(), new Date().getMonth(), 1), maxDate]
  resultList.value = []
  getInspectionTaskListFn()
}

// 门店点击
const handleClickStore = (item) => {
  router.push({
    path: '/audit_activity/inspectionTask',
    query: {
      storeName: item.storeName,
      storeCode: item.storeCode,
      rstId: item.rstId,
      storePicture: item.storePictures?.split(",")[0]
    }
  })
}

// 路由离开守卫：控制是否缓存
// onBeforeRouteLeave((to, from, next) => {
//   if (to.path === '/audit_activity/sales_point_inspection') {
//     // 强制刷新当前组件
//     resetFn()
//   }
//   next()
// })

// 搜索地址/日期
const search = () => {
  query.pageNum = 1
  resultList.value = []
  getInspectionTaskListFn()
}

// 删除任务
const deleteFn = async (item, index) => {
  // await deleteInspectionTaskAPI({
  //   rstdId: item.rstId
  // })
  // resultList.value.splice(index, 1)
  // showNotify({
  //   message: '删除成功',
  //   type: 'success',
  // })
}

// 日期范围确认
const handleConfirm = (dates) => {
  if (dates.length === 2) {
    query.operDate = dates
    showCalendar.value = false
    search()
  }
}

</script>

<style scoped
  lang="scss">

  .mobile-page-container {
    margin: 0 auto;
    font-size: 16px;
    box-sizing: border-box;
    padding-bottom: 20px;
    background-color: #f5f5f5;
    min-height: 100vh;

    .search-text {
      color: var(--main-color);
    }

    .van-pull-refresh {
      min-height: 100vh;

      .result-list {
        background-color: transparent;
        padding: 0 20px;
        margin-top: 10px;

        .van-cell-group {
          margin: 0;
          background-color: transparent;

          .result-item {
            background-color: white;
            margin-bottom: 10px;

            .item-title {
              font-weight: 600;
              color: #333;
              margin-bottom: 4px;
              display: flex;
              justify-content: space-between;

              span:last-child {
                width: 100px;
                text-align: right;
                display: inline-block;
              }
            }

            .item-company {
              font-size: 14px;
              color: #a6a4a4;
              margin-bottom: 2px;
            }

            .item-address {
              font-size: 13px;
              color: #a6a4a4;
              line-height: 1.4;
            }


          }

          /* 滑动右侧按钮 */
          ::v-deep(.van-swipe-cell__right) {
            height: 100px;

            .van-button {
              height: 100%;
            }
          }
        }

      }
    }

    /* 搜索 */
    .wrap {
      --van-field-label-width: 80px;
      height: 100vh;
      width: 85% !important;

      .van-cell {
        align-items: center;

        .search-bar {
          width: 100%;
          padding: 0;
        }

        ::v-deep(.el-input) {
          width: 100%;
        }

      }

    }

  }
</style>