<template>
  <div>
    <el-dialog :title="title" :visible.sync="dialogVisible" width="50%" :before-close="handleClose">
      <el-form ref="form" :model="form" :rules="formRules" label-width="80px">
        <el-form-item label="名称" prop="brandName">
          <el-input v-model="form.brandName" maxlength="20" placeholder="请输入品牌名称" />
        </el-form-item>
        <el-form-item label="logo" prop="brandLogo">
          <ImageUpload v-model="form.brandLogo" :limit="1" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import ImageUpload from '@/components/ImageUpload'
import { addBrand, updateBrand } from '@/api/renovation'
const Form = function () {
  this.id = null
  this.brandLogo = null
  this.brandName = null
}
export default {
  name: 'Form',
  components: { ImageUpload },
  model: {
    prop: 'show',
    event: 'change'
  },
  props: {
    show: {
      type: Boolean,
      default: () => true
    },
    item: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      loading: false,
      title: '新增品牌',
      form: {},
      formRules: {
        brandName: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' },
          { max: 20, message: '品牌名称应小于20个字符', trigger: 'blur' }
        ],
        brandLogo: [
          { required: true, message: '请上传品牌logo', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.show
      },
      set(val) {
        this.$emit('change', val)
      }
    }
  },
  watch: {
    'item': {
      deep: true,
      handler() {
        if (this.item) {
          this.form = JSON.parse(JSON.stringify(this.item))
          if (this.form.id !== null || this.form.id !== undefined) {
            this.title = '修改品牌'
          } else {
            this.title = '新增品牌'
          }
        } else {
          this.form = new Form()
        }
      }
    }
  },
  methods: {
    handleSubmit() {
      this.$refs.form.validate(async (val) => {
        this.loading = true
        if (!val) return this.$message.warning('请完善表单')
        if (this.form.id != null) {
          await updateBrand(this.form)
        } else {
          await addBrand(this.form)
        }
        this.$message.success('操作成功')
        this.loading = false
        this.handleClose()
      })
    },
    handleClose() {
      this.$emit('confirm', this.form)
      this.$refs.form.resetFields()
      this.dialogVisible = false
    }
  }
}
</script>

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