<template>
  <div id="file-1">
    <van-row>
      <van-col span="24" class="main">
        <van-col span="24" class="one">
          <van-form @submit="onSubmit">
            <van-field v-model="form.id" name="id" label="数据id" style="display: none" />
            <van-field name="file" label="文件" :rules="[{ required: true, message: '请上传文件' }]">
              <template #input>
                <van-uploader
                  :fileList="form.file"
                  :max-count="1"
                  :after-read="(file) => toUpload(file, 'file')"
                  @delete="(file) => toDelete(file, 'file')"
                  accept="file"
                />
              </template>
            </van-field>
            <div style="margin: 16px">
              <van-button round block type="info" native-type="submit">提交</van-button>
            </div>
          </van-form>
        </van-col>
      </van-col>
    </van-row>
  </div>
</template>

<script>
import { mapState, createNamespacedHelpers } from 'vuex';
const { mapActions: upload } = createNamespacedHelpers('upload');
export default {
  name: 'file-1',
  props: {
    form: { type: Object },
  },
  components: {},
  data: function () {
    return {};
  },
  created() {},
  methods: {
    ...upload(['upload']),
    onSubmit(value) {
      this.$emit('onSubmit', value);
    },
    async toUpload({ file }, model) {
      // 上传,赋值
      const res = await this.upload({ file, dir: 'file' });
      if (this.$checkRes(res)) {
        this.$set(this.form, model, [{ name: res.name, url: res.uri }]);
      }
    },
    toDelete(file, model) {
      const index = this.form[model].findIndex((f) => _.isEqual(f, file));
      this.form[model].splice(index, 1);
    },
  },
  computed: {
    ...mapState(['user']),
  },
  metaInfo() {
    return { title: this.$route.meta.title };
  },
  watch: {
    test: {
      deep: true,
      immediate: true,
      handler(val) {},
    },
  },
};
</script>

<style lang="less" scoped></style>
