<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="请选择安全责任部门"
            filterable
            clearable
            @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-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-cascader
            v-model="formValue.safetyResponsibleDepartmentId"
            style="width: 50%"
            size="large"
            :ref="(el) => (cascaderRef['safetyResponsibleDepartment'] = el)"
            :options="firstLevelDepts"
            :props="cascaderProp"
            :show-all-levels="false"
            placeholder="请选择安全责任部门"
            filterable
            clearable
            @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: '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, nextTick } 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 { areaCheckListSavaArea, queryAvailableUserList } 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 cascaderProp = {
    expandTrigger: 'click',
    checkStrictly: true,
    // emitPath: false,
    value: 'id',
    label: 'deptName',
  };

  const cascaderRef = ref({});

  const safetyCenterManagerOptions = ref<any[]>([]);

  const formValue = reactive({
    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 handleChangeDept = (val, prop) => {
    const cascader = cascaderRef.value?.[prop];
    const deptInfo = cascader?.getCheckedNodes();
    formValue[prop] = deptInfo[0]?.label;
    formRef.value.validateField(prop);
    nextTick(() => {
      handleQueryAvailableUserList(deptInfo[0]?.label, prop);
    });
  };

  const handleQueryAvailableUserList = (value, prop) => {
    switch (prop) {
      case 'safetyResponsibleCenter':
        formValue.safetyCenterManager = null;
        getUserData(safetyCenterManagerOptions, value);
        break;
      case 'safetyResponsibleDepartment':
        formValue.safetySpecificPerson = null;
        formValue.safetyDepartmentManager = null;
        getUserData(userOptions, value);
        break;
      default:
        break;
    }
  };

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

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

  // 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 = () => {
    console.log(formValue);
    formRef.value?.validate((valid: boolean) => {
      if (valid) {
        submiting.value = true;
        areaCheckListSavaArea({
          ...formValue,
          type: 1,
          safetyResponsibleDepartmentId: JSON.stringify(formValue.safetyResponsibleDepartmentId),
          safetyResponsibleCenterId: JSON.stringify(formValue.safetyResponsibleCenterId),
        })
          .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(.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>
