<template>
  <div class="limited-setting-dialog">
    <el-dialog title="限购设置" :visible.sync="showLimitedSettingDialog" @close="onClose">
      <el-form>
        <el-form-item label="总数限购">
          <el-input-number v-model="allQuota" :min="1"></el-input-number>
        </el-form-item>
        <el-form-item label="单次限购">
          <el-input-number v-model="oneQuota" :min="1" :max="allQuota"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="onClose">取 消</el-button>
         <el-button type="primary" @click="onConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addLimitedRecordApi, updateLimitedRecordApi } from '@/api/marketing';

export default {
  props: ['showLimitedSettingDialog', 'productId', 'limitedSettingInfo'],

  watch: {
    limitedSettingInfo(newVal) {
      if (newVal.id) {
        this.allQuota = newVal.allQuota ? newVal.allQuota : 1;
        this.oneQuota = newVal.oneQuota ? newVal.oneQuota : 1;
      }
      this.limitedSetInfo = newVal;
    }
  },

  data() {
    return {
      allQuota: 1,
      oneQuota: 1,
      limitedSetInfo: {}
    };
  },

  methods: {
    onClose() {
      this.$emit('closeLimitedSettingDialog')
    },

    onConfirm() {
      if (this.oneQuota > this.allQuota) {
        this.$message({
          message: '单次限购数量不能大于总限购数量',
          type: 'error',
          showClose: true
        });

        return
      }

      if (this.limitedSetInfo.id) {
        let params = {
          id: this.limitedSetInfo.id,
          enabled: this.limitedSetInfo.enabled,
          allQuota: this.allQuota,
          oneQuota: this.oneQuota,
          productId: this.limitedSetInfo.productId,
          name: this.limitedSetInfo.name
        }

        updateLimitedRecordApi(params).then(res => {
          this.$message({
            showClose: true,
            message: '修改成功',
            type: 'success'
          });
          this.onClose();
        }).catch(err => {});
      } else {
        let params = {
          productId: this.limitedSetInfo.productId,
          enabled: true,
          allQuota: this.allQuota,
          oneQuota: this.oneQuota,
          name: this.limitedSetInfo.name
        };

        addLimitedRecordApi(params).then(res => {
          this.$message({
            showClose: true,
            message: '新增限购成功',
            type: 'success'
          });
          this.$emit('closeLimitedSettingDialog', {allQuota: this.allQuota, oneQuota: this.oneQuota, productId: this.limitedSetInfo.productId});
        }).catch(err => {});
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>