<template>
  <!-- 申请配件按钮 -->
  <view class="apply-button" v-show="show">
    <u-button
      :custom-style="customStyle"
      shape="circle"
      @click.stop="handleClick"
      type="primary"
    >
      <view class="button-view">
        <u-loading mode="flower" :show="loading"></u-loading>
        <image
          v-if="isImage && !loading"
          :src="imageUrl"
          class="image-icon"
          mode="widthFix"
        ></image>
        <u-icon v-else-if="!loading" class="apply-icon" :name="icon"></u-icon>
        <text class="apply-text" v-if="showText">{{ text }}</text>
      </view>
    </u-button>
  </view>
</template>

<script>
export default {
  props: {
    type: {
      // 按钮宽'collapse': '80rpx', 'expand': '220rpx'
      type: String,
      default: 'expand',
    },
    text: {
      type: String,
      default: '申请物料',
    },
    icon: {
      type: String,
      default: 'plus',
    },
    show: {
      type: Boolean,
      default: true,
    },
    clickedType: {
      // normal 点击之后不隐藏； hidden 点击之后隐藏
      type: String,
      default: 'normal',
    },
    loading: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    typeWidth() {
      return {
        collapse: '80rpx',
        expand: '220rpx',
      }
    },
    imageUrl() {
      return process.uniEnv.qn_base_url + this.icon
    },
    isImage() {
      return /\.(png|jpg|gif|jpeg|webp)$/.test(this.icon)
    },
    clickedHidden() {
      return this.clickedType == 'hidden'
    },
    typeOpacity() {
      return {
        collapse: this.clicked == 0 ? '0.6' : '1',
        expand: '1',
      }
    },
    showText() {
      return this.type == 'expand'
    },
    customStyle() {
      return {
        height: '80rpx',
        width: this.typeWidth[this.type],
        opacity: this.typeOpacity[this.type],
      }
    },
  },
  data() {
    return {
      clicked: 0, // 0 不活跃；>1 活跃中
    }
  },
  created() {
    setTimeout(() => {
      this.$emit('update:type', 'collapse')
    }, 3000)
  },
  watch: {
    show(val) {
      if (val) {
        this.clicked += 1
        setTimeout(() => {
          // 三秒不点击，算失去活跃
          this.clicked = Math.max(0, this.clicked - 1)
        }, 3000)
      }
    },
  },
  methods: {
    handleClick() {
      if (this.clickedHidden) {
        this.$emit('update:show', false)
      }
      this.$emit('click')
    },
  },
}
</script>

<style lang="scss" scoped>
.apply-button {
  .button-view {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    .apply-icon {
      font-size: 36rpx;
    }
    .apply-text {
      font-size: 32rpx;
      padding-left: 10rpx;
    }
    .image-icon {
      width: 30rpx;
      height: 34rpx;
    }
  }
}
</style>
