<template>
  <main class="safety-platform-container__main">
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      style="max-width: 600px"
      label-position="left"
    >
      <el-form-item label="员工工号：" prop="employeeId" required>
        <el-input v-model="form.employeeId" placeholder="请输入员工工号" :disabled="isViewMode" />
      </el-form-item>

      <el-form-item label="员工姓名：" prop="employeeName" required>
        <el-input v-model="form.employeeName" placeholder="请输入员工姓名" :disabled="isViewMode" />
      </el-form-item>

      <el-form-item label="组织名称：" prop="orgId" required>
        <el-tree-select
          placeholder="请选择组织名称"
          v-model="form.orgId"
          :data="organizations"
          check-strictly
          :render-after-expand="false"
          @change="handleOrgChange"
          :disabled="isViewMode"
        >
        </el-tree-select>
      </el-form-item>

      <el-form-item label="岗位职责：" prop="jobResp" required>
        <el-input
          v-model="form.jobResp"
          type="textarea"
          :rows="4"
          :maxlength="200"
          placeholder="请填写岗位职责"
          :disabled="isViewMode"
        />
      </el-form-item>

      <!-- 状态 -->
      <el-form-item label="状态：" prop="status" required>
        <el-radio-group v-model="form.status" :disabled="isViewMode">
          <el-radio :value="1">启用</el-radio>
          <el-radio :value="2">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
  </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 { FORM_RULES } from '../configs/form';
  import {
    getSafetySystemList,
    addEmployee,
    updateEmployee,
    employeeDetail,
  } from '@/api/safety-organization-management';

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

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

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

  interface FormDataType {
    id?: number;
    orgId?: string;
    employeeId: string;
    employeeName: string;
    jobResp: string;
    status: string|number;
    selectedOrg?: any;
  }

  const form = ref<FormDataType>({
    id: undefined,
    orgId: '',
    employeeId: '',
    employeeName: '',
    jobResp: '',
    status: 1,
  });
  const selectedOrg = ref({});
  // 表单验证规则
  const rules = ref(FORM_RULES);
  // 组织名称选项
  const organizations = ref([]);
  // 获取组织列表
  const fetchSafetyOrganizationTeamList = async () => {
    try {
      const res = await getSafetySystemList();
      organizations.value = formatTreeData(res);
    } catch (error) {
      ElMessage.error('获取组织列表失败');
    }
  };
  // 组织名称剔除空的children
  const formatTreeData = (data) => {
    return data
      .map((node) => {
        const children = node.children?.length ? formatTreeData(node.children) : undefined;
        return {
          value: node.orgId,
          label: node.orgName,
          orgId: node.orgId,
          orgName: node.orgName,
          children,
        };
      })
      .filter((node) => node); // 过滤掉无效节点
  };
  // 在树数据中根据 value 查找节点
  const findNodeByValue = (tree, value) => {
    if (!tree || !Array.isArray(tree)) {
      return null;
    }

    for (const node of tree) {
      // 如果当前节点的value匹配，返回该节点
      if (node.value === value || node.orgId === value) {
        return node;
      }

      // 如果有子节点，递归查找
      if (node.children && node.children.length > 0) {
        const found = findNodeByValue(node.children, value);
        if (found) {
          return found;
        }
      }
    }
    return null;
  };

  // 选中组织变化时的回调
  const handleOrgChange = (value) => {
    // 通过 value 在 organizations 树中查找对应的节点
    const selectedNode = findNodeByValue(organizations.value, value);

    if (selectedNode) {
      // 存储当前选中的组织信息
      form.value.orgId = selectedNode.orgId;
      selectedOrg.value = selectedNode;
    }
  };

  const formRef = ref();

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

  const getDetail = async () => {
    if (!currentId.value) return;
    try {
      const res = await employeeDetail(currentId.value);
      if (res) {
        // 详情页面（映射接口字段到表单字段）
        Object.assign(form.value, res);
      }
    } catch (e) {
      console.error('获取详情失败:', e);
      ElMessage.error('获取详情失败');
    }
  };

  const handleSubmit = async () => {
    const res = await handleValidate();
    if (!res) return;
    try {
      console.log(res, form.value);

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

      router.back();
    } catch (e) {
      console.error('保存失败:', e);
      ElMessage.error('保存失败，请重试');
    }
  };

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

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

  .el-form-item {
    margin-bottom: 30px;
  }
</style>
