<script setup>
import { ElMessage } from "element-plus";
import { reactive, ref, computed, watch,onUnmounted, onActivated, onDeactivated } from "vue";

import { sendBonus  } from "@/api/bonus";

const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  bonus_id: {
    type: Number,
    default: null,
  },
});

const emit = defineEmits(["update:show", "reload"]);

const showDialog = computed({
  get: () => props.show,
  set: (value) => {
    if(!value){
      formRef.value.resetFields();
    }
    emit("update:show", value);
  },
});

const formLabelWidth = "140px";

const formRef = ref(null);
const form = reactive({
  send_type: '1',
  bonus_sn: '',
  number: 1,
});

watch(() => form.send_type, (newVal) => {
  if(newVal==='2'){
    form.bonus_sn = ''
  }
});

watch(()=>props.bonus_id, (newVal) => {
  if(newVal){
    form.send_type = '1' 
    form.bonus_sn = ''
    form.number = 1
  }
});

const handleSubmit = async () => {
  let res = await sendBonus({type_id: props.bonus_id, ...form});
  if(res.code === 200){
    ElMessage.success('操作成功');
    formRef.value.resetFields();
    showDialog.value = false;  
  }else{
    ElMessage.error(res.message);
  }
};

onActivated(() => {
  console.log("onActivated");
});

onDeactivated(() => {
  console.log("onDeactivated");
});

onUnmounted(() => {
  console.log("onUnmounted");
});
</script>

<template>
  <el-dialog v-model="showDialog" title="發放優惠劵">
    <el-form ref="formRef" :model="form">
      <el-form-item label="建立模式" prop="send_type" :label-width="formLabelWidth">
        <el-radio-group v-model="form.send_type" class="ml-4">
          <el-radio label="1" size="large">相同序號</el-radio>
          <el-radio label="2" size="large">不同序號</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="數量" prop="number" :label-width="formLabelWidth">
        <el-input v-model="form.number" autocomplete="off" />
      </el-form-item>
      <el-form-item label="指定序號" prop="bonus_sn" :label-width="formLabelWidth" v-if="form.send_type==='1'">
        <el-input v-model="form.bonus_sn" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">
          確定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="less" scoped>
.el-button--text {
  margin-right: 15px;
}
.el-input {
  width: 300px;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
