<!-- 移动端上传图片/视频组件 -->
<template>
  <div class="xl-mobile-upload">
    <!-- 苹果设备上传组件 -->
    <van-uploader ref="uploaderRef"
      :max-count="maxCount"
      :accept="supportedTypes"
      :model-value="photoList"
      :after-read="commitStorePhotosRead"
      preview-size="2.13333rem"
      @delete="deleteCommitStorePhotos"
      :max-size="bigSize"
      @oversize="onOversize">
      <!-- 自定义上传按钮 -->
      <template #default>
        <!-- <div class="upload-btn">
          <van-icon name="photograph" />
        </div> -->
        <div class="upload-btn"
          @click.stop="customUploadClick">
          <van-icon name="photograph" />
        </div>

        <!-- iOS设备或不支持视频的安卓设备：使用默认上传按钮（由van-uploader自动处理点击） -->
        <!-- <div v-else
          class="upload-btn">
          <van-icon name="photograph" />
        </div> -->
      </template>

      <!-- 自定义预览内容 -->
      <template #preview-cover="{ url, index }">
        <div class="preview-container"
          @click.stop>
          <!-- 图片预览 -->
          <van-image v-if="getMediaType(url) === 'image'"
            :src="url"
            alt=""
            class="preview-media"
            fit="cover"
            @click="previewImage(url)" />

          <!-- 视频预览 -->
          <div class="video-wrap"
            v-else-if="getMediaType(url) === 'video'">
            <video :src="url"
              alt=""
              ref="videoRef"
              muted
              autoplay
              playsinline
              preload="auto"
              class="preview-media"
              @loadeddata="handleVideoLoaded" />

            <div class="play-hint"
              @click.stop="showVideoFullscreen(url)">
            </div>
          </div>

          <!-- 删除按钮 -->
          <van-icon name="clear"
            class="delete-icon" />

          <!-- 类型标识 -->
          <span v-if="getMediaType(url) === 'video'"
            class="video-tag">
            视频
          </span>
        </div>
      </template>
    </van-uploader>

    <!-- 拍照方式选择 -->
    <van-action-sheet v-model:show="show"
      :actions="actions"
      teleport="body"
      @select="onSelect" />
  </div>
</template>

<script setup>
import { showImagePreview } from 'vant'
import { getMobileType } from '@/views/mobile/utils'
import { getMediaType } from '@/utils'
const emits = defineEmits(['confirm', 'delete'])
const props = defineProps({
  // 最多支持上传数量
  maxCount: {
    type: Number,
    default: 1
  },
  // 支持视频上传
  supportVideo: {
    type: Boolean,
    default: false
  },
  // 文件组回显
  photoList: { // 回显
    type: Array,
    default: () => []
  },
  // 多张照片，本照片索引
  name: {
    type: [String, Number],
    default: ''
  }
})
/**************** 工具函数 ***************/
// 计算支持的文件类型
const supportedTypes = computed(() => {
  if (props.supportVideo) {
    // 判断安卓还是苹果设备返回不同的字符串
    if (getMobileType() === 'ios') {
      return 'image/*,video/*'
    } else {
      if (selectedMediaType.value === 'image') {
        return 'image/*'
      } else {
        return 'video/*'
      }
    }
  }
  return 'image/*'
})
// 自定义点击拍照按钮效果
const customUploadClick = () => {
  if (getMobileType() === 'ios') {
    // 苹果设备：直接触发点击事件
    nextTick(() => {
      const inputElement = uploaderRef.value.$el.querySelector('input[type="file"]')
      if (inputElement) {
        inputElement.click()
      }
    })
  } else {
    // 安卓设备：显示拍照/录像方式确认菜单
    show.value = true
  }
}
/*************** android 拍照/录像方式确认 ***************/
// 显示菜单
const show = ref(false)
// 拍照/录像方式列表
const actions = ref([
  {
    name: '拍照片',
    type: 'image'
  },
  {
    name: '拍视频',
    type: 'video'
  }
])
// 安卓：拍照/录像方式确认
const onSelect = (item) => {
  selectedMediaType.value = item.type
  nextTick(() => {
    if (uploaderRef.value) {
      // 获取uploader组件实例
      const uploaderInstance = uploaderRef.value

      // 方法1: 如果组件暴露了open或click方法，则模拟一次点击上传
      if (uploaderInstance.open) {
        uploaderInstance.open()
      } else if (uploaderInstance.click) {
        uploaderInstance.click()
      } else {
        // 方法2: 直接查找内部的input元素并触发点击
        // 查找uploader组件内的input[type="file"]元素
        const inputElement = uploaderInstance.$el.querySelector('input[type="file"]')
        if (inputElement) {
          // 触发点击事件
          inputElement.click()
        } else {
          console.error('未找到文件上传input元素')
        }
      }
    } else {
      console.error('uploader组件未加载完成')
    }

    // 隐藏底部选择菜单
    show.value = false
  })

}
// 上传组件和选择类型
const uploaderRef = ref(null)
const selectedMediaType = ref('')

/*************** 上传照片 ***************/
// 上传照片
const commitStorePhotosRead = async (file) => {
  emits('confirm', file, { name: props.name })
}
// 删除照片
const deleteCommitStorePhotos = async (file, { name, index }) => {
  emits('delete', '', { name: props.name, index })
}
// 文件大小限制
const bigSize = 50 * 1024 * 1024
const onOversize = (file) => {
  showNotify({ type: 'danger', message: '文件大小不能超过 5 MB' })
}

/*************** 图片/视频预览 ***************/
// 图片预览
const previewImage = (url) => {
  showImagePreview({
    images: [url],
  })
}

// 视频相关状态
const videoRef = ref(null)
const isPlaying = ref(true)

// 加载完第一帧暂停
const handleVideoLoaded = () => {
  isPlaying.value = false
  videoRef.value.pause()
}

// 全屏播放
const showVideoFullscreen = async (url) => {
  const video = videoRef.value;
  if (!video) return;

  try {
    // 先尝试播放视频
    await video.play();

    // 然后尝试全屏（跨浏览器兼容）
    if (!document.fullscreenElement) {
      await requestFullscreen(video).catch(err => {
        console.error('全屏请求失败，但不影响播放:', err);
      });
    }
  } catch (err) {
    console.error('视频操作失败:', err);
  }
};

// 跨浏览器请求全屏（保留之前的实现）
const requestFullscreen = (element) => {
  if (!element) return Promise.reject(new Error('video 标签不存在'));

  const methods = [
    // 标准API
    () => element.requestFullscreen(),
    // WebKit (Safari, Chrome) 
    () => element.webkitRequestFullscreen(),
    // iOS Safari特定API
    () => {
      if (element.webkitEnterFullscreen) {
        element.webkitEnterFullscreen();
        return Promise.resolve();
      }
      return Promise.reject(new Error('不支持全屏播放'));
    }
  ];

  // 尝试各种方法
  return new Promise((resolve, reject) => {
    for (const method of methods) {
      try {
        const result = method();
        if (result && result.then) {
          result.then(resolve).catch(() => { });
        } else {
          resolve();
          return;
        }
      } catch (err) {
        // 尝试下一个方法
        continue;
      }
    }
    reject(new Error('所有全屏播放方法失败'));
  });
};
</script>

<style scoped
  lang="scss">
  .xl-mobile-upload {

    .van-uploader {
      ::v-deep(.van-uploader__wrapper) {
        gap: 10px;

        /* 自定义上传区域样式 */
        .van-uploader__input-wrapper {
          width: 80px;
          height: 80px;

          .upload-btn {
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #f8f8f8;
            width: 80px;
            height: 80px;
            border: 1px dashed #ccc;
            border-radius: 4px;
            color: #dcdee0;
            font-size: 24px;
            position: absolute;
            top: 0;
            left: 0;
            z-index: 10;
          }
        }

      }
    }

    /* 预览区域 */
    ::v-deep(.van-uploader__preview) {
      margin: 0;

      .preview-container {
        position: relative;
        width: 100%;
        height: 100%;
        border-radius: 8px;
        overflow: hidden;

        .video-wrap {
          width: 100%;
          height: 100%;

          .play-hint {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
          }
        }

        .preview-media {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        .video-tag {
          position: absolute;
          bottom: 4px;
          right: 4px;
          background-color: rgba(0, 0, 0, 0.5);
          color: white;
          font-size: 12px;
          padding: 2px 6px;
          border-radius: 4px;
        }


        .delete-icon {
          position: absolute;
          top: -6px;
          right: -6px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 24px;
        }
      }
    }

    /* 原来上传预览内容样式 */
    ::v-deep(.van-uploader__file) {
      .van-badge__wrapper {
        display: none;
      }

      .van-ellipsis {
        display: none;
      }
    }
  }



</style>