<template>
    <a-card title="创建工单">
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        @finish="handleSubmit"
        layout="vertical"
      >
        <a-form-item label="设备 ID (facilityId)" name="facilityId" required>
          <a-input-number v-model:value="formState.facilityId" placeholder="请输入设备 ID" style="width: 100%;" />
        </a-form-item>
  
        <a-form-item label="描述 (description)" name="description" required>
          <a-input
            v-model:value="formState.description"
            type="textarea"
            placeholder="请输入工单描述"
            style="width: 100%;"
            allow-clear
          />
        </a-form-item>
  
        <a-form-item label="分配人 ID (assigneeId)" name="assigneeId" required>
          <a-input-number v-model:value="formState.assigneeId" placeholder="请输入分配人 ID" style="width: 100%;" />
        </a-form-item>
  
        <a-form-item>
          <a-button type="primary" html-type="submit">提交</a-button>
          <a-button style="margin-left: 8px;" @click="resetForm">重置</a-button>
        </a-form-item>
      </a-form>
    </a-card>
  </template>
  
  <script setup>
  import { ref, reactive } from 'vue';
  import { Form, Card, Button, Input, InputNumber, message } from 'ant-design-vue'; // 导入需要的组件
  import axios from 'axios'; // 用于 HTTP 请求
  import { useRouter } from 'vue-router'; // 用于导航，假设您使用了 Vue Router
  import { localStg } from '@/utils/storage';
  import { apiRequestPost } from '@/utils/api'; // 假设您有一个 API 请求的工具函数
  const formRef = ref(); // 表单引用
  const router = useRouter(); // 获取路由实例
  
  // 表单状态
  const formState = reactive({
    facilityId: undefined, // 设备 ID，数字
    description: '', // 描述，字符串
    assigneeId: undefined, // 分配人 ID，数字
  });
  
  // 表单验证规则
  const rules = {
    facilityId: [
      { required: true, message: '设备 ID 是必填项', trigger: 'blur' },
      { type: 'number', message: '设备 ID 必须是数字', trigger: 'blur' },
    ],
    description: [
      { required: true, message: '描述是必填项', trigger: 'blur' },
      { min: 5, message: '描述至少需要5个字符', trigger: 'blur' },
    ],
    assigneeId: [
      { required: true, message: '分配人 ID 是必填项', trigger: 'blur' },
      { type: 'number', message: '分配人 ID 必须是数字', trigger: 'blur' },
    ],
  };
  
  // 处理表单提交
  const handleSubmit = async () => {
    try {
      //await formRef.value.validate(); // 验证表单

      const response = await apiRequestPost('/work-orders', formState); // 发送 POST 请求
  
      if (response.data.success) {
        message.success('工单创建成功！');
        router.push('/orders'); // 假设订单列表页面路由是 /orders，重定向过去
      } else {
        message.error(response.data.errorMsg || '创建失败');
      }
    } catch (error) {
      message.error('表单验证失败或网络错误');
      console.error(error);
    }
  };
  
  // 重置表单
  const resetForm = () => {
    formRef.value.resetFields(); // 清空表单
  };
  </script>
  
  <style scoped>
  .a-card {
    max-width: 600px;
    margin: 20px auto;
  }
  </style>