<template>
  <div class="brand-edit-form">
    <el-form ref="brandEditForm" :model="formData" :rules="rules" label-width="90px">
      <el-form-item label="品牌名:" prop="brandName">
        <el-input v-model="formData.brandName" placeholder="请输入品牌名" maxlength="50" show-word-limit />
      </el-form-item>
      <el-form-item label="品牌logo:" prop="brandLogo">
        <upload-image
          tip="建议尺寸：200px * 200px"
          :image-list="imageList"
          @success="uploadSuccess"
          @remove="onRemoveImage"
        />
        <el-input v-show="false" v-model="formData.brandLogo" />
      </el-form-item>
      <el-form-item label="产地:" prop="producePlace">
        <el-input v-model="formData.producePlace" placeholder="请输入产地" maxlength="50" show-word-limit />
      </el-form-item>
      <el-form-item label="制造商:" prop="manufacturer">
        <el-input v-model="formData.manufacturer" placeholder="请输入制造商" maxlength="50" show-word-limit />
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import UploadImage from '@/components/UploadImage'
import { objectCover } from '@/utils'
export default {
  components: {
    UploadImage
  },
  props: {
    model: {
      type: Object,
      default: () => ({
        infoId: '',
        brandName: '',
        brandLogo: '',
        producePlace: '',
        manufacturer: ''
      }),
      validator: (value) => {
        return ['infoId', 'brandName', 'brandLogo', 'producePlace', 'manufacturer'].every((key) =>
          Object.hasOwnProperty.call(value, key)
        )
      }
    }
  },
  data() {
    return {
      formData: {
        infoId: '',
        brandName: '',
        brandLogo: '',
        producePlace: '',
        manufacturer: ''
      },
      rules: {
        brandName: [{ required: true, message: '请输入品牌名称', trigger: ['blur'] }],
        brandLogo: [{ required: true, message: '请上传品牌logo', trigger: ['change'] }],
        producePlace: [{ required: true, message: '请输入产地', trigger: ['blur'] }],
        manufacturer: [{ required: true, message: '请输入制造商', trigger: ['blur'] }]
      },
      imageList: []
    }
  },
  watch: {
    formData: {
      deep: true,
      handler: function(nval) {
        this.$emit('change', nval)
      }
    }
  },
  created() {
    objectCover(this.formData, this.model)
    if (this.formData.brandLogo) {
      this.imageList = [{ name: '品牌logo', url: this.formData.brandLogo }]
    }
  },
  methods: {
    validate() {
      return this.$refs.brandEditForm?.validate()
    },
    validateField() {
      return this.$refs.brandEditForm?.validateField()
    },
    resetFields() {
      return this.$refs.brandEditForm?.resetFields()
    },
    clearValidate() {
      return this.$refs.brandEditForm?.clearValidate()
    },
    uploadSuccess({ response, file, fileList }) {
      this.imageList = fileList
      this.formData.brandLogo = response.data
    },
    onRemoveImage() {
      this.imageList = []
      this.formData.brandLogo = ''
    }
  }
}
</script>
