<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({
  balanceLimit: 0
});

const rules = reactive<FormRules>({
  balanceLimit: [
    { 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,
      balanceLimit: formData.balanceLimit
    });
    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.balanceLimit = val.balanceLimit || 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="balanceLimit">
        <el-input-number v-model="formData.balanceLimit" :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>