<template>
  <van-form ref="form">
    <van-field
      v-model="form.text"
      label="单行文本"
      placeholder="请输入"
      autocapitalize="off"
      autocorrect="off"
      clearable
      required
      name="text"
      :rules="[{ required: true, message: '必填' }]"
    />
    <van-field
      v-model="form.textarea"
      label="多行文本"
      placeholder="请输入"
      autocapitalize="off"
      autocorrect="off"
      clearable
      required
      name="text"
      :rules="[{ required: true, message: '必填' }]"
    />
  </van-form>
</template>
<script>
import { get } from '@/api/demo/url-form'

export default {
  props: {
    readonly: {
      type: Boolean,
      default: false
    },
    params: { // 接收表单传过来
      type: Object
    }
  },
  data() {
    return {
      selectorVisible: false,
      defaultForm: {
        text: '',
        textarea: '',
        number: 0,
        editor: ''
      },
      form: {
      }
    }
  },
  watch: {
    // 路由加载
    '$route.query': {
      handler(val, oldVal) {
        const data = this.$route.query
        if (this.$utils.isNotEmpty(data)) {
          this.loadFormData(data)
        }
      },
      immediate: true
    },
    params: {
      handler(val, oldVal) {
        if (val) {
          this.loadFormData(val.attrs)
        } else {
          this.loadFormData({})
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    loadFormData(attrs) {
      // 主键
      const id = attrs.id
      if (this.$utils.isEmpty(id)) {
        this.form = JSON.parse(JSON.stringify(this.defaultForm))
        return
      }
      this.dialogLoading = true
      get({
        id: id
      }).then(response => {
        this.form = response.data
        this.dialogLoading = false
      }).catch(() => {
        this.dialogLoading = false
      })
    },
    validate() {
      return this.$refs.form.validate()
    },
    /**
     * 获取表单数据
     */
    getFormData() {
      return this.form
    }
  }
}
</script>
