<!--
  切换卡片
  @author: 张文
  @date: 2022-05-19
-->
<template>
  <div
    class="ty-global-flex-between"
    style="padding-top: 8px"
  >
    <!-- 左边按钮 -->
    <div
      class="ty-global-flex-center ty-global-click-style ty-cut-card-btn"
      @click="cut('left')"
    >
      <van-icon name="arrow-left"/>
    </div>

    <!-- 任务数据 -->
    <div>
      <span style="color: #D50000">{{ index + 1 }}</span>
      <span> / {{ length }}</span>
    </div>

    <slot name="numLast"></slot>

    <!-- 右边按钮 -->
    <div
      class="ty-global-flex-center ty-global-click-style ty-cut-card-btn"
      @click="cut('right')"
    >
      <van-icon name="arrow" />
    </div>

  </div>
</template>

<script>

export default {
  name: "tyCutCard",
  props:{
    // 当前激活项
    value:{
      type: Number,
      default: 0
    },
    // 总长度
    length:{
      type: Number,
      default: 1
    },
    // 切换前的回调
    cutStart: Function,
    // 切换成功后的回调
    cutEnd: Function
  },
  computed:{
    index:{
      get(){
        return this.value
      },
      set(v){
        this.$emit('input', v)
      }
    }
  },
  watch:{
    length:{
      handler(n){
        if (n < (this.index + 1)) this.index = n-1
        if (n === 0) this.index = 0
        this.cutEnd()
      },
      immediate:true,
      deep:true
    }
  },
  data() {
    return {}
  },
  methods: {

    // 左右切换
    async cut(type){
      try{

        // 判断是点击的左边还是右边
        if (type === 'left'){
          if (this.index === 0){
            this.$tyShowErrorMsg(
              this.$tyLanguage.get('wms_project.pda.ui.cutCard.one','已是第一条')
            )
            return
          }
        }else {
          if ((this.index + 1) >= this.length){
            this.$tyShowErrorMsg(
              this.$tyLanguage.get('wms_project.pda.ui.cutCard.last','已是最后一条')
            )
            return
          }
        }

        // 判断是否传入了触发前的事件
        if (this.cutStart){
          const back = await this.cutStart()

          if (back === false) return
        }

        // 根据不同按钮触发不同事件
        type === 'left' ? this.index-- : this.index++

        // 提示成功
        this.$nextTick(()=>{
          this.$tyToast.toast({
            forbidClick:false,
            message:this.$tyLanguage.get('wms_project.pda.ui.cutCard.cut','已切换至行数：') + (this.index + 1)
          })
        })

        // 调用触发结束后的回调
        this.cutEnd && this.cutEnd()
      }catch(e){
        console.warn('切换组件异常捕获：', e)
      }
    },
  }
}
</script>

<style scoped lang="less">

@import "../../assets/css/var.less";

.ty-cut-card-btn{
  padding: 5px;
  border: solid 1px @titleColor;
  border-radius: 5px;
}

</style>
