<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    width="500px"
    append-to-body
    @close="handleClose"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <!-- 店铺选择 -->
      <el-form-item label="选择店铺" prop="storeId" v-if="showStoreSelect">
        <el-select
          v-model="form.storeId"
          placeholder="请选择店铺"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="store in storeOptions"
            :key="store.storeId"
            :label="store.storeName"
            :value="store.storeId"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="赠送次数" prop="number">
        <el-input-number
          v-model="form.number"
          :min="1"
          :max="maxNumber"
          controls-position="right"
          style="width: 100%"
        />
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { giftLightingNum } from '@/api/bst/lightingNum'

export default {
  name: 'GiftLightingDialog',
  props: {
    visible: Boolean,
    title: {
      type: String,
      default: '赠送爆灯次数'
    },
    userId: [Number, String],
    storeOptions: {
      type: Array,
      default: () => []
    },
    showStoreSelect: {
      type: Boolean,
      default: true
    },
    maxNumber: {
      type: Number,
      default: 9999
    }
  },
  data() {
    return {
      dialogVisible: this.visible,
      form: {
        storeId: null,
        number: 1
      },
      rules: {

      }
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val
      if (val) this.initForm()
    }
  },
  methods: {
    initForm() {
      this.form = {
        number: 1
      }
    },
    handleSubmit() {
      this.$refs.formRef.validate(valid => {
        if (valid) this.submitData()
      })
    },
    async submitData() {
      try {
        await giftLightingNum({
          userId: this.userId,
          storeId: this.form.storeId,
          number: this.form.number
        })
        this.$emit('success')
        this.$message.success('赠送成功')
        this.dialogVisible = false
      } catch (error) {
        this.$message.error(error.message || '操作失败')
      }
    },
    handleClose() {
      this.$emit('update:visible', false)
    }
  }
}
</script>
