<script setup lang="ts">
import { reactive, ref } from "vue";
import { addPromotion, modifyPromotion } from "@/api/recharge-promotion";
import { ElMessage } from "element-plus";

const emit = defineEmits(["refresh"]);
const formRef = ref();

const dialogVisible = ref(false);
const dialogType = ref<"add" | "edit">("add");
const submitting = ref(false);

const state = reactive({
  ruleForm: {
    id: null as number | null,
    title: "",
    rechargeAmountYuan: null as number | null,
    grantsAmountYuan: 0,
    targetMode: 1,
    targetUserIdsStr: "",
    timeRange: [] as string[],
    status: 1
  },
  rules: {
    title: [{ required: true, message: "请输入活动标题", trigger: "blur" }],
    rechargeAmountYuan: [{ required: true, message: "请输入充值金额", trigger: "blur" }],
    timeRange: [{ required: true, message: "请选择有效期", trigger: "change" }]
  }
});

const resetForm = () => {
  state.ruleForm = {
    id: null,
    title: "",
    rechargeAmountYuan: null,
    grantsAmountYuan: 0,
    targetMode: 1,
    targetUserIdsStr: "",
    timeRange: [],
    status: 1
  };
  formRef.value?.clearValidate();
};

const open = (mode: "add" | "edit", row?: any) => {
  dialogType.value = mode;
  resetForm();
  if (mode === "edit" && row) {
    state.ruleForm.id = row.id;
    state.ruleForm.title = row.title || "";
    state.ruleForm.rechargeAmountYuan = row.rechargeAmount ? row.rechargeAmount / 100 : null;
    state.ruleForm.grantsAmountYuan = row.grantsAmount ? row.grantsAmount / 100 : 0;
    state.ruleForm.targetMode = row.targetMode || 1;
    if (row.targetUserIds) {
      try {
        const ids = JSON.parse(row.targetUserIds);
        state.ruleForm.targetUserIdsStr = Array.isArray(ids) ? ids.join(",") : "";
      } catch {
        state.ruleForm.targetUserIdsStr = "";
      }
    } else {
      state.ruleForm.targetUserIdsStr = "";
    }
    state.ruleForm.timeRange = [row.startTime, row.endTime];
    state.ruleForm.status = row.status ?? 1;
  }
  dialogVisible.value = true;
};

const handleClose = () => {
  dialogVisible.value = false;
  resetForm();
};

const handleSubmit = async () => {
  const valid = await formRef.value?.validate().catch(() => false);
  if (!valid) return;

  let targetUserIds: string | null = null;
  if (state.ruleForm.targetMode === 2 && state.ruleForm.targetUserIdsStr) {
    const ids = state.ruleForm.targetUserIdsStr
      .split(",")
      .map(s => Number(s.trim()))
      .filter(n => !isNaN(n));
    targetUserIds = JSON.stringify(ids);
  }

  const data: any = {
    title: state.ruleForm.title,
    rechargeAmount: Math.round((state.ruleForm.rechargeAmountYuan || 0) * 100),
    grantsAmount: Math.round((state.ruleForm.grantsAmountYuan || 0) * 100),
    targetMode: state.ruleForm.targetMode,
    targetUserIds,
    startTime: state.ruleForm.timeRange[0],
    endTime: state.ruleForm.timeRange[1],
    status: state.ruleForm.status
  };

  if (dialogType.value === "edit") {
    data.id = state.ruleForm.id;
  }

  submitting.value = true;
  try {
    if (dialogType.value === "add") {
      await addPromotion(data);
    } else {
      await modifyPromotion(data);
    }
    ElMessage.success(dialogType.value === "add" ? "新增成功" : "修改成功");
    handleClose();
    emit("refresh");
  } catch {
    ElMessage.error("操作失败");
  } finally {
    submitting.value = false;
  }
};

defineExpose({ open });
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogType === 'add' ? '新增活动' : '编辑活动'"
    width="550px"
    :close-on-click-modal="false"
  >
    <el-form ref="formRef" :model="state.ruleForm" :rules="state.rules" label-width="100px">
      <el-form-item label="活动标题" prop="title">
        <el-input v-model="state.ruleForm.title" placeholder="请输入活动标题" maxlength="128" />
      </el-form-item>
      <el-form-item label="充值金额(元)" prop="rechargeAmountYuan">
        <el-input-number
          v-model="state.ruleForm.rechargeAmountYuan"
          :min="0.01"
          :precision="2"
          :step="10"
          placeholder="充值金额"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="赠送金额(元)">
        <el-input-number
          v-model="state.ruleForm.grantsAmountYuan"
          :min="0"
          :precision="2"
          :step="5"
          placeholder="赠送金额"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="目标模式">
        <el-radio-group v-model="state.ruleForm.targetMode">
          <el-radio :value="1">所有人</el-radio>
          <el-radio :value="2">指定用户</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="指定用户" v-if="state.ruleForm.targetMode === 2">
        <el-input v-model="state.ruleForm.targetUserIdsStr" placeholder="请输入用户ID，多个用逗号分隔" />
      </el-form-item>
      <el-form-item label="有效期" prop="timeRange">
        <el-date-picker
          v-model="state.ruleForm.timeRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="状态">
        <el-switch v-model="state.ruleForm.status" :active-value="1" :inactive-value="0" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="submitting" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>
