<template>
  <div class="photos-container">
    <van-nav-bar fixed placeholder :title="isEditMode ? `已选中 ${selectedIds.length} 项` : '相册'">
      <template #right>
        <span @click="toggleEditMode" class="nav-action">
          {{ isEditMode ? '取消' : '管理' }}
        </span>
      </template>
    </van-nav-bar>

    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list v-model="loading" :finished="finished" @load="onLoad">
        <div v-for="group in groupedPhotos" :key="group.date" class="photo-group">
          <div class="group-header">
            <span class="date-title">{{ formatGroupDate(group.date) }}</span>
            <span v-if="isEditMode" class="select-all" @click="selectGroup(group)">
              {{ isGroupSelected(group) ? '取消全选' : '全选' }}
            </span>
          </div>

          <van-grid :column-num="3" :gutter="2" :border="false" square>
            <van-grid-item
              v-for="item in group.children"
              :key="item.fileId"
              @click="onItemClick(item)"
            >
              <van-image width="100%" height="100%" fit="cover" lazy-load :src="item.url" />

              <div v-if="item.type === 'video'" class="video-info-tag">
                <van-icon name="play-circle-o" class="play-icon" />
                <span class="duration">{{ item.duration }}</span>
              </div>

              <div
                v-if="isEditMode"
                class="select-mask"
                :class="{ active: selectedIds.includes(item.fileId) }"
              >
                <van-icon :name="selectedIds.includes(item.fileId) ? 'checked' : 'circle'" />
              </div>
            </van-grid-item>
          </van-grid>
        </div>
      </van-list>
    </van-pull-refresh>

    <transition name="van-slide-up">
      <div v-if="isEditMode" class="bottom-tab-bar">
        <div class="action-item" @click="handleBatchDownload">
          <van-icon name="down" />
          <span>下载</span>
        </div>
        <div class="action-item delete" @click="handleBatchDelete">
          <van-icon name="delete-o" />
          <span>删除</span>
        </div>
      </div>
    </transition>

    <van-popup
      v-model="showPlayerModal"
      position="bottom"
      :style="{ height: '100%' }"
      closeable
      @closed="onVideoPopupClosed"
    >
      <div v-if="currentVideoItem" class="player-container">
        <div class="player-header van-ellipsis">{{ currentVideoItem.filename }}</div>

        <div class="video-wrapper">
          <video
            ref="videoPlayer"
            :src="currentVideoItem.videoUrl"
            controls
            autoplay
            playsinline
            webkit-playsinline
            class="native-video"
          >
            您的浏览器不支持视频播放。
          </video>
        </div>

        <div class="player-info">
          <van-cell title="文件大小" :value="currentVideoItem.size" />
          <van-cell title="拍摄时间" :value="currentVideoItem.updateTime" />
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { getPhotoItems } from '@/api/disk'

export default {
  data() {
    return {
      queryParams: {
        pn: 1
      },
      showPlayerModal: false, // 控制弹窗
      currentVideoItem: null, // 当前播放的视频对象
      photoList: [],
      loading: false, // 是否正在加载
      finished: false, // 是否完成
      refreshing: false, // 是否刷新
      page: 1,
      isEditMode: false, // 是否处于多选模式
      selectedIds: [] // 已选中的照片 ID 列表
    }
  },
  computed: {
    groupedPhotos() {
      return this.groupDataByDate(this.photoList)
    }
  },
  methods: {
    async onLoad() {
      // 1. 如果正在下拉刷新中，不执行滚动加载逻辑
      if (this.refreshing) return

      try {
        // 2. 调用接口（确保传参是当前的 pn）
        const resp = await getPhotoItems(this.queryParams)

        if (resp.code === 0) {
          const respData = resp.data
          const newData = respData.list || []

          // 3. 如果是第一页，直接赋值；否则追加
          if (this.queryParams.pn === 1) {
            this.photoList = newData
          } else {
            this.photoList.push(...newData)
          }

          // 4. 加载状态结束
          this.loading = false

          // 5. 判断是否还有下一页
          // 注意：这里建议优先判断 newData 是否为空，或者使用后端返回的 hasNext
          if (!respData.hasNext || newData.length === 0) {
            this.finished = true
          } else {
            this.queryParams.pn++ // 准备加载下一页
          }
        } else {
          this.$toast(resp.msg)
          this.finished = true
        }
      } catch (error) {
        this.loading = false
        this.finished = true
        this.$toast('加载失败')
      }
    },

    onRefresh() {
      // 下拉刷新的重置逻辑
      this.finished = false
      this.loading = true // 展示加载转圈
      this.refreshing = true

      // 重置参数
      this.queryParams.pn = 1

      // 重新发起请求
      this.onLoad()
    },
    // 转换扁平数据为分组数据
    groupDataByDate(flatList) {
      const groups = {}
      flatList.forEach((item) => {
        // 提取日期部分 (2024-05-09)
        const date = item.updateTime.split(' ')[0]
        if (!groups[date]) {
          groups[date] = []
        }
        groups[date].push(item)
      })

      // 转换为数组格式以便 v-for 渲染
      return Object.keys(groups)
        .map((date) => ({
          date,
          children: groups[date]
        }))
        .sort((a, b) => new Date(b.date) - new Date(a.date)) // 按日期倒序
    },
    formatGroupDate(dateStr) {
      const today = new Date().toISOString().split('T')[0]
      const yesterday = new Date(Date.now() - 86400000).toISOString().split('T')[0]

      if (dateStr === today) return '今天'
      if (dateStr === yesterday) return '昨天'

      // 返回 MM-DD 格式
      return dateStr.split('-').slice(1).join('-')
    },
    // 调用 Vant 的全屏预览
    handlePreview(currentImg) {
      // 获取所有照片的 URL 列表
      const allUrls = this.photoList.map((p) => p.url)
      // 找到当前点击图片在原始扁平数组中的位置
      const startIndex = this.photoList.findIndex((p) => p.id === currentImg.id)

      this.$imagePreview({
        images: allUrls,
        startPosition: startIndex,
        closeable: true
      })
    },
    toggleEditMode() {
      this.isEditMode = !this.isEditMode
      this.selectedIds = [] // 切换模式时清空选中
    },
    onItemClick(item) {
      if (this.isEditMode) {
        this.handleSelect(item.fileId)
      } else {
        if (item.type === 'video') {
          // 唤起视频播放弹窗 (复用之前 Home.vue 里的视频预览逻辑)
          this.previewVideo(item)
        } else {
          // 唤起图片预览
          this.handlePreview(item)
        }
      }
    },

    handleSelect(id) {
      const index = this.selectedIds.indexOf(id)
      if (index > -1) {
        // 如果已经在数组里，说明是要取消选中
        this.selectedIds.splice(index, 1)
      } else {
        // 否则，加入选中列表
        this.selectedIds.push(id)
      }
    },

    // 别忘了补齐 previewVideo 方法 (如果还没从 Home.vue 挪过来的话)
    previewVideo(item) {
      this.currentVideoItem = item
      this.showPlayerModal = true
    },

    // 弹窗关闭后的清理逻辑
    onVideoPopupClosed() {
      if (this.$refs.videoPlayer) {
        this.$refs.videoPlayer.pause() // 停止播放防止后台有声音
      }
      this.currentVideoItem = null
    },

    // 组全选逻辑
    selectGroup(group) {
      const groupIds = group.children.map((img) => img.id)
      if (this.isGroupSelected(group)) {
        // 如果已全选，则该组全部取消
        this.selectedIds = this.selectedIds.filter((id) => !groupIds.includes(id))
      } else {
        // 否则将该组未选中的 ID 加入
        groupIds.forEach((id) => {
          if (!this.selectedIds.includes(id)) this.selectedIds.push(id)
        })
      }
    },

    isGroupSelected(group) {
      return group.children.every((img) => this.selectedIds.includes(img.id))
    },

    handleBatchDownload() {
      console.log('handleBatchDownload')
    },

    handleBatchDelete() {
      if (this.selectedIds.length === 0) return this.$toast('请先选择照片')

      this.$dialog
        .confirm({
          title: '确认删除',
          message: `确定要删除这 ${this.selectedIds.length} 张照片吗？`,
          confirmButtonColor: '#ee0a24'
        })
        .then(() => {
          // 模拟删除
          this.photoList = this.photoList.filter((img) => !this.selectedIds.includes(img.id))
          this.isEditMode = false
          this.selectedIds = []
          this.$toast.success('删除成功')
        })
    }
  }
}
</script>

<style lang="less" scoped>
.nav-action {
  color: #1989fa;
  font-size: 14px;
}

.select-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: flex-end;
  padding: 5px;

  &.active {
    background: rgba(25, 137, 250, 0.2);
    border: 2px solid #1989fa;
    box-sizing: border-box;
  }

  .select-icon {
    font-size: 20px;
    color: #ebedf0;
  }

  &.active .select-icon {
    color: #1989fa;
  }
}

.bottom-tab-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50px;
  background: #fff;
  display: flex;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  z-index: 100;

  .action-item {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    font-size: 10px;
    color: #646566;

    .van-icon {
      font-size: 20px;
      margin-bottom: 2px;
    }

    &.delete {
      color: #ee0a24;
    }
  }
}

.select-all {
  font-size: 12px;
  color: #1989fa;
}

.video-info-tag {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 4px 6px;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.5));
  display: flex;
  align-items: center;
  justify-content: space-between;
  pointer-events: none; /* 确保不影响点击事件 */

  .play-icon {
    color: #fff;
    font-size: 14px;
  }

  .duration {
    color: #fff;
    font-size: 11px;
    font-weight: 500;
  }
}

/* 视频播放器弹窗样式 */
.player-container {
  background: #000;
  height: 100%;
  display: flex;
  flex-direction: column;

  .player-header {
    padding: 15px 45px; // 留出关闭按钮的空间
    text-align: center;
    font-size: 16px;
    color: #fff;
    background: rgba(0, 0, 0, 0.8);
  }

  .video-wrapper {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #000;
  }

  .native-video {
    width: 100%;
    max-height: 80vh;
    object-fit: contain; // 保持视频比例，不拉伸
  }

  .player-info {
    padding-bottom: 20px;
    // 调整内部 Cell 为深色风格
    /deep/ .van-cell {
      background-color: #1a1a1a;
      color: #eee;
      &::after {
        border-bottom: 1px solid #333;
      }
      .van-cell__value {
        color: #aaa;
      }
    }
  }
}

/* 覆盖 Vant Popup 的关闭按钮颜色，使其在黑底上可见 */
/deep/ .van-popup__close-icon {
  color: #fff;
}
</style>
