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

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

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

        <h5 style="margin: 30px 0; font-weight: bold; color: #409eff">信息变更</h5>

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

        <el-form-item label="变更后的安全具体责任人" prop="safetySpecificPersonTodo">
          <el-select
            :disabled="!todoUserOptions.length"
            v-model="formValue.safetySpecificPersonTodo"
            placeholder="请选择新的具体责任人"
            size="large"
            style="width: 50%"
            filterable
            clearable
            @change="(val) => syncUserName(todoUserOptions, val, 'safetySpecificPersonNameTodo')"
          >
            <el-option v-for="item in todoUserOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="变更原因" prop="changeReason">
          <el-input
            v-model="formValue.changeReason"
            type="textarea"
            :rows="5"
            placeholder="请详细描述变更原因"
            style="width: 70%"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
    </main>

    <footer class="safety-platform-container__footer">
      <el-button @click="$router.push({ name: 'listResponsibilities:nonPublic' })">返回</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,
    areaCheckListChange,
    queryAvailableUserList,
  } from '@/api/production-safety/responsibility-implementation';

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

  // 数据源
  const firstLevelDepts = ref<any[]>([]);
  const oldCenterManagerOptions = ref<any[]>([]); // 旧负责人数据源
  const todoUserOptions = 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,
    // 变更数据
    safetyResponsibleDepartmentTodo: '',
    safetyResponsibleDepartmentIdTodo: [],
    safetySpecificPersonTodo: null as number | null,
    safetySpecificPersonNameTodo: '',
    changeReason: '',
  });

  const rules = reactive({
    safetyResponsibleDepartmentTodo: [{ required: true, message: '请选择变更后的责任部门', trigger: 'change' }],
    safetySpecificPersonTodo: [{ required: true, message: '请选择变更后的具体责任人', trigger: 'change' }],
    changeReason: [{ required: true, message: '请输入变更原因', trigger: 'blur' }],
  });

  // 获取部门树
  const getDeptData = async () => {
    const res = await getAllDepartments();
    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,
      }));
    });
  };

  // 级联选择处理
  const handleChangeDept = (val, prop) => {
    const cascader = cascaderRef.value?.[prop];
    const deptInfo = cascader?.getCheckedNodes();
    if (deptInfo?.length) {
      formValue[prop] = deptInfo[0].label;
      // 级联变更后清空已选人员并重新加载
      formValue.safetySpecificPersonTodo = null;
      getUserData(todoUserOptions, deptInfo[0].label);
    }
  };

  const syncUserName = (optionList, id: number, nameField: string) => {
    const user = optionList.find((u) => u.value === id);
    if (user) formValue[nameField] = user.label;
  };

  // 详情回显
  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. 解析旧部门级联路径
        if (typeof res.safetyResponsibleCenterId === 'string') {
          formValue.safetyResponsibleCenterId = JSON.parse(res.safetyResponsibleCenterId);
        }

        // 2. 加载旧负责人列表以显示名称
        if (formValue.safetyResponsibleCenter) {
          getUserData(oldCenterManagerOptions, formValue.safetyResponsibleCenter);
        }

        // 3. 纠正 ID 类型
        if (formValue.safetyCenterManager) formValue.safetyCenterManager = Number(formValue.safetyCenterManager);
      }
    } catch (err) {
      ElMessage.error('加载详情失败');
    }
  };

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

  const handleSubmit = () => {
    formRef.value?.validate((valid: boolean) => {
      if (valid) {
        submiting.value = true;
        const submitData = {
          id: Number(route.query.id),
          safetyResponsibleDepartmentTodo: formValue.safetyResponsibleDepartmentTodo,
          safetyResponsibleDepartmentIdTodo: JSON.stringify(formValue.safetyResponsibleDepartmentIdTodo), // 根据接口需求决定是否 stringify
          safetySpecificPersonTodo: formValue.safetySpecificPersonTodo,
          safetySpecificPersonNameTodo: formValue.safetySpecificPersonNameTodo,
          changeReason: formValue.changeReason,
        };

        areaCheckListChange(submitData)
          .then(() => {
            ElMessage.success('变更申请提交成功!');
            router.push({ name: 'listResponsibilities:nonPublic' });
          })
          .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 *;
</style>
