<template>
  <view>
    <view class="k-icon" v-if="isImg" @click="handleClick">
      <!-- 不能直接写 require(name)，会报错 Cannot find module -->
      <!-- require 参数不能有@，不然引入KIP中会有奇怪的报错 -->
      <!-- 要显示非 static 文件夹中的图片时，name 需要传入 require 函数 -->
      <!-- <image
        :src="
          name.indexOf('./') == 0
            ? require('./' + name.substring(2))
            : name.indexOf('@/') == 0
            ? require('@/' + name.substring(2))
            : name.indexOf('/') == 0
            ? require('@/' + name.substring(1))
            : name
        "
        :style="{
          width: rpxSize + 'px',
          height: rpxSize + 'px',
          opacity: opacity,
        }"
      /> -->
      <image
        :src="name"
        :style="{
          width: rpxSize + 'px',
          height: rpxSize + 'px',
          opacity: opacity,
        }"
      />
    </view>
    <text
      v-else
      :style="{
        color: color,
        fontSize: rpxSize + 'px',
        fontWeight: fontWeight,
      }"
      class="k-icon"
      :class="{
        'k-icon__color': !color && !primary,
        'k-icon__active-color': primary && !color,
        'k-icon__not-allowed': disabled,
      }"
      @click="handleClick"
      >{{ icon }}</text
    >
  </view>
</template>

<script>
import props from './props.js';
import icons from './kuiicons.js';

export default {
  name: 'k-icon',
  mixins: [props],
  data() {
    return {
      icons: icons,
      path: 'image-005',
    };
  },
  computed: {
    rpxSize: function () {
      return this.unit == 'px' ? Number(this.size) * 2 : this.size;
    },
    // 判断传入的name属性是否图片路径，只要带有"/"均认为是图片形式
    // 如果传入的name是一个require函数，那么需要设置image为true
    isImg() {
      return this.image || this.name.indexOf('/') !== -1;
    },
    // 通过图标名，查找对应的图标
    icon() {
      // 如果内置的图标中找不到对应的图标，就直接返回name值，因为用户可能传入的是unicode代码
      const icon = icons.find((i) => i.name == this.name);
      return icon?.unicode || this.name;
    },
  },
  methods: {
    handleClick() {
      if (this.disabled) return;
      this.$emit('click', {
        params: this.params,
      });
    },
  },
};
</script>

<style scoped>
/* stylelint-disable selector-class-pattern */
/* stylelint-disable declaration-no-important */
/* stylelint-disable comment-empty-line-before */
.k-icon {
  display: flex;
  align-items: center;
}

/* #ifndef APP-NVUE */
@font-face {
  font-display: swap;
  font-style: normal;
  font-family: kuiicons;
  src: url("./kuiicons.ttf") format("truetype");
}
/* #endif */

.k-icon {
  font-family: kuiicons;
  text-decoration: none;
  text-align: center;
  /* #ifdef H5 */
  cursor: pointer;
  /* #endif */
}

/* #ifndef APP-NVUE */
.k-icon__color {
  color: var(--k-color-section, #333) !important;
}

.k-icon__active-color {
  color: var(--k-color-primary, #465cff) !important;
}

/* #endif */

.k-icon__not-allowed {
  /* #ifdef H5 */
  cursor: not-allowed !important;

  /* #endif */
}
</style>
