<template>
  <div class="common-dialog">
    <div class="common-dialog-content">
      <div class="common-dialog-title-box">
        <h3 class="common-dialog-title">新建巡查人员</h3>
      </div>
      <div class="common-dialog-box">
        <el-form ref="form" :model="formData" :rules="rules" label-width="120px">
          <el-form-item label="姓名：" prop="nick_name">
            <el-tree-select
              v-model="formData.uuid"
              :data="treeData"
              :props="{ label: 'label', value: 'id', children: 'children' }"
              :render-after-expand="false"
              style="width: 468px"
              @change="onUserNameChange"
            />
          </el-form-item>
          <el-form-item label="粤政易组织：" prop="ancestors_names">
            <el-input v-model="formData.ancestors_names" style="width: 468px !important" />
          </el-form-item>
          <el-form-item label="联系方式：" prop="phonenumber">
            <el-input v-model="formData.phonenumber" style="width: 468px !important" />
          </el-form-item>
          <el-form-item label="责任区划：" prop="area">
            <el-tree-select
              v-model="divisionSelectedId"
              :data="formattedDivisionData"
              :props="{ label: 'label', value: 'code', children: 'children' }"
              :render-after-expand="false"
              style="width: 468px"
              @change="onDivisionChange"
            />
          </el-form-item>
        </el-form>
        <div class="common-dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { inspectorAdd, phoneList, userList, inspectorDivision } from '@/api/inspectionWork/inspector';
import { ref, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';

const emits = defineEmits(['close']);
const props = defineProps<{
  // eventId: string | number;
}>();

const formData = ref({
  user_id: '',
  nick_name: '',
  phonenumber: '',
  uuid: ''
});

const treeData = ref([]);
const rawDivisionData = ref([]);
const formattedDivisionData = ref([]);

const divisionSelectedId = ref(null);

const closeDialog = () => {
  emits('close');
};

const router = useRouter();

// 更新表单数据
const updateFormData = (userData) => {
  formData.value = {
    ...formData.value,
    user_id: userData.rows[0].user_id,
    dept_id: userData.rows[0].dept_id,
    dept_name: userData.rows[0].dept_name,
    ancestors_names: userData.rows[0].ancestors_names,
    user_name: userData.rows[0].user_name,
    nick_name: userData.rows[0].nick_name,
    phonenumber: userData.rows[0].phonenumber || ''
  };
};
// 表单验证规则
const rules = ref({
  nick_name: [{ required: true, message: '请选择姓名', trigger: 'change' }],
  ancestors_names: [{ required: true, message: '请输入粤政易组织', trigger: 'blur' }],
  phonenumber: [{ required: true, message: '请输入联系方式', trigger: 'blur' }],
  area: [{ required: true, message: '请选择责任区划', trigger: 'change' }]
});
// 监听姓名变化，一旦发生变化就请求用户列表
const onUserNameChange = async (value) => {
  if (value) {
    const response = await userList({ userId: value });
    if (response.code === 200 && response.rows.length > 0) {
      updateFormData(response);
    } else {
      ElMessage.error(response.msg);
    }
  }
};

// 提交表单
const submitForm = async () => {
  try {
    let areaCode = '';
    // 确保在提交前有选中的区划
    if (divisionSelectedId.value) {
      const selectedDivision = findNode(formattedDivisionData.value, divisionSelectedId.value);
      if (selectedDivision) {
        areaCode = selectedDivision.code;
      } else {
        ElMessage.error('请选择责任区划。');
        return;
      }
    }
    if (!areaCode) {
      ElMessage.error('请选择责任区划。');
      return;
    }

    const response = await inspectorAdd({
      user_id: formData.value.user_id,
      area_code: areaCode
    });
    if (response.code === 200) {
      ElMessage.success('提交成功');
      closeDialog(); // 关闭对话框
      emits('refresh');
    } else {
      ElMessage.error(response.msg);
    }
  } catch (error) {
    ElMessage.error('提交失败，请检查输入信息。');
  }
};

const fetchPhoneList = async () => {
  const response = await phoneList();
  treeData.value = response.data;
};

const fetchDivisionData = async () => {
  const response = await inspectorDivision();
  if (response.code === 200) {
    rawDivisionData.value = response.data;
    formattedDivisionData.value = formatDivisionData(rawDivisionData.value);
    console.log('Formatted Division Data:', formattedDivisionData.value);
  } else {
    ElMessage.error(response.msg);
  }
};

const onDivisionChange = (value) => {
  // 确认选中的项存在
  const selectedDivision = findNode(formattedDivisionData.value, value);
  if (!selectedDivision) {
    ElMessage.warning('未找到匹配的责任区划。');
    // 将选中的值重置为 null 或空字符串，防止后续逻辑错误
    divisionSelectedId.value = null;
  } else {
    console.log('Selected Division:', selectedDivision); // 调试输出
  }
};

// 递归查找节点
const findNode = (nodes, code) => {
  for (let i = 0; i < nodes.length; i++) {
    const node = nodes[i];
    if (node.code === code) {
      return node;
    }
    if (node.children && node.children.length > 0) {
      const found = findNode(node.children, code);
      if (found) {
        return found;
      }
    }
  }
  return null;
};

// 格式化责任区划数据
const formatDivisionData = (data) => {
  return data.map((item) => ({
    id: item.id,
    label: item.label,
    code: item.code,
    children: item.children ? formatDivisionData(item.children) : []
  }));
};

onMounted(() => {
  fetchPhoneList();
  fetchDivisionData();
});
</script>

<style scoped></style>
