<template>
    <popup v-bind="$attrs" :show="show" @toggle="close" @touchmove.native="$event.preventDefault()">
        <div :class="$style.header" v-if="title||cancel||confirm">
            <span :class="$style.cancel" v-if="cancel" @click="close">{{cancel}}</span>
            <span :class="$style.confirm" v-if="confirm" @click="confirmCallback">{{confirm}}</span>
            <p v-if="title">{{title}}</p>
        </div>
        <picker v-bind="$attrs" style="height:8rem" @update="update" ref="picker"></picker>
    </popup>
</template>

<style module>
    .header {
        position: relative;
        height: 1.2rem;
        color: #000;
        font-size: .44rem;
        line-height: 1.2rem;
        text-align: center;
        border-bottom: 1px solid #d0d0d0;
    }

    .header p {
        margin: 0 auto;
        width: 6.5rem;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .cancel, .confirm {
        position: absolute;
        left: .7rem;
        color: #828282;
    }

    .confirm {
        left: auto;
        right: .7rem;
        color: #f90;
    }
</style>

<script>
    import Popup from '../popup/index.vue'
    import Picker from '../picker/index.vue'

    export default {
      inheritAttrs: false,
      model: {
        prop: 'show',
        event: 'toggle'
      },
      props: {
        show: {
          type: Boolean,
          default: false
        },
        title: {
          type: String,
          default: '请选择'
        },
        cancel: {
          type: String,
          default: '取消'
        },
        confirm: {
          type: String,
          default: '确定'
        }
      },
      computed: {
        $style () {
          return this.$options.cssModules
        }
      },
      methods: {
        close () { // 关闭
          this.$refs.picker.stop(true)
          this.$emit('toggle', false)
        },
        confirmCallback () { // 点击确定按钮
          this.close()
          // 确保update事件先执行
          this.$nextTick(function () {
            this.$emit('confirm', this.value.slice())
          })
        },
        update (value) {
          this.value = value
          this.$emit('update', this.value.slice())
        }
      },
      components: {
        Popup,
        Picker
      }
    }
</script>