<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"
            clearable
          />
        </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 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>

        <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,
    safetyResponsibleDepartment: '',
    safetyResponsibleDepartmentId: [],
    safetyDepartmentManager: null as number | null,
    safetySpecificPerson: null as number | null,
    safetyPersonContact: '',
    // 变更数据
    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('加载详情失败');
  //     }
  //   };
  const safetyCenterManagerOptions = ref<any[]>([]);
  const userOptions = ref<any[]>([]);
  const handlAreaCheckListQueryDetail = async () => {
    const id = route.query.id;
    if (!id) return;

    try {
      const res: any = await areaCheckListQueryDetail({ id });
      if (res) {
        Object.assign(formValue, res);
        formValue.changeReason = ''; // 确保变更原因初始为空
        formValue.safetySpecificPersonTodo = null; // 确保变更具体
        formValue.safetyResponsibleDepartmentIdTodo = []; // 确保变更部门初始为空
        // 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();
    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>
