index.vue 13.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
<template>
  <view class="min-h-screen bg-gray-50">

    <!-- Upload Area -->
    <view class="p-4">
      <!-- Upload Button -->
      <view
        v-if="!uploadedFile"
        class="border border-dashed border-gray-300 rounded-lg p-8 flex flex-col items-center justify-center mb-4 bg-white"
        @tap="chooseMedia"
      >
        <view class="text-gray-400 mb-4">
          <Photograph size="48" />
        </view>
        <view class="text-center text-gray-600 mb-2 text-sm">选择图片或视频</view>
        <view class="text-center text-gray-400 text-sm">
          支持图片格式(jpg、png)最大10MB或60秒内视频
        </view>
      </view>

      <!-- Preview Area -->
      <view v-if="uploadedFile" class="mb-4">
        <!-- Image Preview -->
        <view v-if="uploadedFile.type === 'image'" class="relative rounded-lg overflow-hidden bg-white shadow-sm">
          <image
            :src="uploadedFile.url"
            class="w-full h-64 object-cover cursor-pointer"
            mode="aspectFit"
            @tap="previewImage"
          />
          <view
            @tap="removeFile"
            class="absolute top-2 right-2 w-8 h-8 bg-black bg-opacity-50 rounded-full flex items-center justify-center"
          >
            <Close size="16" class="text-white" />
          </view>
        </view>

        <!-- Video Preview -->
        <view v-if="uploadedFile.type === 'video'" class="relative rounded-lg overflow-hidden bg-white shadow-sm">
          <view
            class="relative w-full h-64 bg-black rounded-lg flex items-center justify-center"
            @tap="playVideo"
          >
            <image
              v-if="uploadedFile.thumbnail"
              :src="uploadedFile.thumbnail"
              class="w-full h-full object-cover"
              mode="widthFix"
            />
            <view class="absolute inset-0 flex items-center justify-center">
              <view class="w-16 h-16 bg-black bg-opacity-60 rounded-full flex items-center justify-center">
                <image :src="playIcon" class="w-6 h-6" />
              </view>
            </view>
          </view>
          <view
            @tap="removeFile"
            class="absolute top-2 right-2 w-8 h-8 bg-black bg-opacity-50 rounded-full flex items-center justify-center"
          >
            <Close size="16" class="text-white" />
          </view>
        </view>

        <!-- File Info -->
        <view class="mt-3 p-3 bg-white rounded-lg">
          <view class="text-sm text-gray-600">文件大小: {{ formatFileSize(uploadedFile.size) }}</view>
          <view v-if="uploadedFile.type === 'video'" class="text-sm text-gray-600 mt-1">
            时长: {{ formatDuration(uploadedFile.duration) }}
          </view>
        </view>
      </view>

      <!-- Action Buttons -->
      <view class="flex gap-3">
        <view
          @tap="chooseMedia"
          class="flex-1 bg-gray-100 text-gray-700 py-3 rounded-lg text-center text-sm"
        >
          {{ uploadedFile ? '重新选择' : '选择文件' }}
        </view>
        <view
          v-if="uploadedFile"
          @tap="saveMedia"
          class="flex-1 bg-blue-500 text-white py-3 rounded-lg text-center text-sm"
        >
          提交
        </view>
      </view>
      <view class="mt-6 text-sm text-gray-500">
        <view class="mb-2">积分注意事项:</view>
        <view class="text-xs mb-1">• 每张图片或视频积分100分</view>
        <view class="text-xs mb-1">• 每天最多积分100分</view>
      </view>
    </view>

    <!-- Video Player Modal -->
    <view
      v-if="videoVisible"
      class="fixed inset-0 bg-black"
      style="z-index: 9999;"
      @tap="closeVideo"
    >
      <!-- Close Button -->
      <view
        @tap.stop="closeVideo"
        class="absolute top-4 right-4 w-10 h-10 bg-black bg-opacity-50 rounded-full flex items-center justify-center"
        style="z-index: 10000;"
      >
        <Close size="24" class="text-white" />
      </view>

      <!-- Video Player -->
      <video
        v-if="uploadedFile && uploadedFile.type === 'video'"
        :id="'upload-video-' + videoId"
        :src="uploadedFile.url"
        :poster="uploadedFile.thumbnail"
        :controls="true"
        :autoplay="false"
        :show-center-play-btn="true"
        :show-play-btn="true"
        :object-fit="'contain'"
        :show-fullscreen-btn="true"
        style="width: 100vw; height: 50vh; position: absolute; top: 20vh; left: 0;"
        @tap.stop
        @play="handleVideoPlay"
        @pause="handleVideoPause"
        @error="handleVideoError"
        @fullscreenchange="handleFullscreenChange"
      />
    </view>

    <!-- 图片预览 -->
    <nut-image-preview
      v-model:show="previewVisible"
      :images="previewImages"
      :init-no="previewIndex"
      :show-index="false"
      @close="closePreview"
    />
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import Taro from '@tarojs/taro';
import { Photograph, Close } from '@nutui/icons-vue-taro';
import BASE_URL from '@/utils/config';
import { savePhotoAPI } from '@/api/photo';

//
const playIcon = 'https://cdn.ipadbiz.cn/lls_prog/icon/play.svg';
const callbackUrl = BASE_URL + '/srv/?f=walk&a=media&t=qiniu_audit_notify'

// 响应式数据
const uploadedFile = ref(null);
const videoVisible = ref(false);
const videoId = ref(Date.now());

// 图片预览相关
const previewVisible = ref(false);
const previewImages = ref([]);
const previewIndex = ref(0);

// 页面参数
const pageParams = ref({
  from: '',
  id: '',
});

/**
 * 页面加载时获取参数并设置标题
 */
onMounted(() => {
  // 获取页面参数
  const instance = Taro.getCurrentInstance();
  const params = instance.router?.params || {};

  pageParams.value = {
    from: params.from || '',
    id: params.id || '',
  };

  // 根据来源设置页面标题
  const title = pageParams.value.from === 'checkin' ? '上传图片' : '拍照留念';
  Taro.setNavigationBarTitle({ title });
});

/**
 * 选择媒体文件(图片或视频)
 */
const chooseMedia = () => {
  Taro.chooseMedia({
    count: 1,
    mediaType: ['image', 'video'],
    sourceType: ['album', 'camera'],
    maxDuration: 60,
    sizeType: ['compressed'],
    camera: 'back',
    success: async (res) => {
      const file = res.tempFiles[0];

      // 检查文件大小(仅对图片进行10MB限制,视频不检查大小)
      if (file.fileType === 'image' && file.size > 10 * 1024 * 1024) {
        Taro.showToast({
          title: '图片大小不能超过10MB',
          icon: 'none',
          duration: 2000
        });
        return;
      }

      // 检查视频长度(仅对视频进行60秒限制)
      if (file.fileType === 'video' && file.duration > 60) {
        Taro.showToast({
          title: '视频时长不能超过60秒',
          icon: 'none',
          duration: 2000
        });
        return;
      }

      // 显示上传进度
      Taro.showLoading({ title: '上传中...' });

      try {
        // 立即上传文件到服务器
        const serverUrl = await uploadFileToServer(file.tempFilePath, file.fileType);

        // 根据文件类型设置不同的信息,包含服务器URL
        if (file.fileType === 'image') {
          uploadedFile.value = {
            type: 'image',
            url: file.tempFilePath,
            serverUrl: serverUrl.src,
            qiniu_audit: serverUrl.qiniu_audit,
            size: file.size,
            name: `image_${Date.now()}.jpg`
          };
        } else if (file.fileType === 'video') {
          uploadedFile.value = {
            type: 'video',
            url: file.tempFilePath,
            serverUrl: serverUrl.src,
            qiniu_audit: serverUrl.qiniu_audit,
            thumbnail: file.thumbTempFilePath,
            duration: Math.floor(file.duration),
            size: file.size,
            name: `video_${Date.now()}.mp4`,
          };
        }

        Taro.hideLoading();
        Taro.showToast({
          title: '上传成功',
          icon: 'success',
          duration: 1500
        });
      } catch (error) {
        console.error('上传失败:', error);
        Taro.hideLoading();
        Taro.showToast({
          title: '上传失败,请重试',
          icon: 'none',
          duration: 2000
        });
      }
    },
    fail: (err) => {
      console.error('选择媒体文件失败:', err);
      // Taro.showToast({
      //   title: '选择文件失败',
      //   icon: 'error',
      //   duration: 2000
      // });
    }
  });
};

/**
 * 移除文件
 */
const removeFile = () => {
  uploadedFile.value = null;
};

/**
 * 播放视频
 */
const playVideo = () => {
  if (uploadedFile.value && uploadedFile.value.type === 'video') {
    videoId.value = Date.now();
    videoVisible.value = true;
  }
};

/**
 * 关闭视频播放
 */
const closeVideo = () => {
  videoVisible.value = false;
};

/**
 * 预览图片
 */
const previewImage = () => {
  if (!uploadedFile.value || uploadedFile.value.type !== 'image') {
    Taro.showToast({
      title: '暂无图片可预览',
      icon: 'error',
      duration: 2000
    });
    return;
  }
  previewImages.value = [{ src: uploadedFile.value.url }];
  previewIndex.value = 0;
  previewVisible.value = true;
};

/**
 * 关闭图片预览
 */
const closePreview = () => {
  previewVisible.value = false;
};

/**
 * 处理视频播放
 */
const handleVideoPlay = () => {
  console.log('视频开始播放');
};

/**
 * 处理视频暂停
 */
const handleVideoPause = () => {
  console.log('视频暂停播放');
};

/**
 * 处理全屏状态变化
 * @param {Event} event - 全屏事件
 */
const handleFullscreenChange = (event) => {
  console.log('全屏状态变化:', event.detail);
};

/**
 * 处理视频播放错误
 * @param {Event} error - 错误事件
 */
const handleVideoError = (error) => {
  console.error('视频播放错误:', error);
  Taro.showToast({
    title: '视频播放失败',
    icon: 'error',
    duration: 2000
  });
  closeVideo();
};

/**
 * 格式化文件大小
 * @param {number} bytes - 字节数
 * @returns {string} 格式化后的文件大小
 */
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

/**
 * 格式化视频时长
 * @param {number} seconds - 秒数
 * @returns {string} 格式化后的时长
 */
const formatDuration = (seconds) => {
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
};

/**
 * 上传文件到服务器
 * @param {string} filePath - 文件路径
 */
const uploadFileToServer = (filePath, fileType) => {
  return new Promise((resolve, reject) => {
    // 视频上传需要判断回调
    let video_params = ''
    if (fileType === 'video') {
      video_params = '&callback_rul=' + encodeURIComponent(callbackUrl)
    }
    Taro.uploadFile({
      url: BASE_URL + '/admin/?m=srv&a=upload&image_audit=1' + video_params,
      filePath,
      name: 'file',
      header: {
        'content-type': 'multipart/form-data',
      },
      success: function (res) {
        try {
          const upload_data = JSON.parse(res.data);
          if (upload_data.code === 0 && upload_data.data) {
            resolve({ src: upload_data.data.src, qiniu_audit: upload_data.data.audit_result});
          } else {
            reject(new Error(upload_data.msg || '服务器错误'));
          }
        } catch (error) {
          reject(new Error('解析响应数据失败'));
        }
      },
      fail: function (error) {
        reject(error);
      }
    });
  });
};

/**
 * 保存媒体文件
 */
const saveMedia = async () => {
  if (!uploadedFile.value) {
    Taro.showToast({
      title: '请先选择文件',
      icon: 'error',
      duration: 2000
    });
    return;
  }

  if (!uploadedFile.value.serverUrl) {
    Taro.showToast({
      title: '文件上传未完成,请重新选择',
      icon: 'error',
      duration: 2000
    });
    return;
  }

  Taro.showLoading({
    title: '保存中...',
    mask: true
  });

  try {
    // 调用后端接口保存媒体信息
    const saveData = {
      media_type: uploadedFile.value.type === 'image' ? 'IMAGE' : 'VIDEO',
      media_url: uploadedFile.value.serverUrl,
      source_type: pageParams.value.from === 'checkin' ? 'CHECK_IN' : 'COMPANION',
      source_id: pageParams.value.id || '0',
      qiniu_audit: uploadedFile.value.qiniu_audit || '',
    };

    const result = await savePhotoAPI(saveData);

    if (result.code) {
      Taro.hideLoading();
      Taro.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 2000
      });

      // 根据来源进行不同的跳转处理
      setTimeout(() => {
        if (pageParams.value.from === 'checkin') {
          // 如果是从打卡页面跳转过来的,带着参数跳转到海报打卡页面
          Taro.redirectTo({
            url: `/pages/PosterCheckin/index?id=${pageParams.value.id}`
          });
        } else {
          // 其他情况返回上一页
          Taro.navigateBack();
        }
      }, 2000);
    } else {
      throw new Error(result.msg || '保存失败');
    }
  } catch (error) {
    console.error('保存失败:', error);
    Taro.hideLoading();
    Taro.showToast({
      title: error.message || '保存失败,请重试',
      icon: 'error',
      duration: 2000
    });
  }
};
</script>