<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" :rules="rules">
        <!-- <el-form-item label="楼号" prop="buildingNo">
                    <el-input v-model="formValue.buildingNo" size="large" placeholder="请输入楼号" style="width: 50%" />
                </el-form-item> -->
        <el-form-item label="楼宇/区域" prop="buildingArea">
          <el-input v-model="formValue.buildingArea" size="large" placeholder="请输入楼宇/区域" style="width: 50%" />
        </el-form-item>
        <el-form-item label="楼层/房号" prop="floorRoomNo">
          <el-input v-model="formValue.floorRoomNo" size="large" placeholder="请输入楼层/房号" style="width: 50%" />
        </el-form-item>
        <el-form-item label="名称/功能" prop="nameFunction">
          <el-input v-model="formValue.nameFunction" size="large" placeholder="请输入名称/功能" style="width: 50%" />
        </el-form-item>

        <el-form-item label="安全责任所/中心" prop="safetyResponsibleCenter">
          <el-cascader
            v-model="formValue.safetyResponsibleCenterId"
            style="width: 50%"
            size="large"
            :ref="(el) => (cascaderRef['safetyResponsibleCenter'] = el)"
            :options="firstLevelDepts"
            :props="cascaderProp"
            :show-all-levels="false"
            placeholder="请选择安全责任部门"
            clearable
            filterable
            @change="(val) => handleChangeDept(val, 'safetyResponsibleCenter')"
          />
        </el-form-item>

        <el-form-item label="安全责任所/中心负责人" prop="safetyCenterManager">
          <el-select
            v-model="formValue.safetyCenterManager"
            placeholder="请选择"
            size="large"
            style="width: 50%"
            filterable
            @change="(val) => syncUserName(safetyCenterManagerOptions, val, 'safetyCenterManagerName')"
          >
            <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="安全责任部门" prop="safetyResponsibleDepartment">
          <el-cascader
            v-model="formValue.safetyResponsibleDepartmentId"
            style="width: 50%"
            size="large"
            :ref="(el) => (cascaderRef['safetyResponsibleDepartment'] = el)"
            :options="firstLevelDepts"
            :props="cascaderProp"
            :show-all-levels="false"
            placeholder="请选择安全责任部门"
            clearable
            filterable
            @change="(val) => handleChangeDept(val, 'safetyResponsibleDepartment')"
          />
        </el-form-item>

        <el-form-item label="安全责任部门负责人" prop="safetyDepartmentManager">
          <el-select
            v-model="formValue.safetyDepartmentManager"
            placeholder="请选择"
            size="large"
            style="width: 50%"
            filterable
            @change="(val) => syncUserName(userOptions, val, 'safetyDepartmentManagerName')"
          >
            <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="安全具体责任人" prop="safetySpecificPerson">
          <el-select
            v-model="formValue.safetySpecificPerson"
            placeholder="请选择"
            size="large"
            style="width: 50%"
            filterable
            @change="(val) => syncUserName(userOptions, val, 'safetySpecificPersonName')"
          >
            <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="安全具体责任人联系方式" prop="safetyPersonContact">
          <el-input
            v-model="formValue.safetyPersonContact"
            size="large"
            placeholder="选择责任人后自动填充"
            style="width: 50%"
          />
        </el-form-item>
      </el-form>
    </main>
    <footer class="safety-platform-container__footer">
      <el-button @click="$router.push({ name: 'listResponsibilities:public' })">返回</el-button>
      <el-button type="primary" :loading="submiting" @click="handleSubmit">提交</el-button>
    </footer>
  </div>
</template>

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

  const router = useRouter();
  const route = useRoute();
  const formRef = ref<any>(null);
  const submiting = ref(false);

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

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

  const rules = reactive({
    // buildingNo: [{ required: true, message: '请输入楼号' }],
    buildingArea: [{ required: true, message: '请输入楼宇/区域' }],
    floorRoomNo: [{ required: true, message: '请输入楼层/房号' }],
    nameFunction: [{ required: true, message: '请输入名称/功能' }],
    safetyResponsibleCenter: [{ required: true, message: '请选择安全责任所/中心', trigger: 'change' }],
    safetyCenterManager: [{ required: true, message: '请选择负责人', trigger: 'change' }],
    safetyResponsibleDepartment: [{ required: true, message: '请选择安全责任部门', trigger: 'change' }],
    safetyDepartmentManager: [{ required: true, message: '请选择负责人', trigger: 'change' }],
    safetySpecificPerson: [{ required: true, message: '请选择安全具体责任人', trigger: 'change' }],
    safetyPersonContact: [
      { required: true, message: '请输入联系方式' },
      { pattern: /^1[3-9]\d{9}$/, message: '格式不正确' },
    ],
  });

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

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

  const handleChangeDept = (val, prop) => {
    const cascader = cascaderRef.value?.[prop];
    const deptInfo = cascader?.getCheckedNodes();
    if (deptInfo?.length) {
      formValue[prop] = deptInfo[0]?.label;
      handleQueryAvailableUserList(deptInfo[0]?.label, prop);
    }
  };

  const handleQueryAvailableUserList = (value, prop) => {
    if (prop === 'safetyResponsibleCenter') {
      formValue.safetyCenterManager = null;
      getUserData(safetyCenterManagerOptions, value);
    } else {
      formValue.safetySpecificPerson = null;
      formValue.safetyDepartmentManager = null;
      getUserData(userOptions, value);
    }
  };

  const syncUserName = (optionList, id, nameField) => {
    const user = optionList.find((u) => u.value === id);
    if (user) {
      formValue[nameField] = user.label;
      if (nameField === 'safetySpecificPersonName') formValue.safetyPersonContact = user.mobile;
    }
  };

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

    try {
      const res: any = await areaCheckListQueryDetail({ id });
      if (res) {
        // 1. 基础赋值
        Object.assign(formValue, res);

        // 2. 解析 JSON 字符串格式的 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);
        }

        // 3. ID 类型纠正 (String to Number)
        formValue.safetyCenterManager = res.safetyCenterManager ? Number(res.safetyCenterManager) : null;
        formValue.safetyDepartmentManager = res.safetyDepartmentManager ? Number(res.safetyDepartmentManager) : null;
        formValue.safetySpecificPerson = res.safetySpecificPerson ? Number(res.safetySpecificPerson) : null;

        // 4. 立即同步加载人员列表，防止页面初次显示 ID 数字
        if (formValue.safetyResponsibleCenter) {
          getUserData(safetyCenterManagerOptions, formValue.safetyResponsibleCenter);
        }
        if (formValue.safetyResponsibleDepartment) {
          getUserData(userOptions, formValue.safetyResponsibleDepartment);
        }
      }
    } catch (err) {
      ElMessage.error('详情获取失败');
    }
  };

  onMounted(() => {
    getDeptData();
    handlAreaCheckListQueryDetail();
  });

  const handleSubmit = () => {
    formRef.value?.validate((valid) => {
      if (valid) {
        submiting.value = true;
        // 提交时后端通常接受字符串形式，如果后端要数组，则直接传 formValue
        areaCheckListUpdateArea({ ...formValue, type: 1 })
          .then(() => {
            ElMessage.success('编辑成功!');
            router.push({ name: 'listResponsibilities:public' });
          })
          .finally(() => (submiting.value = false));
      }
    });
  };
</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 *;

  .editor-container {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    margin-right: 20px;
    overflow: hidden;

    // :deep(.w-e-text-container) {
    //   min-height: 400px;
    //   overflow-y: auto;
    // }
  }

  // :deep(.breadcrumb .title) {
  //   margin-left: 0;
  // }

  // .main {
  //   display: flex;
  //   flex-direction: column;
  //   padding: 20px;
  //   flex: 1;
  //   overflow: hidden;
  //   background-color: #fff;
  // }
  // .button-content {
  //   margin-bottom: 20px;
  // }

  // .page-content {
  //   display: flex;
  //   justify-content: flex-end;
  // }
  // // :deep(.el-form) {
  // //   flex: 1;
  // //   overflow: hidden;
  // //   overflow-y: auto;
  // // }
</style>
