<template>
  <el-dialog :title="form.id ? '编辑兑换码' : '添加兑换码'" width="500px" v-model="visible" @closed="onClosedHandle">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" 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="total">
        <div class="column">
          <el-input v-model="form.total" placeholder="请输入" :maxlength="8" style="width: 350px;"
            @input="e => form.total = filterNumberInput(e, true)" :disabled="!!form.id">
            <template #append>个</template>
          </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-item label="赠送优惠券" style="margin-top: 14px;" prop="coupon">
        <div class="center" v-for="(item, index) in selectCoupons" :key="item.id">
          <el-select v-model="item.id" @change="selectCouponChnge($event, index)">
            <el-option :label="val.title" :value="val.id" v-for="val in couponList" :key="val.id"></el-option>
          </el-select>
          <el-input v-model="item.num" input-style="text-align:center;">
            <template #append>张/1个码</template>
          </el-input>
          <div class="del" @click="selectCoupons.splice(index, 1)">
            <el-icon size="18" color="#FF2F2F">
              <Delete />
            </el-icon>
          </div>
        </div>
        <div class="center">
          <el-button link type="primary" icon="CirclePlus" @click="addCoupon">新增券</el-button>
        </div>
      </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 _ from 'lodash'
import { ref, nextTick, onMounted } from "vue";
import { filterNumberInput } from '@/utils'
import { couponRedemption, couponPage } 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 = ref({})

// 关闭后重置表单
function onClosedHandle() {
  form.value = { ...resetForm.value };
  selectCoupons.value = [];

  nextTick(() => {
    setTimeout(() => {
      formRef.value.resetFields();
    }, 100);
  });
}

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'
    }
  ],
  coupon: [
    {
      required: true,
      validator: (rule, value, callback) => {
        // value 是 selectCoupons.value 的 JSON 字符串
        let coupons = selectCoupons.value;
        if (coupons.length === 0) {
          callback(new Error('至少添加1种优惠券'));
          return;
        } else {
          // 校验每个优惠券
          for (let i = 0; i < coupons.length; i++) {
            if (!coupons[i].id) {
              callback(new Error('请选择优惠券'));
              return;
            }
            if (!coupons[i].num || !Number.isInteger(Number(coupons[i].num)) || Number(coupons[i].num) <= 0) {
              callback(new Error('请输入大于零的优惠券数量'));
              return;
            }
          }
          callback();
        }
      },
      trigger: 'change'
    }
  ],
};

// 开始提交
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];
        data.couponInfoList = selectCoupons.value;
        await couponRedemption(data, form.value.id ? 'put' : 'post');
        emit('success');
        visible.value = false;
      } catch (error) {
        console.log('error', error);
      }
      setTimeout(() => {
        confirmLoading.value = false;
      }, 500);
    }
  });
};

// 选择优惠券开始
const couponList = ref([])
const selectCoupons = ref([]);
const couponObj = ref({ id: '', num: 1, title: '' });

// 选择优惠券添加标题
function selectCouponChnge(e, index) {
  const coupon = couponList.value.find(item => item.id === e)
  if (coupon) {
    selectCoupons.value[index].title = coupon.title
  }
}

// 新增优惠券
function addCoupon() {
  selectCoupons.value.push(_.cloneDeep(couponObj.value));
}

// 获取优惠券列表
async function couponPageAjax() {
  try {
    const res = await couponPage({
      shopId: form.value.shopId,
      page: 1,
      size: 500
    })
    couponList.value = res.records
  } catch (error) {
    console.log(error);
  }
}
// 选择优惠券结束

const stockFlagNum = ref(0)

function show(obj) {
  couponPageAjax()
  if (obj && obj.id) {
    form.value = { ...obj }
    form.value.timeScope = obj.startTime && obj.endTime ? [obj.startTime, obj.endTime] : []

    selectCoupons.value = obj.couponInfoList

    stockFlagNum.value = obj.stock || 0
  } else {
    onClosedHandle();
  }
  visible.value = true;
}

defineExpose({
  show,
});

onMounted(() => {
  resetForm.value = { ...form.value }
})
</script>

<style scoped lang="scss">
.center {
  display: flex;
  align-items: center;
  gap: 14px;

  &:not(:first-child) {
    margin-top: 14px;
  }

  .del {
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
  }
}
</style>