<template>
  <el-dialog :title="title" :visible.sync="dialogFormVisible" width="500px" @close="close">
    <el-form ref="form" label-width="80px" :model="form" :rules="rules">
      <el-form-item label="头像框" prop="imageUrl">
        <single-upload
          v-model="form.imageUrl"
          style="width: 100px; height: 100px"
          :upload-url="uploadUrl"
          @upload-success="handleUploadSuccess"
        />
      </el-form-item>
      <el-form-item label="是否启用" prop="isEnabled">
        <el-switch v-model="form.isEnabled" active-text="启用" :active-value="true" inactive-text="禁用" :inactive-value="false" />
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { doEdit, doAdd } from '@/api/spring/avatar/frame'
  import SingleUpload from '@/components/SingleUpload'

  export default {
    name: 'AppManagementEdit',
    components: { SingleUpload },
    data() {
      return {
        id: '',
        form: {
          imageUrl: '',
          isEnabled: true,
        },
        rules: {
          imageUrl: [{ required: true, trigger: 'blur', message: '请上传头像框图片' }],
          isEnabled: [{ required: true, trigger: 'blur', message: '请选择是否启用' }],
        },
        title: '',
        dialogFormVisible: false,
      }
    },
    computed: {
      uploadUrl() {
        return `${process.env.VUE_APP_API_BASE_URL}/management/api/common/upload`
      },
    },
    created() {},
    methods: {
      handleUploadSuccess(url) {
        this.form.imageUrl = url
      },
      showEdit(row) {
        if (!row) {
          this.title = '添加'
        } else {
          this.title = '编辑'
          this.form = {
            imageUrl: row.imageUrl,
            isEnabled: row.isEnabled,
          }
          this.id = row.id
        }
        this.dialogFormVisible = true
      },
      close() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.id = ''
        this.dialogFormVisible = false
      },
      save() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            if (this.id) {
              const { msg } = await doEdit(this.id, this.form)
              this.$baseMessage(msg, 'success')
            } else {
              const { msg } = await doAdd(this.form)
              this.$baseMessage(msg, 'success')
            }
            this.$emit('fetch-data')
            this.close()
          } else {
            return false
          }
        })
      },
    },
  }
</script>
