<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"
        :formRules="formRules"
        :formConfig="SPECIAL_EQUIPMENT_FORM_CONFIG"
        class="equipment-form"
      >
        <template #deviceStatus>
          <el-radio-group v-model="formData.deviceStatus">
            <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="请选择使用部门"
            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, computed } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import BreadcrumbBack from '@/components/BreadcrumbBack.vue';
  import { querySpecialEquipmentDetail, updateSpecialEquipment, 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 route = useRoute();
  const loading = ref(false);
  const submitting = ref(false);

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

  const formData = reactive({
    ...SPECIAL_EQUIPMENT_FORM_DATA,
    id: undefined as number | undefined,
  });

  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);
      // 根据已有 responsibilityDeptId 反推路径（简单遍历）
      if ((formData as any).responsibilityDeptId) {
        const path: number[] = [];
        const dfs = (nodes: any[], currentPath: number[]): boolean => {
          for (const n of nodes) {
            const newPath = [...currentPath, n.id];
            if (n.id === (formData as any).responsibilityDeptId) {
              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, formData.isUseDepartmentName);
      }
    } catch (e) {
      console.error('获取部门树失败:', e);
      deptOptions.value = [];
    }
  };

  /** 根据部门名称在树中查找路径（用于回显） */
  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 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);
      // useDepartmentPath.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 getDetail = async () => {
    if (!id.value) {
      ElMessage.error('缺少 id');
      return;
    }
    loading.value = true;
    try {
      const res = await querySpecialEquipmentDetail(id.value);
      if (res) {
        (formData as any).id = res.id;
        formData.deviceId = res.deviceId ?? '';
        formData.deviceName = res.deviceName ?? '';
        formData.useUnit = res.useUnit ?? '';
        (formData as any).categoryId = res.categoryId;
        (formData as any).typeId = res.typeId;
        (formData as any).registerCode = res.registerCode ?? '';
        (formData as any).deviceCode = res.deviceCode ?? '';
        formData.isUseDepartmentName = res.isUseDepartmentName?? '',
        (formData as any).useDepartment = res.isUseDepartment ?? '';
        (formData as any).responsiblePerson = res.responsiblePerson ?? '';
        (formData as any).factoryNo = res.factoryNo ?? '';
        formData.startUseDate = res.startUseDate ?? '';
        formData.useYears = res.useYears ?? undefined;
        formData.inspectionTime = res.inspectionTime ?? '';
        formData.assetId = res.assetId ?? '';
        formData.licenseNo = res.licenseNo ?? '';
        formData.safeLocation = res.safeLocation ?? '';
        (formData as any).responsibilityDeptId = res.responsibilityDeptId;
        (formData as any).jobNo = res.jobNo ?? '';
        formData.productionDate = res.productionDate ?? '';
        formData.inspectionCycle = res.inspectionCycle ?? undefined;
        formData.deviceStatus = res.deviceStatus ?? 1;
        formData.nextInspectionDate = res.nextInspectionDate ?? '';
        formData.remark = res.remark ?? '';
        // useDepartmentPath.value = res.isUseDepartment ?? [];
      }
    } catch (e) {
      console.error('获取特种设备设施详情失败:', e);
      ElMessage.error('获取详情失败');
    } finally {
      loading.value = false;
    }
  };

  const handleSubmit = async () => {
    const valid = await basicFormRef.value?.validateForm().catch(() => false);
    if (!valid) return;
    if (!(formData as any).id) {
      ElMessage.error('缺少 id');
      return;
    }
    submitting.value = true;
    try {
      const payload: SpecialEquipment = {
        ...(formData as any),
        id: (formData as any).id,
        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 updateSpecialEquipment(payload);
      ElMessage.success('保存成功');
      router.back();
    } catch (e) {
      console.error('编辑特种设备设施失败:', e);
      ElMessage.error('保存失败，请重试');
    } finally {
      submitting.value = false;
    }
  };

  onMounted(() => {
    getDetail().then(() => {
      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>
