<template>
  <el-dialog ref="dialogForm" width="45%" :title="title" :visible.sync="visible" @close="closeDialog">
    <el-form label-width="25%" ref="edit" :rules="rules" :model="edit">
      <el-input v-show="false" v-model="edit.id"/>
      <el-form-item label="指向Url" prop="toUrl">
        <el-col :span="18">
          <el-input v-model="edit.toUrl"/>
        </el-col>
      </el-form-item>
      <el-form-item label="二维码Url" prop="qrUrl">
        <el-col :span="18">
          <el-input v-model="edit.qrUrl"/>
        </el-col>
      </el-form-item>
      <el-form-item label="备注" prop="tip">
        <el-col :span="18">
          <el-input v-model="edit.tip"/>
        </el-col>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="beforeSave">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { saveOrUpdate } from '@/api/qr'

export default {
  name: 'EditDialog',
  props: {
    row: {
      type: Object,
      require: true
    },
    show: {
      type: Boolean,
      default: () => false
    }
  },
  components: {},
  data() {
    return {
      edit: { id: null },
      visible: this.show,
      rules: {
        name: [{ required: true, message: '请输入', trigger: 'blur' }]
      }
    }
  },
  computed: {
    title() {
      return (this.edit.id === null ? '新增' : '编辑')
    }
  },
  watch: {
    visible() {
      this.$emit('update:show', false)
    }
  },
  created() {

  },
  mounted() {
    if (this.row !== null) {
      this.edit = JSON.parse(JSON.stringify(this.row))
      // console.log(this.edit)
    }
  },
  methods: {
    closeDialog() {
      // 关闭
    },
    beforeSave() {
      if (this.row && this.row.qrUrl != null && this.row.qrUrl !== this.edit.qrUrl) {
        this.$confirm('你更改了二维码Url,这可能带来一些意外的结果, 是否继续?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消(维持原值)',
          type: 'warning'
        }).then(() => {
          this.handleSave()
        }).catch(() => {
          this.edit.qrUrl = this.row.qrUrl
        })
      } else {
        this.handleSave()
      }
    },
    handleSave() {
      this.$refs.edit.validate(valid => {
        if (valid) {
          const loading = this.$loading({
            background: this.$elementGlobal.loadingBackground
          })
          saveOrUpdate([this.edit])
            .then(r => {
              loading.close()
              if (r.data === true) {
                this.visible = false
                this.$message({ type: 'success', message: '保存成功!' })
                this.$emit('saved')
              } else {
                this.$message({ type: 'error', message: '保存失败!' })
              }
            })
            .catch(() => {
              loading.close()
            })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">

</style>
