<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" style="margin-bottom: 10px;display:flex;flex-direction:row;justify-content:space-between;align-items:center;">
      <a :href="file.url" target="__blank" >
        {{file.name}}
      </a>
      <common-svg name="shanchu1" @click.native="del(index)"></common-svg>
    </div>
    <input type="file" @change="handleFileChange" id="uploader" accept=".pdf" :value="file" style="display:none;">
    <label for="uploader" class="uploader">
      <common-svg name="shangchuantupian1" 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 TypeTwo extends Vue {
  @Prop()
  private proofSubItem: any;
  @Prop()
  private value!: any;
  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 input = e.target;
    const files = input.files;
    if (files && files[0]) {
      this.$api.file.upload(files[0]).then((res: any) => {
        e.target.value = '';
        this.file = '';
        const temp: any = Array.isArray(this.value) ? this.value : [];
        this.$emit('update:value', [...temp, {
          type: 'file',
          format: 'hash',
          value: res.hash,
        }]);
      });
    }
  }
}
</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>
