<template>
  <a-drawer
    :width="500"
    :visible="visible"
    :title="id ? '编辑' : '新增'"
    @close="close"
  >
    <a-form :form="form" layout="vertical">
      <a-form-item label="描述">
        <a-input v-decorator="['description']" />
      </a-form-item>
      <ImageUpload
        label="图片"
        decoration="url"
        :formItemLayout="null"
        :required="true"
        ref="image"
        :form="form"
      />
      <a-form-item label="排序">
        <a-input-number v-decorator="['showOrder']" defaultValue="0" />
      </a-form-item>
      <a-form-item label="跳转类型">
        <a-select
          v-decorator="['type']"
          defaultValue="0"
          :options="[
            { label: '不跳转', value: 0 },
            { label: '公众号文章', value: 2 }
          ]"
          @change="typeChange"
        />
      </a-form-item>
      <a-form-item v-if="type == 2" label="文章链接">
        <a-input
          v-decorator="[
            'mpArticle',
            { rules: [{ required: true, message: '请输入文章链接' }] }
          ]"
        />
      </a-form-item>
    </a-form>

    <div class="drawer-form-bottom-toolbar">
      <a-button :style="{ marginRight: '8px' }" @click="close"> 取消 </a-button>
      <a-button type="primary" v-if="hasPerm('SYS02102.EDIT')" @click="submit"> 保存 </a-button>
    </div>
  </a-drawer>
</template>
<script>
import ImageUpload from '@/components/image-upload/ImageUpload'
import { save, getDetail } from '@/api/banner'

export default {
  name: 'BannerEdit',
  components: { ImageUpload },
  props: { success: Function },
  data() {
    return {
      form: this.$form.createForm(this),
      visible: false,
      id: null,
      type: 0
    }
  },
  methods: {
    show(id) {
      console.info('id', id)
      this.id = id
      this.visible = true
      if (this.id) {
        getDetail(this.id).then(({ data }) => {
          this.type = data.type
          this.$nextTick(() => {
            this.form.setFieldsValue(data)
          })
          this.$refs.image.setValue([data.url])
        })
      }
    },
    close() {
      this.id = null
      this.$refs.image.reset()
      this.form.resetFields()
      this.type = 0
      this.form.setFieldsValue({ type: 0 })
      this.visible = false
    },
    typeChange(value) {
      this.type = value
    },
    submit() {
      this.form.validateFields((err, values) => {
        if (err) {
          return
        }
        const reqData = {
          ...values,
          url: this.$refs.image.getValue()[0],
          id: this.id
        }
        save(reqData).then(({ code }) => {
          if (code == 200) {
            this.$message.success('保存成功')
            this.close()
            this.success()
          }
        })
      })
    }
  }
}
</script>