<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: '照片',
          placeholder: '请上传照片'
        },
        {
          fieldType: 'video',
          name: 'videos',
          label: '视频',
          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 (this.type) {
        this.$toast('正在上传文件，请稍后')
        return
      }
      const params = {
        mobile: data.mobile,
        photos: '',
        videos: ''
      }
      if (data.photos.length > 0) {
        params.photos = JSON.stringify(ruleForm.photos.map(k => k.url))
      }
      if (data.videos.length > 0) {
        params.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>
