<template>
  <div class="van-hairline--bottom type-two">
    <div class="title" style="margin-bottom: 10px;">{{proofSubItem.label}}</div>
    <div v-for="(file,index) in fileList" :key="index">
      <audio controls :src="file.url">
      </audio>
      <div style="text-align:right;color:#3175FF;" @click="del(index)">删除</div>
    </div>
    <input type="file" @change="handleFileChange" id="uploader1" accept="audio/*" :value="file" style="display:none;">
    <label for="uploader1" class="uploader">
      <common-svg name="yinpin" width="32px" height="32px"></common-svg>
      <div class="title">上传音频</div>
      <common-svg name="jinru" class="righticon"></common-svg>
    </label>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Model, Emit, Vue, Watch } from 'vue-property-decorator';
import { Field, Uploader, Image } from 'vant';
@Component({
  components: {
    [Field.name]: Field,
    [Uploader.name]: Uploader,
    [Image.name]: Image,
  },
})
export default class TypeNine extends Vue {
  @Prop()
  private proofSubItem: any;
  @Prop()
  private value!: [];
  private fileList: any[] = [];
  private file: any = '';
  @Watch('valHash', { immediate: true, deep: true })
  private async onChange(newVal: [], oldVal: []) {
    if (newVal.length <= 0) {
      this.fileList = [];
      return;
    }
    this.$api.file.getFiles(newVal).then((res: any) => {
      this.fileList = res.files;
    });
  }
  get valHash() {
    if (!Array.isArray(this.value)) {
      return [];
    }
    return this.value.map((val: any) => {
        return val.value;
    });
  }
  private del(index: number) {
    const value = [...this.value];
    value.splice(index, 1);
    this.$emit('update:value', value);
  }
  private handleFileChange(e: any) {
    const [ file ] = e.target.files;
    if (!file) { return; }
    const toast = this.$toast({
      message: '0%',
      duration: 0, // 持续展示 toast
      forbidClick: true,
    });
    this.$api.file.upload(file, (process: any) => {
      const { loaded, total } = process;
      const percent = Math.floor(loaded / total * 100);
      toast.message = `${ percent }%`;
      if (percent === 100) {
        toast.clear();
      }
    }).then((res: any) => {
      e.target.value = '';
      this.file = '';
      const temp: any = Array.isArray(this.value) ? this.value : [];
      this.$emit('update:value', [...temp, {
        type: 'media',
        format: 'hash',
        value: res.hash,
      }]);
    }).catch((err: any) => {
      toast.clear();
    });
  }
}
</script>
<style lang="scss" scoped>
audio{
  width: 100%;
}
  .type-two{
    text-align: left;
    padding-bottom: 10px;
    a{
      word-break: break-all;
      white-space: wrap;
    }
    .uploader{
      display: flex;
      flex-direction: row;
      align-items: center;
      .title{
        flex: auto;
        align-content: flex-start;
        margin-left: 12px;
      }
    }
  } 
</style>
