<template>
  <el-form ref="form" class="image-link-input-form" :model="modelValueObj" :rules="rules">
    <el-form-item label="资源链接" prop="link" required>
      <LinkInput v-model="modelValueObj.link" @change="handleChange"/>
      <FormItemTip>资源链接可为相对路径，也可以为绝对路径！</FormItemTip>
    </el-form-item>
    <el-form-item label="资源图片" prop="image" required>
      <ImageInput v-model="modelValueObj.image" @change="handleChange"/>
      <FormItemTip v-if="imageTip != null && imageTip !== ''">{{ imageTip }}</FormItemTip>
    </el-form-item>
  </el-form>
</template>

<script>
import LinkInput from './LinkInput'
import ImageInput from './ImageInput'

export default {
  name: 'ImageLinkInput',
  components: { ImageInput, LinkInput },
  props: {
    // 值，格式为{ image: '', link: '' }
    modelValue: {
      type: String
    },
    // 图片提示
    imageTip: {
      required: false
    }
  },
  data () {
    return {
      modelValueObj: {
        image: '',
        link: ''
      },
      rules: {
        image: [
          { required: true, message: '请上传图片', trigger: 'blur' }
        ],
        link: [
          { required: true, message: '请输入链接地址', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    modelValue: {
      immediate: true,
      handler () {
        this.initModelValueObj()
      }
    }
  },
  methods: {
    // 初始化值对象
    initModelValueObj () {
      this.modelValueObj.image = null
      this.modelValueObj.link = null
      if (this.modelValue != null && this.modelValue.length > 0) {
        const modelValueObj = JSON.parse(this.modelValue)
        this.modelValueObj.image = modelValueObj.image
        this.modelValueObj.link = modelValueObj.link
      }
    },
    handleChange () {
      this.$emit('update:modelValue', JSON.stringify(this.modelValueObj))
    },
    validate () {
      return this.$refs.form.validate()
    }
  }
}
</script>

<style scoped lang="scss">
.image-link-input-form {
  padding: 0 20px;
  background-color: var(--background-color);
  .el-form-item {
    margin-bottom: 16px;
  }
}
</style>
