<script setup lang="ts">
import { reactive, ref } from "vue";
import { addRechargeConfigItem, modifyRechargeConfigItem } from "@/api/platform";
import { ElMessage } from "element-plus";

defineOptions({ name: "RechargeConfigItemDialog" });

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

const initState = () => ({
  ruleForm: {
    id: null as number | null,
    groupId: null as number | null,
    rechargeAmountYuan: 0,
    grantsAmountYuan: 0,
    label: ""
  },
  btnLoading: false,
  dialog: {
    isShowDialog: false,
    type: "",
    title: "",
    submitTxt: ""
  },
  rules: {
    rechargeAmountYuan: [{ required: true, message: "请输入充值金额", trigger: "blur" }]
  }
});

const state = reactive(initState());

const open = (action: string = "add", row: any) => {
  state.dialog.title = (action === "add" ? "新增" : "编辑") + "『配置项』";
  state.dialog.submitTxt = (action === "add" ? "新增" : "编辑") + "『配置项』";
  state.dialog.isShowDialog = true;
  if (action !== "add" && row) {
    state.ruleForm = {
      id: row.id,
      groupId: row.groupId,
      rechargeAmountYuan: (row.rechargeAmount || 0) / 100,
      grantsAmountYuan: (row.grantsAmount || 0) / 100,
      label: row.label || ""
    };
  } else if (row) {
    state.ruleForm.groupId = row.groupId;
  }
};

const onClose = () => {
  state.dialog.isShowDialog = false;
  Object.assign(state, initState());
};

const onCancel = () => onClose();

const onSubmit = () => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      state.btnLoading = true;
      const payload = {
        id: state.ruleForm.id,
        groupId: state.ruleForm.groupId,
        rechargeAmount: Math.round(state.ruleForm.rechargeAmountYuan * 100),
        grantsAmount: Math.round(state.ruleForm.grantsAmountYuan * 100),
        label: state.ruleForm.label || null
      };
      const url = !!state.ruleForm.id ? modifyRechargeConfigItem : addRechargeConfigItem;
      url(payload)
        .then(() => {
          state.btnLoading = false;
          ElMessage.success("操作成功");
          onClose();
          emit("refresh");
        })
        .catch(() => {
          state.btnLoading = false;
          ElMessage.error("操作失败");
        });
    } else {
      ElMessage.error("请先完整填写表单");
    }
  });
};

defineExpose({ open });
</script>

<template>
  <div class="system-dialog-container">
    <el-dialog
      :title="state.dialog.title"
      v-model="state.dialog.isShowDialog"
      width="500px"
      draggable
      destroy-on-close
      :close-on-click-modal="false"
      align-center
    >
      <el-form
        :model="state.ruleForm"
        :rules="state.rules"
        label-position="top"
        ref="formRef"
        size="default"
      >
        <el-form-item label="充值金额（元）" prop="rechargeAmountYuan">
          <el-input-number
            v-model="state.ruleForm.rechargeAmountYuan"
            placeholder="充值金额"
            :min="0"
            :step="10"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="赠款金额（元）" prop="grantsAmountYuan">
          <el-input-number
            v-model="state.ruleForm.grantsAmountYuan"
            placeholder="赠款金额（0表示不赠送）"
            :min="0"
            :step="5"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="标签" prop="label">
          <el-input v-model="state.ruleForm.label" placeholder="如：推荐、限时" clearable />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel" size="default">取 消</el-button>
          <el-button :loading="state.btnLoading" type="primary" @click="onSubmit" size="default">
            {{ state.dialog.submitTxt }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
