<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="name">
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="form.type" placeholder="请选择 APP 类型">
          <el-option label="小程序" :value="1" />
          <el-option label="H5" :value="2" />
          <el-option label="后台管理" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="form.description" autocomplete="off" />
      </el-form-item>
      <el-form-item label="APP图标" prop="appIcon">
        <single-upload
          style="width: 100px; height: 100px"
          upload-url="http://127.0.0.1:3999/management/api/common/upload"
          @upload-success="handleUploadSuccess"
        />
      </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/appManagement'
  import SingleUpload from '@/components/SingleUpload'

  export default {
    name: 'AppManagementEdit',
    components: { SingleUpload },
    data() {
      return {
        id: '',
        form: {
          name: '',
          type: '',
          description: '',
          icon: '',
        },
        rules: {
          name: [{ required: true, trigger: 'blur', message: '请输入名称' }],
          type: [{ required: true, trigger: 'blur', message: '请选择类型' }],
        },
        title: '',
        dialogFormVisible: false,
      }
    },
    created() {},
    methods: {
      handleUploadSuccess(url) {
        this.form.icon = url
      },
      showEdit(row) {
        if (!row) {
          this.title = '添加'
        } else {
          this.title = '编辑'
          this.form = {
            name: row.name,
            description: row.description,
            icon: row.icon,
          }
          this.id = row.id
        }
        this.dialogFormVisible = true
      },
      close() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        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>
