<template>
  <main class="safety-platform-container__main">
    <BasicForm
      ref="basicFormRef"
      :formData="ruleFormData"
      :formRules="isViewMode ? undefined : formRules"
      :formConfig="computedFormConfig"
    >
      <template #status>
        <el-radio-group v-model="ruleFormData.status" :disabled="isViewMode">
          <el-radio :value="1">启用</el-radio>
          <el-radio :value="0">禁用</el-radio>
        </el-radio-group>
      </template>
    </BasicForm>
  </main>
  <footer class="safety-platform-container__footer">
    <el-button @click="router.back()">返回</el-button>
    <el-button v-if="!isViewMode" type="primary" @click="handleSubmit">
      {{ isCreateMode ? '提交' : '保存' }}
    </el-button>
  </footer>
</template>

<script setup lang="ts">
  import { computed, onMounted, ref } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import BasicForm from '@/components/BasicForm.vue';
  import { useFormConfigHook } from '@/hooks/useFormConfigHook';
  import { ACADEMY_FILE_FORM_CONFIG, ACADEMY_FILE_FORM_DATA, ACADEMY_FILE_FORM_RULES } from '../configs/form';
  import {
    queryDangerTypeById,
    saveDangerType,
    updateDangerType,
  } from '@/api/production-safety';

  const router = useRouter();
  const route = useRoute();

  const operate = computed(() => (route.query.operate as string) || 'hidden-trouble-category-create');
  const currentId = computed(() => Number(route.query.id));

  const isCreateMode = computed(() => operate.value === 'hidden-trouble-category-create');
  const isEditMode = computed(() => operate.value === 'hidden-trouble-category-edit');
  const isViewMode = computed(() => operate.value === 'hidden-trouble-category-view');

  const { ruleFormData, formRules, ruleFormConfig, cloneRuleFormData } =
    useFormConfigHook(ACADEMY_FILE_FORM_CONFIG, ACADEMY_FILE_FORM_DATA, ACADEMY_FILE_FORM_RULES);

  // 查看模式下，所有字段设为只读
  const viewFormConfig = ref(
    ACADEMY_FILE_FORM_CONFIG.map((item) => ({
      ...item,
      componentProps: {
        ...item.componentProps,
        disabled: true,
      },
    })),
  );

  const computedFormConfig = computed(() => {
    if (isViewMode.value) {
      return viewFormConfig.value;
    }
    return ruleFormConfig.value;
  });

  const basicFormRef = ref<InstanceType<typeof BasicForm>>();

  const handleValidate = async () => {
    if (!basicFormRef.value) return;
    const res = await basicFormRef.value.validateForm();
    return res;
  };

  const getDetail = async () => {
    if (!currentId.value) return;
    try {
      const res = await queryDangerTypeById(currentId.value);
      if (res) {
        ruleFormData.categoryName = res.categoryName || '';
        ruleFormData.description = res.description || '';
        ruleFormData.status = res.status ?? 1;
      }
      cloneRuleFormData();
    } catch (e) {
      console.error('获取隐患类别详情失败:', e);
      ElMessage.error(e?.message || e?.data || '获取详情失败');
    }
  };

  const handleSubmit = async () => {
    const res = await handleValidate();
    if (!res) return;
    try {
      const basePayload = {
        categoryName: ruleFormData.categoryName,
        description: ruleFormData.description || '',
        status: ruleFormData.status ?? 1,
      };

      if (isCreateMode.value) {
        await saveDangerType(basePayload);
        ElMessage.success('创建成功');
      } else if (isEditMode.value && currentId.value) {
        await updateDangerType({
          id: currentId.value,
          ...basePayload,
        });
        ElMessage.success('保存成功');
      }

      router.back();
    } catch (e) {
      console.error('保存隐患类别失败:', e);
      ElMessage.error(e?.message || e?.data || '保存失败，请重试');
    }
  };

  onMounted(() => {
    cloneRuleFormData();
    if (isEditMode.value || isViewMode.value) {
      getDetail();
    }
  });
</script>

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

