<template>
  <card title="学员提交" style="margin:0 20px;">
    <v-form
      ref="form"
      :model="formModel"
      :fields="fields"
      @submit="onSubmit"
      @fileStatus="fileStatus"
    >
      <input
        type="button"
        value="上传"
        class="submit-button"
        @click="handleSubmit"
      />
    </v-form>
  </card>
</template>

<script>
import Card from '@/components/Card'
import VForm from '@/components/Form'
import * as api from '@/api'

export default {
  name: 'submitStudent',
  components: { Card, VForm },
  data() {
    return {
      formModel: { photos: [], videos: [] },
      fields: [
        {
          name: 'mobile',
          label: '手机号',
          required: true,
          placeholder: '请输入手机号',
          maxlength: '11',
          rules: [
            { required: true, message: '请输入手机号' },
            { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式错误' }
          ]
        },
        {
          fieldType: 'upliadMultiple',
          name: 'photos',
          label: '照片',
          required: true,
          placeholder: '请上传照片'
        },
        {
          fieldType: 'video',
          name: 'videos',
          label: '视频',
          required: true,
          placeholder: '请上传视频'
        }
      ],
      type: false
    }
  },
  watch: {
    $route: {
      immediate: true,
      deep: true,
      handler(route) {
        this.formModel = Object.assign(this.formModel, route.query)
      }
    }
  },
  methods: {
    fileStatus(state) {
      this.type = state
    },
    handleSubmit() {
      this.$refs.form.submit()
    },
    onSubmit(data) {
      const ruleForm = this.$refs.form.ruleForm
      if (!ruleForm.photos.length || ruleForm.photos.length === 0) {
        this.$toast('请上传照片')
        return
      }
      if (!ruleForm.videos.length || ruleForm.videos.length === 0) {
        this.$toast('请上传视频')
        return
      }
      if (this.type) {
        this.$toast('正在上传文件，请稍后')
        return
      }
      const params = {
        mobile: data.mobile,
        photos: JSON.stringify(ruleForm.photos.map(k => k.url)),
        videos: JSON.stringify(ruleForm.videos.map(k => k.url))
      }
      api.addSubmitStudent(params).then(response => {
        if (response.success) {
          this.$dialog
            .alert({
              confirmButtonText: '确定',
              message: '上传成功'
            })
            .then(() => {})
        } else {
          this.$toast(response.message)
        }
      })
    }
  }
}
</script>

<style lang="scss"></style>
