<template>
  <el-drawer
    v-model="isDrawer"
    size="480"
    :title="props.type === 'add' ? '添加车辆信息记录' : '编辑车辆信息记录'"
    @close="handleCloseDrawer"
  >
    <el-form ref="formRef" :model="formParams" :rules="rules" label-placement="left" :label-width="80">
      <el-form-item label="车牌号" prop="carNum">
        <el-input placeholder="请输入车牌号" v-model="formParams.carNum" />
      </el-form-item>
      <el-form-item label="工号" prop="staffNo">
        <el-tree-select
          v-model="formParams.staffNo"
          placeholder="请输入工号进行搜索"
          class="protocal-select"
          filterable
          remote
          clearable
          :loading="loading"
          :data="staffNoOptions"
          :render-after-expand="false"
          :default-expand-all="true"
          :remote-method="debouncedRemoteMethod"
          @clear="handleClearStaffNo"
          @change="handleChangeStaffNo"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="userName">
        <el-input placeholder="请选择工号，此项自动填充" v-model="formParams.userName" disabled />
      </el-form-item>
      <el-form-item label="所属部门" prop="deptName">
        <el-input placeholder="请选择工号，此项自动填充" v-model="formParams.deptName" disabled />
      </el-form-item>
      <el-form-item label="联系方式" prop="phoneNum">
        <el-input
          :placeholder="formParams.staffNo ? '请输入联系方式' : '请选择工号，此项自动填充'"
          v-model="formParams.phoneNum"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-space>
        <el-button @click="handleCloseDrawer">取消</el-button>
        <el-button type="primary" @click="handleSubmitForm(formRef)">提交</el-button>
      </el-space>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
  import { debounce } from 'lodash-es';
  import { queryOrganizationUserTree } from '@/api/system/user';
  import { OrganizationUserTree } from '@/views/system/user/types';
  import {
    findUserByWorkNo,
    transformTreeData,
    TransformedTreeNode,
    findOrgCodeByWorkNo,
  } from '@/utils/findUserByWorkNo';
  import { VehicleInfoStruct, addVehicleInfo, updateVehicleInfo } from '@/api/traffic-vehicle';

  const props = defineProps<{
    type: string; // add or edit
    initialData: VehicleInfoStruct;
  }>();

  const emits = defineEmits<{
    (e: 'close'): void;
  }>();

  const formRef = ref<FormInstance>();
  const formParams = ref<VehicleInfoStruct>({
    id: 0,
    carNum: '',
    userId: 0,
    userName: '',
    staffNo: '',
    deptId: 0,
    deptName: '',
    phoneNum: '',
    createdAt: '',
    updatedAt: '',
    isDeleted: 0,
  });

  const rules = reactive<FormRules<VehicleInfoStruct>>({
    carNum: [
      { required: true, message: '车牌号不能为空', trigger: 'blur' },
      { min: 1, max: 8, message: '车牌号格式错误', trigger: 'blur' },
    ],
    staffNo: {
      required: true,
      message: '工号不能为空',
      trigger: 'blur',
    },
    userName: {
      required: true,
      message: '姓名不能为空',
      trigger: 'blur',
    },
    deptName: {
      required: true,
      message: '所属部门不能为空',
      trigger: 'blur',
    },
    phoneNum: [
      { required: true, message: '联系方式不能为空', trigger: 'blur' },
      {
        pattern: /^1\d{10}$/,
        message: '联系方式非11位数字',
        trigger: 'blur',
      },
    ],
  });

  const isDrawer = ref(true);
  const loading = ref(false);
  const staffNoOptions = ref<TransformedTreeNode[]>([]); // 工号选择列表
  const OrganizationSourceData = ref<OrganizationUserTree[]>([]); // 组织结构树原始数据
  const departmentArr = ref<{ value: string | number; label: string }[]>([]);

  // 通过工号查询组织结构树
  const remoteMethod = (query: string) => {
    if (query) {
      loading.value = true;
      queryOrganizationUserTree(Number(query)).then((res) => {
        if (res) {
          loading.value = false;
          staffNoOptions.value = transformTreeData(res, true);
          OrganizationSourceData.value = res;
          departmentArr.value = transformTreeData(OrganizationSourceData.value, false);
        }
      });
    } else {
      staffNoOptions.value = [];
    }
  };

  // 防抖
  const debouncedRemoteMethod = debounce(remoteMethod, 1000);

  const handleClearStaffNo = () => {
    formParams.value.staffNo = '';
    formParams.value.userName = '';
    formParams.value.deptName = '';
    formParams.value.phoneNum = '';
  };

  // 递归查找树结构中的节点
  const findNodeInTree = (tree: any[], value: string | number): any => {
    for (const node of tree) {
      // 检查当前节点
      if (node.value === value) {
        return node;
      }
      // 检查子节点（如果有）
      if (node.children && node.children.length > 0) {
        const foundNode = findNodeInTree(node.children, value);
        if (foundNode) {
          return foundNode;
        }
      }
    }
    return null;
  };

  const handleChangeStaffNo = (value) => {
    const findUser = findUserByWorkNo(OrganizationSourceData.value, value);
    const deptId = Number(findOrgCodeByWorkNo(OrganizationSourceData.value, value));
    const dept = findNodeInTree(departmentArr.value, deptId);
    if (findUser) {
      formParams.value.userId = findUser.id;
      formParams.value.userName = findUser.appAccountAccountName;
      formParams.value.staffNo = findUser.idtUserWorkNo;
      formParams.value.deptId = deptId;
      formParams.value.deptName = dept.label;
      formParams.value.phoneNum = findUser.idtUserMobile;
    }
  };

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

  const handleSubmitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid) => {
      if (!valid) return;
      const addParams = {
        carNum: formParams.value.carNum,
        userId: formParams.value.userId,
        userName: formParams.value.userName,
        staffNo: formParams.value.staffNo,
        deptId: formParams.value.deptId,
        deptName: formParams.value.deptName,
        phoneNum: formParams.value.phoneNum,
      };
      if (props.type === 'add') {
        addVehicleInfo(addParams).then(() => {
          ElMessage.success('添加成功');
          handleCloseDrawer();
        });
      } else {
        updateVehicleInfo(formParams.value).then(() => {
          ElMessage.success('编辑成功');
          handleCloseDrawer();
        });
      }
    });
  };

  watch(
    () => props.initialData,
    (newData) => {
      if (newData) formParams.value = { ...newData };
    },
    { immediate: true, deep: true },
  );
</script>

<style lang="scss" scoped>
  .protocal-select:deep(.el-select-dropdown__wrap) {
    max-height: 600px;
  }
</style>
