<template>
  <div>
    <div v-if="showInput" class="link-input">
      <el-input v-model="chooseLinkUrl">
        <template #append>
          <el-button @click="onClick">{{ defaultLinkText }}</el-button>
        </template>
      </el-input>
    </div>
    <div v-else class="link-input">
      <el-link :type="_type" :underline="false" @click="onClick">
        <div v-if="haveLink"> {{ chooseLink.title }}</div>
        <div v-else> {{ defaultLinkText }}</div>
      </el-link>
      <i v-if="haveLink" class="el-icon-close close" @click="chooseLink={}" />
    </div>
    <el-dialog title="选择链接" :visible.sync="dialogLinkVisible" append-to-body width="1000px">
      <dk-link :url="value" @choose="handleChooseLink" />
    </el-dialog>
  </div>
</template>

<script>
import DkLink from './DkLink'

export default {
  name: 'DkLinkInput',
  components: { DkLink },
  props: {
    placeholder: {
      default: '',
      type: String
    },
    value: {
      default: () => {
        return ''
      },
      type: [Object, String]
    },
    showInput: {
      default: true,
      type: Boolean
    },
    defaultLinkText: {
      default: '选择链接',
      type: String
    }
  },
  data() {
    return {
      dialogLinkVisible: false,
      chooseLink: this.value || {},
      chooseLinkUrl: this.value || ''
    }
  },
  computed: {
    haveLink() {
      return !!this.chooseLink.title
    },
    _type() {
      return this.haveLink ? 'success' : 'primary'
    }
  },
  watch: {
    chooseLink(value) {
      this.$emit('input', value)
    },
    chooseLinkUrl(value) {
      this.$emit('input', value)
    },
    value(value) {
      this.chooseLink = value
    }
  },
  mounted() {
    this.icon = this.value
  },
  methods: {
    handleChooseLink(link) {
      if (this.showInput) {
        this.chooseLinkUrl = link.url
      } else {
        this.chooseLink = link
      }
      this.dialogLinkVisible = false
    },
    onClick() {
      this.dialogLinkVisible = true
    }
  }
}
</script>

<style scoped lang="scss">
.link-input {
  .close {
    margin-left: 10px;
    cursor: pointer;
    text-align: center;
    vertical-align: middle;
  }
}
</style>
