<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
        v-loading="loading"
        ref="basicFormRef"
        :formData="formData"
        :formConfig="viewFormConfig"
      >
        <template #deviceStatus>
          <el-radio-group v-model="formData.deviceStatus" disabled>
            <el-radio :label="1">在用</el-radio>
            <el-radio :label="2">停用</el-radio>
            <el-radio :label="3">报废</el-radio>
          </el-radio-group>
        </template>
        <template #useDepartment>
          <el-cascader
            v-model="useDepartmentPath"
            :options="deptOptions"
            :props="deptCascaderProps"
            :show-all-levels="false"
            placeholder="请选择使用部门"
            class="act-search-input"
            filterable
            clearable
            disabled
          />
        </template>
        <template #responsibilityDept>
          <el-cascader
            v-model="responsibilityDeptPath"
            :options="deptOptions"
            :props="deptCascaderProps"
            :show-all-levels="false"
            placeholder="请选择责任部门"
            class="act-search-input"
            filterable
            clearable
            disabled
          />
        </template>
      </BasicForm>
    </main>
    <footer class="safety-platform-container__footer">
      <el-button @click="router.back()">返回</el-button>
    </footer>
  </div>
</template>

<script setup lang="ts">
  import { reactive, ref, onMounted, computed } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import BreadcrumbBack from '@/components/BreadcrumbBack.vue';
  import BasicForm from '@/components/BasicForm.vue';
  import { querySpecialEquipmentDetail, type SpecialEquipment } from '@/api/production-safety/special-equipment';
  import { SPECIAL_EQUIPMENT_FORM_CONFIG, SPECIAL_EQUIPMENT_FORM_DATA } from './configs/form';
  import { getAllDepartments } from '@/api/auth/dept';
  import { formatDeptTree } from '@/views/disaster/utils/formatDeptTree';

  const router = useRouter();
  const route = useRoute();
  const loading = ref(false);

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

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

  const viewFormConfig = ref(
    SPECIAL_EQUIPMENT_FORM_CONFIG.map((item) => ({
      ...item,
      componentProps: {
        ...(item.componentProps || {}),
        disabled: true,
      },
    })),
  );

  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 getDeptPathByName = (options: any[], name: string): number[] => {
    if (!name || !options?.length) return [];
    const dfs = (nodes: any[], currentPath: number[]): number[] => {
      for (const n of nodes) {
        const newPath = [...currentPath, n.id];
        if (n.deptName === name) return newPath;
        if (n.children?.length) {
          const found = dfs(n.children, newPath);
          if (found.length) return found;
        }
      }
      return [];
    };
    return dfs(options, []);
  };

  const getDetail = async () => {
    if (!id.value) {
      ElMessage.error('缺少 id');
      return;
    }
    loading.value = true;
    try {
      const res = (await querySpecialEquipmentDetail(id.value)) as SpecialEquipment | undefined;
      if (res) {
        formData.deviceId = res.deviceId ?? '';
        formData.assetId = res.assetId ?? '';
        formData.deviceName = res.deviceName ?? '';
        formData.useUnit = res.useUnit ?? '';
        (formData as any).categoryId = res.categoryId ?? undefined;
        (formData as any).typeId = res.typeId ?? undefined;
        formData.registerCode = res.registerCode ?? '';
        formData.licenseNo = res.licenseNo ?? '';
        formData.deviceCode = res.deviceCode ?? '';
        formData.safeLocation = res.safeLocation ?? '';
        formData.useDepartment = res.isUseDepartment ?? undefined;
        (formData as any).responsibilityDeptId = res.responsibilityDeptId ?? undefined;
        formData.responsiblePerson = res.responsiblePerson ?? '';
        formData.jobNo = res.jobNo ?? '';
        formData.factoryNo = res.factoryNo ?? '';
        formData.productionDate = res.productionDate ?? '';
        formData.startUseDate = res.startUseDate ?? '';
        formData.inspectionCycle = res.inspectionCycle ?? undefined;
        formData.useYears = res.useYears ?? undefined;
        formData.inspectionTime = res.inspectionTime ?? '';
        formData.deviceStatus = res.deviceStatus ?? 1;
        formData.nextInspectionDate = res.nextInspectionDate ?? '';
        formData.remark = res.remark ?? '';

        // 加载部门树并回显路径
        try {
          const deptRes = await getAllDepartments();
          deptOptions.value = formatDeptTree(deptRes);
          const targetId = (formData as any).responsibilityDeptId;
          if (targetId) {
            const dfs = (nodes: any[], currentPath: number[]): boolean => {
              for (const n of nodes) {
                const newPath = [...currentPath, n.id];
                if (n.id === targetId) {
                  responsibilityDeptPath.value = newPath;
                  return true;
                }
                if (n.children && n.children.length && dfs(n.children, newPath)) {
                  return true;
                }
              }
              return false;
            };
            dfs(deptOptions.value, []);
          }
          if (formData.useDepartment) {
            useDepartmentPath.value = getDeptPathByName(deptOptions.value, res.isUseDepartmentName);
          }
        } catch (e) {
          console.error('获取部门树失败:', e);
          deptOptions.value = [];
        }
      }
    } catch (e) {
      console.error('获取特种设备设施详情失败:', e);
      ElMessage.error('获取详情失败');
    } finally {
      loading.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;
  }
</style>
