<script>
// 查看媒体文件，支持图片和视频
import iconpath from "@/static/images/close.png"

import { updateImg } from "@/api/system";

const imgExts = ['png', 'jpg', 'jpeg', 'gif']
export default {
  name: "MediaList",
  props:{
    readonly:{
      type:Boolean,
      default:false
    },
    // 图片或视频数组
    value: {
      type: Array,
      default: () => []
    },
  },
  data(){
    return {
      iconpath,
      pictureUrls:[]
    }
  },
  computed:{
    isImage(){
      return (url) => {
        const ext = url?.split('.').pop() || ''
        return imgExts.includes(ext.toLowerCase())
      }
    }
  },
  watch:{
    pictureUrls(){
      if(this.value == this.pictureUrls) return
      this.$emit('input', this.pictureUrls)
    },
    value(){
      if(this.value && Array.isArray(this.value) && this.value.length && this.value != this.pictureUrls){
        console.log('watch value then pictureUrls赋值', this.value)
        this.pictureUrls = this.value
      }
    }
  },
  created(options){
    if(this.value && Array.isArray(this.value) && this.value.length){
      console.log('pictureUrls赋值', this.value)
      this.pictureUrls = this.value
    }
  },
  methods:{
    previewImage(url) {
      // 通过后缀判断是图片还是视频
      if (!this.isImage(url)) {
        // 不是图片就当做视频处理
        uni.PLAYER_URL = url
        return uni.navigateTo({
          url: '/pages/utils/player'
        })
      }
      // 通过后缀过滤，只保留图片
      const imgs = this.pictureUrls.filter(item => {
        return this.isImage(item)
      })
      uni.previewImage({
        current: url, //预览图片的下标
        urls: imgs
      })
    },
    onVideoPlay(url){
      this.$refs.player.stop()
      this.previewImage(url)
    },
    chooseVideoImage() {
      uni.showActionSheet({
        title: this.$t('选择上传类型'),
        itemList: [this.$t('图片'), this.$t('视频')],
        success: res => {
          console.log(res);
          if (res.tapIndex == 0) {
            this.chooseImages();
          } else {
            this.chooseVideo();
          }
        }
      });
    },
    chooseImages() {
      uni.chooseImage({
        count: 9, //默认是9张
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], //从相册选择
        success: res => {
          res.tempFilePaths.forEach((item, index) => {
            updateImg(item).then(data => {
              this.pictureUrls.push(data.data)
            })
          })
        }
      })
    },

    //上传视频
    chooseVideo() {
      uni.chooseVideo({
        maxDuration: 60, //拍摄视频最长拍摄时间，单位秒。最长支持 60 秒
        count: 9,
        success: res => {
          let videoFile = res.tempFilePath;
          updateImg(videoFile).then(data => {
            this.pictureUrls.push(data.data)
          })
        },
        fail:(error)=>{
          uni.hideLoading();
          uni.showToast({
            title: error,
            icon: 'none'
          })
        }
      })
    },
    delImage(index) {
      this.pictureUrls.splice(index, 1);
    }
  }
};
</script>

<template>
  <view class="img-wrap">
    <uni-grid :column="4" :highlight="true" :show-border="false">
      <uni-grid-item v-for="(url, index) in pictureUrls.filter(item => {return !!item})" :index="index" :key="index">
        <view class="grid-item-box" style="height: 100%;position: relative;">
          <image v-if="!readonly" :src="iconpath" style="position: absolute;top:4px;right:4px;width:24px;height:24px;z-index:9" @tap="delImage(index)" mode="widthFix"></image>
          <image v-if="isImage(url)" :src="url" mode="scaleToFill" style="height: 100%" @tap="previewImage(url)" />
          <video v-else :id="`video_${index}`" style="width: 100%;height: 100%"
                 :src="url"
                 @tap.stop.prevent="previewImage(url)"
                 @play="onVideoPlay(url)"
                 :controls="false"
                 :autoplay="false"
                 :show-center-play-btn="false"
                 :show-play-btn="false"
          ></video>
        </view>
      </uni-grid-item>
      <uni-grid-item v-if="!readonly">
        <view class="grid-item-box" style="height: 100%">
          <view class="grid-item-box-add" @tap="chooseVideoImage(pictureUrls)">
            <uni-icons type="plusempty" size="30" color="#eae8eb"></uni-icons>
            <!-- <text>添加视频或图片</text> -->
          </view>
        </view>
      </uni-grid-item>
    </uni-grid>

  </view>
</template>

<style scoped lang="scss">
.img-wrap {
  ::v-deep .uni-grid-item {
    background: #fbf8fb;
  }
  .grid-item-box-add {
    height: 100%;
    display: flex;
    flex-flow: column;
    font-size: 10px;
    padding: 16px 0;
    text-align: center;
    justify-content: center;
  }
}
</style>
