<template>
  <div class="cmp-minus-plus">
    <div class="add-cart" v-if="!count" @click.stop="handlePlus">加入购物车</div>
    <div class="minus-plus-wrapper" v-else>
      <div class="btn-minus" @click.stop="handleMinus"></div>
      <div :class="{count: true, 'type-shopCar': typeShopCar}">
        <span v-if="type !== 'input'">{{count}}</span>
        <input  v-if="type === 'input'" type="number" class="input-count" @blur="countChange" v-model.number="inputCount">
      </div>
      <div class="btn-plus" @click.stop="handlePlus"></div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { errToast,jumpPage } from '@/utils/uniapi.js'
import { msgData } from '@/config.js'
import {debounce} from '@/utils'
export default {
  inject: {
    shopCar: {
      default: ''
    }
  },
  props:['count','type','skuName'],
  data() {
    return {
      typeShopCar: false,
      inputCount: this.count
    }
  },
  computed: {
    ...mapGetters({
      isLogin: 'login/isLogin',
      storeMap: "indexPage/storeMap",
      storeID: "indexPage/storeID"
    })
  },
  mounted() {
    this.typeShopCar = this.shopCar
    this.inputCount = this.count
  },
  watch: {
    count(count) {
      this.inputCount = +count
    }
  },
  methods: {
    // minus
    handleMinus:debounce(function() {
      if (this.storeMap[this.storeID[0]].status !== 1) return errToast(msgData.storeIsClose)  // 判断当前门店是否营业
      this.$emit('clickMinus')
    },1000),
    // plus
    handlePlus:debounce(function() {
      if (this.storeMap[this.storeID[0]].status !== 1) return errToast(msgData.storeIsClose)  // 判断当前门店是否营业

      // 判断用的登录状态
      if (!this.isLogin) {
        errToast('请登录')
        jumpPage('switchTab', '/pages/mine/index', 800)
        return
      }

      this.$emit('clickPlus')
    },1000),
    // count改变
    countChange:debounce(function(e) {
      if(+e.target.value > this.skuName.stock) {
        this.inputCount = this.skuName.count
        return  errToast('暂时没有那么多商品喔~')
      }
      const count = +e.target.value
      if (!count) this.inputCount = 0
      if (count !== this.count) this.$emit('countChange', count ? count : 0)
    },1000)
  }
}
</script>

<style lang="scss">
@import "./plus-minus.scss";
</style>