<template>
  <el-tooltip class="item" :placement="placement" v-bind="$attrs">
    <template slot="content">
      <ul class="es-tips-content">
        <li class="es-tips-item" v-for="item in tipCotent" :key="item">
          {{ item }}
        </li>
      </ul>
    </template>
    <slot>
      <i
        @click="handleClick"
        :class="[icon, 'es-tips' + (position ? '-' + position : position)]"
      ></i>
    </slot>
  </el-tooltip>
</template>
<script>
import { gethelpdoc } from 'eoss-ui/src/config/api.js';
import { debounce } from 'throttle-debounce';
import util from 'eoss-ui/src/utils/util.js';
export default {
  name: 'EsTips',
  inheritAttrs: false,
  props: {
    method: {
      type: String,
      default: 'get'
    },
    url: {
      type: String,
      default: gethelpdoc
    },
    param: {
      type: Object,
      default() {
        return {};
      }
    },
    icon: {
      type: String,
      default: 'es-icon-bangzhu'
    },
    content: {
      type: String,
      default: ''
    },
    contents: {
      type: [String, Array],
      default: ''
    },
    placement: {
      type: String,
      default: 'right'
    },
    position: {
      type: String,
      default: ''
    },
    labelKey: {
      type: String,
      default: 'name'
    },
    spill: {
      type: Boolean,
      default() {
        return false;
      }
    },
    disabled: Boolean
  },
  data() {
    return {
      reselutContent: ''
    };
  },
  computed: {
    tipCotent() {
      const content = this.reselutContent || this.contents || this.content;
      if (content && content.length > 0) {
        if (typeof content === 'string') {
          return [content];
        } else {
          if (util.isObject(content[0])) {
            return content.map((item) => {
              return item[this.labelKey];
            });
          } else {
            return content;
          }
        }
      } else {
        return [];
      }
    }
  },
  watch: {
    url(val) {
      if (val) {
        this.getTips();
      }
    }
  },
  beforeCreate() {
    this.getTips = debounce(500, () => {
      this.getTipsData();
    });
  },
  created() {},
  mounted() {
    if (this.url && !this.contents && JSON.stringify(this.param) !== '{}') {
      this.getTips();
    }
  },
  methods: {
    getTipsData() {
      util
        .ajax({
          url: this.url,
          method: this.method,
          data: this.params,
          params: this.params
        })
        .then((res) => {
          if (res.rCode === 0) {
            this.reselutContent = res;
          }
        })
        .catch((err) => {
          if (err.message && err.message !== 'canceled') {
            this.$message.error(err.message);
          }
        });
    },
    handleClick(e) {
      e.stopPropagation();
      e.preventDefault();
    }
  }
};
</script>
