<template>
  <div class="safety-platform-container">
    <header class="safety-platform-container__header">
      <div class="breadcrumb-title">
        <BreadcrumbBack />
        查看非公共区域责任区域
      </div>
    </header>
    <main class="safety-platform-container__main">
      <el-form ref="formRef" label-width="auto" :model="formValue">
        <el-form-item label="楼号">
          <el-input disabled v-model="formValue.buildingNo" size="large" style="width: 50%" />
        </el-form-item>
        <el-form-item label="楼层">
          <el-input disabled v-model="formValue.buildingArea" size="large" style="width: 50%" />
        </el-form-item>
        <el-form-item label="房间/区域">
          <el-input disabled v-model="formValue.floorRoomNo" size="large" style="width: 50%" />
        </el-form-item>
        <el-form-item label="功能名称">
          <el-input disabled v-model="formValue.nameFunction" size="large" style="width: 50%" />
        </el-form-item>

        <el-form-item label="安全责任所/中心">
          <el-cascader
            disabled
            v-model="formValue.safetyResponsibleCenterId"
            style="width: 50%"
            size="large"
            :options="firstLevelDepts"
            :props="cascaderProp"
            :show-all-levels="false"
          />
        </el-form-item>

        <el-form-item label="安全责任所/中心负责人">
          <el-select disabled v-model="formValue.safetyCenterManager" size="large" style="width: 50%">
            <el-option
              v-for="item in safetyCenterManagerOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="安全责任部门">
          <el-cascader
            disabled
            v-model="formValue.safetyResponsibleDepartmentId"
            style="width: 50%"
            size="large"
            :options="firstLevelDepts"
            :props="cascaderProp"
            :show-all-levels="false"
          />
        </el-form-item>

        <el-form-item label="安全责任部门负责人">
          <el-select disabled v-model="formValue.safetyDepartmentManager" size="large" style="width: 50%">
            <el-option v-for="item in userOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="安全具体责任人">
          <el-select disabled v-model="formValue.safetySpecificPerson" size="large" style="width: 50%">
            <el-option v-for="item in userOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="安全具体责任人联系方式">
          <el-input disabled v-model="formValue.safetyPersonContact" size="large" style="width: 50%" />
        </el-form-item>
      </el-form>
    </main>
    <footer class="safety-platform-container__footer">
      <el-button type="primary" @click="$router.push({ name: 'areaResponsibilities:nonPublic' })">返回</el-button>
    </footer>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, onMounted } from 'vue';
  import { useRoute } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import { getAllDepartments } from '@/api/auth/dept';
  import { formatDeptTree } from '@/views/disaster/utils/formatDeptTree';
  import {
    areaCheckListQueryDetail,
    queryAvailableUserList,
  } from '@/api/production-safety/responsibility-implementation';

  const route = useRoute();

  const userOptions = ref<any[]>([]);
  const safetyCenterManagerOptions = ref<any[]>([]);
  const firstLevelDepts = ref<any[]>([]);
  const cascaderProp = { value: 'id', label: 'deptName', checkStrictly: true };

  const formValue = reactive({
    buildingNo: '',
    buildingArea: '',
    floorRoomNo: '',
    nameFunction: '',
    safetyResponsibleCenter: '',
    safetyResponsibleCenterId: [],
    safetyCenterManager: null as number | null,
    safetyResponsibleDepartment: '',
    safetyResponsibleDepartmentId: [],
    safetyDepartmentManager: null as number | null,
    safetySpecificPerson: null as number | null,
    safetyPersonContact: '',
  });

  const getDeptData = async () => {
    const res = await getAllDepartments();
    firstLevelDepts.value = formatDeptTree(res);
  };

  const getUserData = (optionList: any, deptName: string) => {
    return queryAvailableUserList({
      pageNumber: 1,
      pageSize: 200,
      queryParam: { deptName },
    }).then((res: any) => {
      optionList.value = (res.records || []).map((u: any) => ({
        value: u.id,
        label: u.realname,
      }));
    });
  };

  const handlAreaCheckListQueryDetail = async () => {
    const id = route.query.id;
    if (!id) return;

    try {
      const res: any = await areaCheckListQueryDetail({ id });
      if (res) {
        Object.assign(formValue, res);

        // 1. 解析级联 ID 数组
        try {
          if (typeof res.safetyResponsibleCenterId === 'string') {
            formValue.safetyResponsibleCenterId = JSON.parse(res.safetyResponsibleCenterId);
          }
          if (typeof res.safetyResponsibleDepartmentId === 'string') {
            formValue.safetyResponsibleDepartmentId = JSON.parse(res.safetyResponsibleDepartmentId);
          }
        } catch (e) {
          console.error('解析部门ID路径失败', e);
        }

        // 2. 类型转换
        formValue.safetyCenterManager = res.safetyCenterManager ? Number(res.safetyCenterManager) : null;
        formValue.safetyDepartmentManager = res.safetyDepartmentManager ? Number(res.safetyDepartmentManager) : null;
        formValue.safetySpecificPerson = res.safetySpecificPerson ? Number(res.safetySpecificPerson) : null;
        // 3. 补全人员名单以显示姓名
        if (formValue.safetyResponsibleCenter) {
          getUserData(safetyCenterManagerOptions, formValue.safetyResponsibleCenter);
        }
        if (formValue.safetyResponsibleDepartment) {
          getUserData(userOptions, formValue.safetyResponsibleDepartment);
        }
      }
    } catch (err) {
      ElMessage.error('获取详情失败');
    }
  };

  onMounted(async () => {
    await getDeptData();
    handlAreaCheckListQueryDetail();
  });
</script>

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