<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { ElMessage } from "element-plus";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { updateQyUserApi } from "@/api/qy/qyUser";
import Confirm from "@iconify-icons/ep/check";
import type { FormRules } from 'element-plus';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  row: {
    type: Object,
    default: null
  }
});

const emit = defineEmits(["update:visible", "refresh"]);

const formRef = ref();
const formData = reactive({
  balance: 0
});

const rules = reactive<FormRules>({
  balance: [
    { required: true, message: "请输入金额", trigger: "blur" },
    { type: 'number', message: '必须为数字类型' },
    { validator: (_, v, cb) => v >= 0 ? cb() : cb(new Error('金额不能小于0')), trigger: 'blur' }
  ]
});

const handleConfirm = async () => {
  try {
    await formRef.value.validate();
    await updateQyUserApi(props.row.id, {
      id: props.row.id,
      balance: formData.balance
    });
    ElMessage.success("余额修改成功");
    emit("refresh");
    closeDialog();
  } catch (error) {
    console.error("表单提交失败", error);
  }
};

const closeDialog = () => {
  formRef.value.resetFields();
  emit("update:visible", false);
};

watch(() => props.row, (val) => {
  if (val) {
    formData.balance = val.balance || 0;
  }
}, { immediate: true });
</script>

<template>
  <el-dialog title="修改余额" :model-value="visible" width="500px" @close="closeDialog">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
      <el-form-item label="金额" prop="balance">
        <el-input-number v-model="formData.balance" :precision="2" :step="0.1" :min="0" controls-position="right"
          class="!w-[200px]" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" :icon="useRenderIcon(Confirm)" @click="handleConfirm">
        确认
      </el-button>
    </template>
  </el-dialog>
</template>