<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-select
            v-model="formValue.safetyResponsibleCenter"
            placeholder="请选择"
            size="large"
            style="width: 50%"
            filterable
          >
            <el-option
              v-for="item in firstLevelDepts"
              :key="item.hrIdtOrgId"
              :label="item.deptName"
              :value="item.deptName"
            />
          </el-select>
        </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(val, 'safetyCenterManagerName')"
          >
            <el-option v-for="item in userOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="安全责任部门" prop="safetyResponsibleDepartment">
          <el-select
            v-model="formValue.safetyResponsibleDepartment"
            placeholder="请选择"
            size="large"
            style="width: 50%"
            filterable
          >
            <el-option
              v-for="item in firstLevelDepts"
              :key="item.hrIdtOrgId"
              :label="item.deptName"
              :value="item.deptName"
            />
          </el-select>
        </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(val, 'safetyDepartmentManagerName')"
          >
            <el-option v-for="item in userOptions" :key="item.id" :label="item.name" :value="item.id" />
          </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="handleSpecificPersonChange"
          >
            <el-option v-for="item in userOptions" :key="item.id" :label="item.name" :value="item.id" />
          </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: 'areaResponsibilities:public' })">返回</el-button>
      <el-button type="primary" :loading="submiting" @click="handleSubmit">提交</el-button>
    </footer>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, onMounted } from 'vue';
  import { useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import { getAllDepartments } from '@/api/auth/dept';
  import { formatDeptTree } from '@/views/disaster/utils/formatDeptTree';
  import { getUserList } from '@/api/system/user-operate';

  import {
    queryUserPageByUsername,
    areaCheckListSavaArea,
  } from '@/api/production-safety/responsibility-implementation';

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

  const userOptions = ref<any[]>([]);
  const firstLevelDepts = ref<any[]>([]);

  const formValue = reactive({
    buildingNo: '',
    buildingArea: '',
    floorRoomNo: '',
    nameFunction: '',
    safetyResponsibleCenter: '',
    safetyCenterManager: null as number | null,
    safetyCenterManagerName: '',
    safetyResponsibleDepartment: '',
    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 = () => {
    getUserList({ pageNumber: 1, pageSize: 200, queryParam: {} }).then((res: any) => {
      userOptions.value = (res.records || []).map((u: any) => ({
        id: u.userId || u.id,
        name: u.realName || u.username,
      }));
    });
  };

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

  const handleSpecificPersonChange = (id: number) => {
    const user = userOptions.value.find((u) => u.id === id);
    if (user) {
      formValue.safetySpecificPersonName = user.name;
      formValue.safetyPersonContact = user.mobile;
    }
  };

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

  const handleSubmit = () => {
    formRef.value?.validate((valid: boolean) => {
      if (valid) {
        submiting.value = true;
        areaCheckListSavaArea({
          ...formValue,
          type: 1,
        })
          .then(() => {
            ElMessage.success('创建成功!');
            router.push({ name: 'areaResponsibilities: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>
