<template>
  <div class="safety-platform-container">
    <header class="safety-platform-container__header">
      <BreadcrumbBack />
      <span class="breadcrumb-title">编辑劳防用品</span>
    </header>
    <main class="safety-platform-container__main">
      <el-form
        v-loading="loading"
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="120px"
        class="ppe-form"
      >
        <el-form-item label="作业(岗位)分类" prop="jobPost">
          <el-input v-model="form.jobPost" placeholder="请输入作业(岗位)分类" clearable />
        </el-form-item>
        <el-form-item label="物品分类" prop="ppeCategory">
          <el-input v-model="form.ppeCategory" placeholder="请输入物品分类" clearable />
        </el-form-item>
        <el-form-item label="物品名称" prop="ppeName">
          <el-input v-model="form.ppeName" placeholder="请输入物品名称" clearable />
        </el-form-item>
        <el-form-item label="使用期限(月)" prop="serviceMonths">
          <el-input-number
            v-model="form.serviceMonths"
            :min="1"
            :max="9999"
            :precision="0"
            placeholder="1-9999"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="用品状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :value="true">启用</el-radio>
            <el-radio :value="false">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入备注"
            :rows="3"
            clearable
          />
        </el-form-item>
      </el-form>
    </main>
    <footer class="safety-platform-container__footer">
      <el-button @click="router.back()">返回</el-button>
      <el-button type="primary" :loading="submitting" @click="handleSubmit">保存</el-button>
    </footer>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, computed } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
  import BreadcrumbBack from '@/components/BreadcrumbBack.vue';
  import {
    queryPersonalProtectiveEquipmentDetail,
    updatePersonalProtectiveEquipment,
  } from '@/api/production-safety/personal-protective-equipment';

  const router = useRouter();
  const route = useRoute();
  const formRef = ref<FormInstance>();
  const loading = ref(false);
  const submitting = ref(false);

  const id = computed(() => Number(route.query.id));

  const form = reactive({
    id: undefined as number | undefined,
    jobPost: '',
    ppeCategory: '',
    ppeName: '',
    serviceMonths: undefined as number | undefined, // 1-9999 整数
    status: true, // true-启用，false-禁用，默认启用
    remark: '',
  });

 const formRules: FormRules = {
    jobPost:[{ required: true, message: '请输入作业(岗位)分类', trigger: 'blur' }],
    ppeCategory: [{ required: true, message: '请输入物品分类', trigger: 'blur' }],
    ppeName:[{ required: true, message: '请输入物品名称', trigger: 'blur' }],
    serviceMonths: [{ required: true, message: '请输入使用期限', trigger: 'blur' }],
    status: [{ required: true, message: '请输入用品状态', trigger: 'change' }],
    remark: [{ required: true, message: '请输入备注', trigger: 'blur' }],
  };

  const getDetail = async () => {
    if (!id.value) {
      ElMessage.error('缺少 id');
      return;
    }
    loading.value = true;
    try {
      const res = await queryPersonalProtectiveEquipmentDetail(id.value);
      if (res) {
        form.id = res.id;
        form.jobPost = res.jobPost ?? '';
        form.ppeCategory = res.ppeCategory ?? '';
        form.ppeName = res.ppeName ?? '';
        const sm = res.serviceMonths;
        form.serviceMonths =
          sm !== '' && sm != null && !Number.isNaN(Number(sm)) ? Number(sm) : undefined;
        form.status = res.status
        form.remark = res.remark ?? '';
      }
    } catch (e) {
      console.error('获取劳防用品详情失败:', e);
      ElMessage.error('获取详情失败');
    } finally {
      loading.value = false;
    }
  };

  const handleSubmit = async () => {
    const valid = await formRef.value?.validate().then(() => true).catch(() => false);
    if (!valid) return;
    if (!form.id) {
      ElMessage.error('缺少 id');
      return;
    }
    submitting.value = true;
    try {
      await updatePersonalProtectiveEquipment({
        id: form.id,
        jobPost: form.jobPost || undefined,
        ppeCategory: form.ppeCategory || undefined,
        ppeName: form.ppeName || undefined,
        serviceMonths: form.serviceMonths != null ? String(form.serviceMonths) : undefined,
        status: form.status,
        remark: form.remark || undefined,
      });
      ElMessage.success('保存成功');
      router.back();
    } catch (e) {
      console.error('编辑劳防用品失败:', e);
      ElMessage.error('保存失败，请重试');
    } finally {
      submitting.value = false;
    }
  };

  onMounted(() => {
    getDetail();
  });
</script>

<style scoped lang="scss">
  @use '@/styles/page-details-layout.scss' as *;
  @use '@/styles/page-main-layout.scss' as *;

  .safety-platform-container__header {
    flex-direction: row !important;
    justify-content: flex-start !important;
    gap: 8px !important;
  }
  .ppe-form {
    max-width: 600px;
  }
</style>
