<template>
  <div>
    <el-dialog title="赠送优惠券" v-model="show" @close="reset" width="400px">
      <el-form :model="form" label-width="120px">
        <el-form-item label="赠送用户">
          <div class="flex" v-if="user">
            <el-avatar :src="form.name" :size="60" shape="square" />
            <div class="ml-[18px]">
              <p class="text-size-lg">{{ user.nickName }}</p>
              <p class="color-999 mt-1">id:{{ user.userId }}</p>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="手机号：">
          <span>{{ user.phone }}</span>
        </el-form-item>

        <el-form-item label="选择优惠券" required>
          <el-select v-model="form.couponId" placeholder="请选择优惠券">
            <el-option
              v-for="coupon in couponList"
              :key="coupon.id"
              :label="coupon.title"
              :value="coupon.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="数量" required>
          <el-input-number
            style="width: 160px"
            v-model="form.num"
            :min="1"
            :step="1"
            placeholder="请输入数量"
          ></el-input-number>
          <span class="ml-2">张</span>
        </el-form-item>
      </el-form>
      <div style="text-align: right; margin-top: 20px">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="submit">{{ isedit ? "更新" : "提交" }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import couponApi from "@/api/market/coupon";

import { ref, toRaw } from "vue";
import { ElMessage } from "element-plus";
// 控制主弹窗显示
const show = ref(false);

// 表单数据
const form = ref({
  userId: "",
  couponId: "",
  num: 1,
});

// 优惠券列表
const couponList = ref([]);

// 重置表单
function reset() {
  form.value = {
    userId: "",
    couponId: "",
    num: 1,
  };
}

const emits = defineEmits(["submitSuccess"]);
// 提交表单
function submit() {
  console.log("提交表单数据：", form.value);
  if (!form.value.couponId) {
    return ElMessage.error("请选择优惠券");
  }
  if (form.value.num <= 0) {
    return ElMessage.error("请输入数量");
  }
  couponApi.giveCoupon(form.value).then((res) => {
    if (res) {
      ElMessage.success("优惠券发放成功");
      emits("submitSuccess", form.value);
      close();
    }
  });
}

const user = ref("");
function open(data) {
  console.log("打开表单：", data);
  user.value = data;
  form.value.userId = data.userId;
  show.value = true;
}
function close() {
  show.value = false;
  reset();
}
defineExpose({ open, close, reset, submit });

onMounted(() => {
  couponApi.getList({ size: 999 }).then((res) => {
    if (res) {
      couponList.value = res.records || [];
    }
  });
});
</script>