<template>
  <el-dialog title="添加兑换码" width="500px" v-model="visible" @closed="onClosed">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px" label-position="right">
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入" :maxlength="50" style="width: 350px;"></el-input>
      </el-form-item>
      <el-form-item label="有效期" prop="timeScope">
        <div style="width: 350px;">
          <el-date-picker v-model="form.timeScope" type="datetimerange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss" style="width: 100%;"
            :disabled="!!form.id" />
        </div>
      </el-form-item>
      <el-form-item label="金额" prop="amount">
        <el-input v-model="form.amount" placeholder="请输入" :maxlength="8" style="width: 350px;"
          @input="e => form.amount = filterNumberInput(e)" :disabled="!!form.id"></el-input>
      </el-form-item>
      <el-form-item label="发行数量" prop="total">
        <div class="column">
          <el-input v-model="form.total" placeholder="请输入" :maxlength="4" style="width: 350px;"
            @input="e => form.total = filterNumberInput(e, true)" :disabled="!!form.id"></el-input>
          <div class="tips" style="color: #999;">单次发行上限1000个，如需更多请分多次创建</div>
        </div>
      </el-form-item>
      <el-form-item label="库存" prop="stock" v-if="form.id">
        <el-input v-model="form.stock" placeholder="请输入" :maxlength="4" style="width: 350px;"
          @input="e => form.stock = filterNumberInput(e, true)"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false;">取 消</el-button>
        <el-button type="primary" @click="handleOk" :loading="confirmLoading">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from "vue";
import { filterNumberInput } from '@/utils'
import { rechargeRedemption } from "@/api/coupon/index.js";

const visible = ref(false);
const confirmLoading = ref(false);
const formRef = ref(null);

const form = ref({
  id: '',
  stock: '',
  name: '',
  timeScope: [],
  amount: '',
  total: 0,
  startTime: '',
  endTime: '',
});

const resetForm = () => {
  form.value = {
    id: '',
    stock: '',
    name: '',
    timeScope: [],
    amount: '',
    total: 0,
    startTime: '',
    endTime: '',
  };
};

const rules = {
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' },
  ],
  timeScope: [
    { type: 'array', required: true, message: '请选择有效期', trigger: 'change' },
  ],
  amount: [
    { required: true, message: '请输入金额', trigger: 'blur' },
  ],
  total: [
    {
      required: true,
      validator: (rule, value, callback) => {
        const num = Number(value);
        if (value === '' || value == null) {
          callback(new Error('请输入发行数量'));
          return;
        }
        if (isNaN(num) || !Number.isInteger(num)) {
          callback(new Error('请输入有效整数'));
          return;
        }
        if (num < 1) {
          callback(new Error('发行数量需大于1'));
          return;
        }
        if (num > 1000) {
          callback(new Error('发行数量最大1000'));
          return;
        }
        callback();
      },
      trigger: 'blur'
    },
  ],
  stock: [
    {
      required: true,
      validator: (rule, value, callback) => {
        const num = Number(value);
        if (value === '' || value == null) {
          callback(new Error('请输入库存'));
          return;
        }
        if (num > stockFlagNum.value) {
          callback(new Error(`修改库存不能大于${stockFlagNum.value}`));
          return;
        }
        callback();
      },
      trigger: 'blur'
    }
  ]
};

// 开始提交
const emit = defineEmits(['success']);
const handleOk = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        confirmLoading.value = true;
        const data = { ...form.value };
        data.startTime = form.value.timeScope[0];
        data.endTime = form.value.timeScope[1];
        await rechargeRedemption(data, form.value.id ? 'put' : 'post');
        emit('success');
        visible.value = false;
      } catch (error) {
        console.log('error', error);
      }
      setTimeout(() => {
        confirmLoading.value = false;
      }, 500);
    }
  });
};

const onClosed = () => {
  visible.value = false;
  resetForm();
};

const stockFlagNum = ref(0)

function show(obj) {
  console.log(obj);
  if (obj && obj.id) {
    form.value = {
      id: obj.id || '',
      stock: obj.stock || '',
      name: obj.name || '',
      timeScope: obj.startTime && obj.endTime ? [obj.startTime, obj.endTime] : [],
      amount: obj.amount || '',
      total: obj.total || 0,
      startTime: '',
      endTime: '',
    };
    stockFlagNum.value = obj.stock || 0
  } else {
    resetForm();
  }
  visible.value = true;
}

defineExpose({
  show,
});
</script>

<style scoped lang="scss"></style>