<!-- 添加优惠券 -->
<template>
  <el-dialog
    :title="type == 1 ? '编辑优惠券' : '添加优惠券'"
    v-model="dialogVisible"
    @close="reset"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" label-position="left">
      <el-form-item label="券名称" prop="id">
        <el-select v-model="form.id" placeholder="请选择优惠券">
          <el-option
            :label="item.title"
            :value="item.id"
            v-for="item in coupons"
            :key="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="数量">
        <el-input-number v-model="form.num" :min="1"></el-input-number>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="onSubmitHandle">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import couponApi from "@/api/account/coupon";
export default {
  data() {
    return {
      dialogVisible: false,
      loading: false,
      coupons: [],
      type: 1,
      form: {
        id: "",
        name: "",
        num: "",
      },
      resetForm: {},
      rules: {
        id: [
          {
            required: true,
            message: "请选择优惠券",
            trigger: "blur",
          },
        ],
      },
    };
  },
  mounted() {
    this.resetForm = { ...this.form };
    this.getTbShopCoupon();
  },
  methods: {
    // 提交
    onSubmitHandle() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            this.form.name = this.coupons.find((item) => item.id == this.form.id).title;
            this.$emit("success", { ...this.form });
            this.close();
          } catch (error) {
            console.log(error);
          }
        }
      });
    },
    // 获取优惠券列表
    async getTbShopCoupon() {
      try {
        const res = await couponApi.getList({
          type: 1,
          page: 1,
          size: 100,
        });
        this.coupons = res;
      } catch (error) {
        console.log(error);
      }
    },
    reset() {
      this.form = { ...this.resetForm };
    },
    close() {
      this.dialogVisible = false;
    },
    show(row) {
      if (row && row.id) {
        this.type = 1;
        this.form = { ...row };
      } else {
        this.type = 2;
      }
      this.dialogVisible = true;
    },
  },
};
</script>