<template>
  <div>
    <div v-show="showFlag">
      <img
        v-show="!codeFlag"
        style="cursor:pointer"
        src="@/assets/logo_2_custom.png"
        :width="width"
        @click="getCode"
        :height="height"
        :alt="alt" />
      <img
        v-show="codeFlag"
        ref="imgCode"
        src="@/assets/logo_2.png"
        :width="width"
        :height="height"
      />
    </div>
    <div v-show="!showFlag">
      <a-spin />
    </div>

  </div>
</template>

<script>
import { saveCode } from '@/api/upms/code'
export default {
  name: 'ImgCode',
  props: {
    alt: {
      type: String,
      default: '请刷新'
    },
    src: { // 金额
      type: String,
      default: ''
    },
    type: { // 1.表示设备
      type: Number,
      default: 1
    },
    codeId: { // 金额
      type: String,
      default: ''
    },
    width: {
      type: Number,
      default: 200
    },
    height: {
      type: Number,
      default: 200
    }
  },
  data () {
    return {
      defaultSrc: '/src/assets/logo_2.png',
      showFlag: false,
      codeFlag: false
    }
  },
  watch: {
    src: function () {
      this.showCode()
    }
  },
  created () {
    this.showCode()
  },
  methods: {
    getCode () {
      saveCode({ type: this.type, codeId: this.codeId }).then(result => {
        console.log(1111, result)
        this.imageIsExist(result.data).then(res => {
          if (res) {
            this.$refs.imgCode.src = result.data
            this.showFlag = true
            this.codeFlag = true
          } else {
            this.showFlag = true
            this.codeFlag = false
          }
        })
      })
    },
    showCode () {
      this.showFlag = false
      this.imageIsExist(this.src).then(res => {
        if (res) {
          this.$refs.imgCode.src = this.src
          this.showFlag = true
          this.codeFlag = true
        } else {
          this.showFlag = true
          this.codeFlag = false
        }
      })
    },
    imageIsExist: (url) => {
      return new Promise((resolve) => {
        let img = new Image()
        img.onload = function () {
          resolve(true)
          img = null
        }
        img.onerror = function () {
          resolve(false)
          img = null
        }
        img.src = url
      })
    }
  }

}
</script>

<style scoped>

</style>
