<template>
  <popup class="x-action-sheet" :visible="show" @click-mask="onClickingMask">
    <div class="x-action-sheet-content">
      <div class="x-action-sheet-content__menu">
        <div
          class="x-action-sheet-content__cell"
          v-for="(text, key) in menus"
          :key="key"
          @click="onMenuClick(text, key)"
          v-html="text.label || text"
          :class="`x-action-sheet-menu-${text.type || 'default'}`">
        </div>
      </div>
      <div class="x-action-sheet-content__action" @click="emitEvent('on-click-menu', 'cancel')" v-if="showCancel">
        <div class="x-action-sheet-content__cell">{{cancelText || '取消'}}</div>
      </div>
    </div>
  </popup>
</template>

<script>
import Popup from '../Popup'

export default {
  props: {
    value: Boolean,
    showCancel: Boolean,
    cancelText: String,
    menus: {
      type: [Object, Array],
      default: () => ({})
    },
    closeOnClickingMask: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      show: false
    }
  },
  components: {
    Popup
  },
  methods: {
    onMenuClick (text, key) {
      if (typeof text === 'string') {
        this.emitEvent('on-click-menu', key)
      } else {
        if (text.type !== 'disabled' && text.type !== 'info') {
          if (text.value) {
            this.emitEvent('on-click-menu', text.value)
          } else {
            this.$emit('input', false)
          }
        }
      }
    },
    onClickingMask () {
      this.closeOnClickingMask && this.$emit('input', false)
    },
    emitEvent (event, menu, shouldClose = true) {
      if (event === 'on-click-menu' && !/.noop/.test(menu)) {
        this.$emit(event, menu)
        this.$emit(`${event}-${menu}`)
        shouldClose && this.$emit('input', false)
      }
    }
  },
  watch: {
    value(val) {
      this.show = val
    }
  }
}
</script>

<style lang="less">
.x-action-sheet {

  &-mask {
    position: fixed;
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
    z-index: 1000;
    background: rgba(0, 0, 0, 0.6);
  }
  // TODO 后面改用更好的方式实现样式处理，这里直接覆盖了 popup 的样式
  .x-popup__content {
    max-height: 100%;
    overflow-y: auto;
    background: #EFEFF4;
  }
  &-content {
    &__menu {
      background: #fff;
    }
    &__cell {
      position: relative;
      font-size: 16px;
      line-height: 44px;
      text-align: center;
      color: #333;
      // 单行超出省略
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;

      // 边线
      &:before {
        content: " ";
        position: absolute;
        left: 0;
        top: 0;
        right: 0;
        height: 1px;
        border-top: 1px solid #D9D9D9;
        color: #D9D9D9;
        transform-origin: 0 0;
        transform: scaleY(0.5);
      }
      &:first-child:before {
        display: none;
      }
    }
    &__action {
      margin-top: 5px;
      background: #fff;
    }
  }
}
</style>
