<template>
  <div class="van-hairline--bottom type-one">
    <div class="title">{{proofSubItem.label}}</div>
    <van-uploader :after-read="afterRead" v-model="fileList" :max-count="10" :before-delete="beforeDel" :max-size="1 * 1024 * 1024" @oversize="onOversize"></van-uploader>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Model, Emit, Vue, Watch } from 'vue-property-decorator';
import { Field, Uploader } from 'vant';
@Component({
  components: {
    [Field.name]: Field,
    [Uploader.name]: Uploader,
  },
})
export default class TypeOne extends Vue {
  @Prop()
  private proofSubItem: any;
  @Prop()
  private value!: [];
  private fileList: 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 afterRead(file: any) {
    if (!Array.isArray(file)) {
      this.$api.file.upload(file.file).then((res: any) => {
        const temp: any = Array.isArray(this.value) ? this.value : [];
        this.$emit('update:value', [...temp, {
          type: 'image',
          format: 'hash',
          value: res.hash,
        }]);
      });
    }
  }
  private beforeDel(file: any, detail: any) {
    const fileHashes = [...this.value];
    fileHashes.splice(detail.index, 1);
    this.$emit('update:value', fileHashes);
    return true;
  }
  private onOversize(file: any) {
    this.$toast('超出大小限制');
  }
}
</script>
<style lang="scss" scoped>
  .type-one{
    text-align: left;
    .title{
      margin-bottom: 10px;
    }

  }
</style>
