<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">
      <BasicForm
        ref="basicFormRef"
        :formData="formData"
        :formRules="formRules"
        :formConfig="SPECIAL_EQUIPMENT_FORM_CONFIG"
        class="equipment-form"
      >
        <template #deviceStatus>
          <el-radio-group v-model="formData.deviceStatus">
            <el-radio :value="1">在用</el-radio>
            <el-radio :value="2">停用</el-radio>
            <el-radio :value="3">报废</el-radio>
          </el-radio-group>
        </template>
        <template #useDepartment>
          <el-cascader
            v-model="useDepartmentPath"
            :options="deptOptions"
            :props="deptCascaderProps"
            :show-all-levels="false"
            placeholder="请选择使用部门"
            filterable
            clearable
            @change="handleUseDeptChange"
          />
        </template>
        <template #responsibilityDept>
          <el-cascader
            v-model="responsibilityDeptPath"
            :options="deptOptions"
            :props="deptCascaderProps"
            :show-all-levels="false"
            placeholder="请选择责任部门"
            filterable
            clearable
            @change="handleDeptChange"
          />
        </template>
      </BasicForm>
    </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 { reactive, ref, onMounted } from 'vue';
  import { useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import BreadcrumbBack from '@/components/BreadcrumbBack.vue';
  import { saveSpecialEquipment, type SpecialEquipment } from '@/api/production-safety/special-equipment';
  import { getAllDepartments } from '@/api/auth/dept';
  import { formatDeptTree } from '@/views/disaster/utils/formatDeptTree';
  import BasicForm from '@/components/BasicForm.vue';
  import {
    SPECIAL_EQUIPMENT_FORM_CONFIG,
    SPECIAL_EQUIPMENT_FORM_DATA,
    SPECIAL_EQUIPMENT_FORM_RULES,
  } from './configs/form';

  const router = useRouter();
  const submitting = ref(false);

  const formData = reactive({
    ...SPECIAL_EQUIPMENT_FORM_DATA,
  });

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

  // 部门树（queryAllDeptTree 样式）
  const deptOptions = ref<any[]>([]);
  const responsibilityDeptPath = ref<number[]>([]);
  const useDepartmentPath = ref<number[]>([]);
  const deptCascaderProps = {
    expandTrigger: 'click',
    checkStrictly: true,
    value: 'id',
    label: 'deptName',
  };

  const formRules = SPECIAL_EQUIPMENT_FORM_RULES;

  const loadDeptTree = async () => {
    try {
      const res = await getAllDepartments();
      deptOptions.value = formatDeptTree(res);
    } catch (e) {
      console.error('获取部门树失败:', e);
      deptOptions.value = [];
    }
  };

  /** 根据部门树路径取末级部门名称（使用部门复用责任部门） */
  const getDeptNameByPath = (options: any[], pathIds: number[]): string => {
    if (!pathIds?.length) return '';
    let current = options;
    let name = '';
    for (const id of pathIds) {
      const node = current.find((n: any) => n.id === id);
      if (!node) return name;
      name = node.deptName;
      current = node.children || [];
    }
    return name;
  };

  const handleDeptChange = (val: number[]) => {
    if (Array.isArray(val) && val.length) {
      (formData as any).responsibilityDeptId = val[val.length - 1];
      (formData as any).useDepartment = getDeptNameByPath(deptOptions.value, val);
      responsibilityDeptPath.value = [...val];
    } else {
      (formData as any).responsibilityDeptId = undefined;
    }
  };

  const handleUseDeptChange = (val: number[]) => {
    if (Array.isArray(val) && val.length) {
      (formData as any).useDepartment = getDeptNameByPath(deptOptions.value, val);
    } else {
      (formData as any).useDepartment = '';
    }
  };

  const handleSubmit = async () => {
    const valid = await basicFormRef.value?.validateForm().catch(() => false);
    if (!valid) return;
    submitting.value = true;
    try {
      const payload: SpecialEquipment = {
        ...(formData as any),
        deviceId: formData.deviceId || undefined,
        deviceName: formData.deviceName || undefined,
        useUnit: formData.useUnit || undefined,
        registerCode: (formData as any).registerCode || undefined,
        deviceCode: (formData as any).deviceCode || undefined,
        useDepartment: (formData as any).useDepartment || undefined,
        responsiblePerson: (formData as any).responsiblePerson || undefined,
        factoryNo: (formData as any).factoryNo || undefined,
        startUseDate: formData.startUseDate || undefined,
        inspectionTime: formData.inspectionTime || undefined,
        assetId: formData.assetId || undefined,
        licenseNo: formData.licenseNo || undefined,
        safeLocation: formData.safeLocation || undefined,
        jobNo: (formData as any).jobNo || undefined,
        productionDate: formData.productionDate || undefined,
        nextInspectionDate: formData.nextInspectionDate || undefined,
        remark: formData.remark || undefined,
      };
      await saveSpecialEquipment(payload);
      ElMessage.success('新增成功');
      router.back();
    } catch (e) {
      console.error('新增特种设备设施失败:', e);
      ElMessage.error('新增失败，请重试');
    } finally {
      submitting.value = false;
    }
  };

  onMounted(() => {
    loadDeptTree();
  });
</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;
  }
  .equipment-form {
    max-width: 700px;
  }
</style>
