<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Form, FormItem, Input, Button, message } from 'ant-design-vue'
import { SaveOutlined } from '@ant-design/icons-vue'
import { getConfig, updateConfig } from '@/api/system'

/**
 * 页面加载状态
 * 用于控制 Card 组件的加载动画显示
 */
const loading = ref(false)

/**
 * 表单提交状态
 * 用于控制保存按钮的加载状态，防止重复提交
 */
const submitting = ref(false)

/**
 * 表单实例引用
 * 用于调用 Ant Design Vue 表单的方法，如 validate 验证
 */
const formRef = ref()

/**
 * 表单数据状态
 * 存储系统设置的表单字段值
 * @property {string} propertyCompanyName - 物业企业名称
 */
const formState = ref({
  propertyCompanyName: ''
})

/**
 * 表单验证规则
 * 定义各字段的验证规则，用于表单提交前的校验
 * @property {Array} propertyCompanyName - 物业企业名称的验证规则，必填
 */
const rules = {
  propertyCompanyName: [{ required: true, message: '请输入物业企业名称', trigger: 'blur' as const }]
}

/**
 * 组件挂载生命周期钩子
 * 页面加载时自动获取系统配置信息
 * 设置 loading 状态，获取成功后填充表单，失败显示错误提示
 */
onMounted(async () => {
  loading.value = true
  try {
    const res = await getConfig()
    const data = res.data.data || {}
    formState.value.propertyCompanyName = data.property_company_name || ''
  } catch {
    message.error('获取系统设置失败')
  } finally {
    loading.value = false
  }
})

/**
 * 处理表单提交
 * 先验证表单数据，验证通过后调用 API 保存配置
 * 成功显示成功提示，失败显示错误提示
 * @returns {Promise<void>}
 */
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
  } catch {
    return
  }

  submitting.value = true
  try {
    await updateConfig({
      property_company_name: formState.value.propertyCompanyName
    })
    message.success('保存成功')
  } catch {
    message.error('保存失败')
  } finally {
    submitting.value = false
  }
}
</script>

<template>
  <div class="page-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">系统设置</h2>
      <div class="page-header-actions"></div>
    </div>

    <div class="table-card" v-loading="loading">
      <Form
        ref="formRef"
        :model="formState"
        layout="vertical"
        :rules="rules"
      >
        <FormItem label="物业企业名称" name="propertyCompanyName">
          <Input
            v-model:value="formState.propertyCompanyName"
            placeholder="请输入物业企业名称"
            :maxlength="100"
            style="width: 400px"
          />
        </FormItem>

        <FormItem>
          <Button
            type="primary"
            :loading="submitting"
            @click="handleSubmit"
          >
            <SaveOutlined /> 保存设置
          </Button>
        </FormItem>
      </Form>
    </div>
  </div>
</template>

<style scoped>
/* 使用全局 .table-card 样式 */
</style>
