<template>
  <div class="flag-icons" @click="copyTextContent(tooltip)">
    <div class="imgs">
      <el-tooltip :disabled="!tooltip || tooltip.trim().length === 0" class="item" effect="dark">
        <div slot="content">{{ tooltip }}</div>
        <img :src="iconPath" :style="'width:'+ iconSize">
      </el-tooltip>
    </div>
  </div>
</template>

<script>
import { copyText } from '@/utils'
export default {
  name: 'FlagIcon',
  props: {
    code: {
      type: String,
      default: ''
    },
    size: {
      type: String,
      default: '48px'
    },
    tooltip: {
      type: String,
      default: ''
    }
  },
  data() {
    return { iconSize: '' }
  },
  computed: {
    iconPath() {
      return this.code ? require(`@/flag-icons/flag/flag_${this.code.toLowerCase()}.png`) : ''
    }
  },
  watch: {
    size: {
      immediate: true,
      deep: true,
      handler(newVal) {
        if (newVal) {
          if (newVal.indexOf('px') > 0 || newVal.indexOf('%') > 0 || newVal.indexOf('rem') > 0) {
            this.iconSize = newVal
          } else {
            this.iconSize = newVal + 'px'
          }
          return
        }
        this.iconSize = '48px'
      }
    }
  },
  methods: {
    copyTextContent(text) {
      if (!text) {
        return
      }
      const that = this
      copyText(text).then(() => {
        that.$message({
          message: '复制成功',
          type: 'success'
        })
      }).catch(() => {
        that.$message({
          message: '复制失败',
          type: 'error'
        })
      })
    }
  }
}
</script>

<style scoped lang="scss">
.flag-icons {
  cursor: pointer;
}
</style>
