<template>
  <el-button-group class="es-button-group">
    <template v-if="length > 1">
      <template v-for="(item, index) in showBtns">
        <template v-if="item && !item.hide">
          <es-upload
            v-if="item.upload || (item.code && item.ownId)"
            :key="index"
            v-bind="{
              ...exclAttribute({
                data: item,
                attrs: ['events']
              }),
              ...parseProps(),
              method: 'post',
              btnSize: size,
              showFileList: false,
              selectType: mode == 'plus' ? 'text' : item.type
            }"
            v-on="item.events"
          ></es-upload>
          <el-tooltip
            :key="index"
            v-else-if="item.showTooltip"
            :effect="item.effect ? item.effect : 'dark'"
            :content="item.tips"
            :placement="item.placement ? item.placement : 'top'"
          >
            <es-button
              :stop="stop"
              :data="data"
              :outside="outside"
              v-bind="
                exclAttribute({
                  data: item,
                  attrs: ['events']
                })
              "
              :size="size"
              :type="mode == 'plus' ? 'text' : item.type"
              v-on="item.events"
              @click="handleClick({ ...data, handle: item })"
            >
              {{
                item.template
                  ? item.template({ ...data, config: item })
                  : item.text
              }}
            </es-button>
          </el-tooltip>
          <es-button
            v-else
            :stop="stop"
            :data="data"
            :outside="outside"
            v-bind="
              exclAttribute({
                data: item,
                attrs: ['events']
              })
            "
            :key="index"
            :size="size"
            :type="mode == 'plus' ? 'text' : item.type"
            v-on="item.events"
            @click="handleClick({ ...data, handle: item })"
          >
            {{
              item.template
                ? item.template({ ...data, config: item })
                : item.text
            }}
          </es-button>
        </template>
      </template>
    </template>
    <el-dropdown
      v-if="other.length > 0"
      ref="dropdown"
      @command="handleCommand"
      @visible-change="handleChange"
      :trigger="trigger"
    >
      <el-button :size="size" :type="mode == 'plus' ? 'text' : ''">
        <el-badge v-bind="badges">
          <template v-if="mode == 'plus'">更多</template>
          <template v-else-if="moreText">
            {{ moreText }}
            <i
              :class="{
                'el-icon-arrow-down': !show,
                'el-icon-arrow-up': show
              }"
            ></i>
          </template>
          <i v-else class="es-icon-more"></i>
        </el-badge>
      </el-button>
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item
          v-for="(item, index) in other"
          :key="index"
          :command="item"
          :class="{ 'es-dropdown-padding': item.upload || item.selector }"
          v-show="!item.hide"
        >
          <es-upload
            v-if="item.upload || (item.code && item.ownId)"
            class="es-dropdown-upload"
            v-bind="{
              ...exclAttribute({
                data: item,
                attrs: ['events']
              }),
              ...parseProps(),
              method: 'post',
              showFileList: false,
              selectType: 'text'
            }"
            v-on="item.events"
          ></es-upload>
          <es-selector
            v-else-if="item.selector"
            class="es-dropdown-selector"
            v-bind="{
              reset: true,
              ...exclAttribute({
                data: item,
                attrs: ['events', 'type', 'value']
              }),
              businessData: data
            }"
            v-on="item.events"
            :button="{ size: 'medium', type: 'text' }"
          >
            <i :class="item.icon" v-if="item.icon"></i
            >{{
              item.template
                ? item.template({ ...data, config: item })
                : item.text
            }}
          </es-selector>
          <el-tooltip
            :key="index"
            v-else-if="item.showTooltip"
            :effect="item.effect ? item.effect : 'dark'"
            :content="item.tips"
            :placement="item.placement ? item.placement : 'top'"
          >
            <span type="text">
              {{
                item.template
                  ? item.template({ ...data, config: item })
                  : item.text
              }}
            </span></el-tooltip
          >
          <template v-else>
            <i :class="item.icon" v-if="item.icon"></i
            >{{
              item.template
                ? item.template({ ...data, config: item })
                : item.text
            }}
          </template>
          <el-badge
            v-if="item.badge"
            v-bind="
              typeof item.badge === 'number'
                ? { value: item.badge }
                : item.badge
            "
          ></el-badge>
        </el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>
  </el-button-group>
</template>
<script>
import util from 'eoss-ui/src/utils/util';
export default {
  name: 'EsButtonGroup',
  provide() {
    return {
      btnGroup: this
    };
  },
  props: {
    mode: String,
    value: String,
    data: Object,
    contents: { type: Array, default: [] },
    length: {
      type: Number,
      default: 3
    },
    rules: Function,
    stop: Boolean,
    trigger: {
      type: String,
      default: 'hover'
    },
    useCaseCodeKey: String,
    moreText: String,
    size: {
      type: String,
      default: 'mini'
    },
    placement: {
      type: String,
      default: 'bottom'
    },
    parseData: Function,
    badge: Object,
    sort: Boolean,
    outside: {
      type: Boolean,
      default: true
    }
  },
  computed: {
    btns() {
      return this.getBtns();
    },
    showBtns() {
      return this.btns.length > this.length
        ? this.btns.slice(0, this.length - 1)
        : this.btns;
    },
    other() {
      let btns =
        this.length > 0 && (this.btns.length > this.length || this.length == 1)
          ? this.btns.slice(this.length - 1, this.btns.length)
          : [];
      return btns;
    },
    badges() {
      if (
        this.other.length &&
        this.other.filter((item) => {
          return item.badge;
        }).length
      ) {
        return this.badge ? { isDot: true, ...this.badge } : { isDot: true };
      }
      return this.badge
        ? { isDot: true, hidden: true, ...this.badge }
        : { isDot: true, hidden: true };
    }
  },
  watch: {},
  data() {
    return {
      show: false
    };
  },
  mounted() {
    this.resetWidth();
  },
  methods: {
    exclAttribute({ data, attrs }) {
      return util.exclAttribute({ data, attrs });
    },
    getBtns() {
      let useCaseCodes = util.getStorage('useCaseCodes');
      let keyword =
        this.data && this.useCaseCodeKey
          ? this.data.row[this.useCaseCodeKey]
          : null;
      let arry = this.contents.filter((item) => {
        if (Object.prototype.hasOwnProperty.call(item, 'rules')) {
          if (useCaseCodes && (item.useCaseCode || keyword)) {
            return (
              item.rules(this.data.row) &&
              useCaseCodes.indexOf(item.useCaseCode || keyword) > -1
            );
          }
          return item.rules(this.data.row);
        }
        if (this.rules !== undefined) {
          if (useCaseCodes && (item.useCaseCode || keyword)) {
            return (
              this.rules(this.data.row) &&
              useCaseCodes.indexOf(item.useCaseCode || keyword) > -1
            );
          }
          return this.rules(this.data.row);
        }
        if (useCaseCodes && (item.useCaseCode || keyword)) {
          return useCaseCodes.indexOf(item.useCaseCode || keyword) > -1;
        }
        return item.hide !== true;
      });
      let newBtns = arry.map((item) => {
        let badge, tips;
        if (item.badge && typeof item.badge === 'function') {
          badge = item.badge(this.data.row);
        }
        if (item.tips && typeof item.tips === 'function') {
          item.tips = item.tips(this.data.row);
        }
        return badge ? { ...item, badge: badge } : { ...item };
      });
      if (this.sort) {
        newBtns = newBtns.sort((a, b) => {
          return (b.badge ? 1 : 0) - (a.badge ? 1 : 0);
        });
      }
      return newBtns;
    },
    handleChange(res) {
      this.show = res;
    },
    handleClick(obj) {
      this.$emit('handleClick', obj);
      this.$emit('handle-click', obj);
    },
    handleCommand(res) {
      if (res.upload || res.selector) {
        this.$refs.dropdown.hide();
        return false;
      }
      this.$emit('handleClick', { ...this.data, handle: res });
      this.$emit('handle-click', { ...this.data, handle: res });
    },
    resetWidth() {
      this.$nextTick(() => {
        let childNodes = this.$el.childNodes;
        let width = parseInt(this.value, 10);
        let w = 0;
        for (let i = 0; i < childNodes.length; i++) {
          let item = childNodes[i];
          w += item.clientWidth ? item.clientWidth : 0;
        }
        w += 20 + childNodes.length + 10;
        if (w > width) {
          this.$emit('input', w + 'px');
        }
      });
    },
    parseProps() {
      return this.parseData && this.data ? this.parseData(this.data) : {};
    }
  }
};
</script>
