<template>
  <el-dialog title="修改库存" :visible.sync="show" width="500px" :before-close="close" :closed="closed" append-to-body>
    <div v-loading="loading">
      <span class="mr20">库存数量</span><el-radio v-model="calculate" :label="true">增加</el-radio>
      <el-radio v-model="calculate" :label="false">减少</el-radio>
      <div class="pt20 ml76">
        <el-input-number controls-position="right" :min="0" v-model="count" class="w200 block-center" size="small" :max="max"></el-input-number>
      </div>
      <div class="pt20 ml76" v-if="calculate">
        <span class="fz14">可用库存：{{ maxStock }}</span>
      </div>
      <div class="pt20 ml76" v-else>
        <span class="fz14">当前库存：{{ totalCount }}</span>
      </div>
      <div class="pt20 ml76 pb10">
        <span class="fz14">结果：{{ after }}</span>
      </div>
    </div>

    <span slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getCouponStock } from '@/service/api/gameApi.js';
export default {
  props: {
    totalCount: {
      type: Number,
      default: 0
    },
    show: {
      type: Boolean,
      default: false
    },
    coupCardId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      count: 0,
      calculate: true,
      loading: false,
      maxStock: 0 // 可操作库存
    };
  },
  watch: {
    calculate(val) {
      this.count = 0;
    },
    show(val) {
      if (val) {
        this.getCouponStock();
      }
    }
  },
  computed: {
    max() {
      const totalCount = this.totalCount > 0 ? this.totalCount : 0;
      return this.calculate ? this.maxStock - totalCount : this.totalCount;
    },
    after() {
      return (this.calculate ? parseInt(this.totalCount) + parseInt(this.count) : parseInt(this.totalCount) - parseInt(this.count)) || 0;
    }
  },
  methods: {
    getCouponStock() {
      this.loading = true;
      getCouponStock({ cardId: this.coupCardId })
        .then(res => {
          this.maxStock = res.result || 0;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    close() {
      this.calculate = true;
      this.count = 0;
      this.$emit('update:show', false);
    },
    submit() {
      if (!this.calculate) {
        if (this.count > this.totalCount) {
          this.$tips({ type: 'warning', message: '操作后目标库存值不能小于0' });
          return;
        }
      } else {
        if (this.count > this.maxStock) {
          this.$tips({ type: 'warning', message: '增加值不能超过可用库存' });
          return;
        }
      }
      this.$emit('backStock', this.after);
      this.close();
    }
  }
};
</script>

<style lang="scss" scoped>
.ml76 {
  margin-left: 76px;
}
</style>
