<template>
  <el-dialog
      v-model="state.visible"
      :title="state.isEdit ? '编辑活动' : '新增活动'"
      width="550px"
      :close-on-click-modal="false"
      @open="onOpen">
    <el-form ref="formRef" :model="state.form" :rules="rules" label-width="100px">
      <el-form-item label="活动标题" prop="title">
        <el-input v-model="state.form.title" placeholder="请输入活动标题" maxlength="128"/>
      </el-form-item>
      <el-form-item label="充值金额(元)" prop="rechargeAmountYuan">
        <el-input-number v-model="state.form.rechargeAmountYuan" :min="0.01" :precision="2" :step="10"
                         placeholder="充值金额" style="width: 100%"/>
      </el-form-item>
      <el-form-item label="赠送金额(元)" prop="grantsAmountYuan">
        <el-input-number v-model="state.form.grantsAmountYuan" :min="0" :precision="2" :step="5"
                         placeholder="赠送金额" style="width: 100%"/>
      </el-form-item>
      <el-form-item label="目标模式" prop="targetMode">
        <el-radio-group v-model="state.form.targetMode">
          <el-radio :value="1">所有人</el-radio>
          <el-radio :value="2">指定用户</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="指定用户" prop="targetUserIds" v-if="state.form.targetMode === 2">
        <el-input v-model="state.form.targetUserIdsStr" placeholder="请输入用户ID，多个用逗号分隔"/>
      </el-form-item>
      <el-form-item label="有效期" prop="timeRange">
        <el-date-picker
            v-model="state.form.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="状态" prop="status">
        <el-switch v-model="state.form.status" :active-value="1" :inactive-value="0"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="state.visible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="state.submitting">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="RechargePromotionDialog">
import { reactive, ref } from 'vue';
import { $body } from "/@/utils/request";
import { Msg } from "/@/utils/message";

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

const rules = {
  title: [{ required: true, message: '请输入活动标题', trigger: 'blur' }],
  rechargeAmountYuan: [{ required: true, message: '请输入充值金额', trigger: 'blur' }],
  timeRange: [{ required: true, message: '请选择有效期', trigger: 'change' }],
};

const state = reactive({
  visible: false,
  isEdit: false,
  submitting: false,
  editId: null as number | null,
  form: {
    title: '',
    rechargeAmountYuan: null as number | null,
    grantsAmountYuan: 0,
    targetMode: 1,
    targetUserIdsStr: '',
    timeRange: [] as string[],
    status: 1,
  },
});

const open = (mode: string, row: any) => {
  state.isEdit = mode === 'edit';
  state.editId = row?.id || null;
  if (row) {
    state.form.title = row.title || '';
    state.form.rechargeAmountYuan = row.rechargeAmount ? (row.rechargeAmount / 100) : null;
    state.form.grantsAmountYuan = row.grantsAmount ? (row.grantsAmount / 100) : 0;
    state.form.targetMode = row.targetMode || 1;
    if (row.targetUserIds) {
      try {
        const ids = JSON.parse(row.targetUserIds);
        state.form.targetUserIdsStr = Array.isArray(ids) ? ids.join(',') : '';
      } catch {
        state.form.targetUserIdsStr = '';
      }
    } else {
      state.form.targetUserIdsStr = '';
    }
    state.form.timeRange = [row.startTime, row.endTime];
    state.form.status = row.status ?? 1;
  } else {
    resetForm();
  }
  state.visible = true;
};

const resetForm = () => {
  state.form = {
    title: '',
    rechargeAmountYuan: null,
    grantsAmountYuan: 0,
    targetMode: 1,
    targetUserIdsStr: '',
    timeRange: [],
    status: 1,
  };
};

const onOpen = () => {
  formRef.value?.clearValidate();
};

const handleSubmit = () => {
  formRef.value?.validate((valid: boolean) => {
    if (!valid) return;
    state.submitting = true;

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

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

    if (state.isEdit) {
      data.id = state.editId;
    }

    const url = state.isEdit ? '/rechargePromotion/modify' : '/rechargePromotion/add';
    $body(url, data).then(() => {
      Msg.message(state.isEdit ? '修改成功' : '新增成功', 'success');
      state.visible = false;
      state.submitting = false;
      emit('refresh');
    }).catch(() => {
      state.submitting = false;
    });
  });
};

defineExpose({ open });
</script>
