<template>
  <div id="upload-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
              readonly
              clickable
              name="calendar"
              :value="form.answer_date"
              label="答题时间"
              placeholder="点击选择日期"
              @click="showCalendar = true"
              :rules="[{ required: true, message: '答题时间' }]"
            />
            <van-calendar v-model="showCalendar" @confirm="onConfirm" />
            <van-field
              v-model="form.answer_explain"
              name="answer_explain"
              label="答题说明"
              autosize
              type="textarea"
              rows="1"
              :rules="[{ required: true, message: '答题说明' }]"
            />
            <van-field name="answer_file" label="答题文件" :rules="[{ required: false, message: '答题文件' }]">
              <template #input>
                <van-uploader
                  :fileList="form.answer_file"
                  :max-count="1"
                  :after-read="(file) => toUpload(file, 'answer_file')"
                  @delete="(file) => toDelete(file, 'answer_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');
const moment = require('moment');
export default {
  name: 'upload-1',
  props: {
    form: { type: Object },
  },
  components: {},
  data: function () {
    return {
      // 答题时间
      showCalendar: false,
    };
  },
  created() {},
  methods: {
    ...upload(['upload']),
    // 提交
    onSubmit(values) {
      if (values) this.$emit('onSubmit', { data: this.form });
    },
    // 确认选择时间
    onConfirm(values) {
      this.$set(this.form, 'answer_date', moment(values).format('YYYY-MM-DD'));
      this.showCalendar = false;
    },
    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>
