<template>
    <div class="user-select-component">
        <el-input v-model:value="displayValue" :class="{ selected: isSelected }" placeholder="请选择用户" />

        <!-- 用户选择弹窗 -->
        <el-dialog v-model="isModalVisible" title="选择用户" width="800px" @close="handleModalClose">
            <div class="user-select-container">
                <!-- 部门树（带复选框） -->
                <div class="dept-tree">
                    <el-input
                        v-model="searchQuery"
                        placeholder="输入关键字按enter键查询"
                        class="search-input"
                        @keyup.enter="handleSearch"
                    >
                        <template #append>
                            <el-button @click="handleSearch">
                                <el-icon><Search /></el-icon>
                            </el-button>
                        </template>
                    </el-input>
                    <el-tree
                        ref="deptTree"
                        :data="deptData"
                        :props="deptProps"
                        :default-expanded-keys="defaultExpandedKeys"
                        :default-checked-keys="selectedUserIds"
                        show-checkbox
                        node-key="id"
                        @check="handleDeptCheck"
                        class="tree"
                    >
                        <template #default="{ node }">
                            <span class="custom-tree-node">
                                <el-icon v-if="node.children && node.children.length">
                                    <Fold v-if="node.expanded" />
                                    <Expand v-else />
                                </el-icon>
                                {{ node.label }}
                            </span>
                        </template>
                    </el-tree>
                </div>

                <!-- 已选用户列表 -->
                <div class="user-transfer">
                    <div
                        style="display: flex; align-items: center; justify-content: space-between; padding: 8px 0"
                        v-for="item in userData"
                        :key="item.id"
                    >
                        <div>{{ item.label }}</div>
                    </div>
                </div>
            </div>

            <template #footer>
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="handleConfirm">确认</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from "vue";
import { inject } from "vue";
import { Designer } from "epic-designer";
import $Bus from "@/utils/mittBus";
import { ElMessage } from "element-plus";
import { Search, Fold, Expand } from "@element-plus/icons-vue";
// import { useMsg } from "@/hooks/useMsg";

// 接收props
const props = defineProps({
    componentSchema: {
        type: Object,
        default: () => ({
            placeholder: "请选择用户",
            value: null,
            disabled: false,
            componentProps: {}
        })
    },
    modelValue: {
        type: String,
        default: null
    }
});

// 事件发射（补充v-model更新事件）
const emit = defineEmits(["update:modelValue"]);

// 状态管理
const isModalVisible = ref(false);
const selectedUser = ref(props.modelValue || props.componentSchema.value || null);
const isSelected = ref(false);
const defaultExpandedKeys = ref<number[]>([]); // 用于默认展开部门节点

// 设计器实例
const designer = inject("designer") as Designer;

// 部门数据
const deptData = ref([
    {
        id: 1,
        label: "销售部",
        type: "dept", // 明确标记为部门
        children: [{ id: 11, label: "錢二", type: "user" }]
    },
    {
        id: 2,
        label: "市场部",
        type: "dept",
        children: [{ id: 21, label: "姚彤", type: "user" }]
    },
    {
        id: 3,
        label: "开发部",
        type: "dept",
        children: [{ id: 22, label: "張三", type: "user" }]
    },
    {
        id: 4,
        label: "运维部",
        type: "dept",
        children: [{ id: 23, label: "王五", type: "user" }]
    },
    {
        id: 5,
        label: "财务部",
        type: "dept",
        children: [{ id: 24, label: "李五四", type: "user" }]
    },
    {
        id: 6,
        label: "IT部",
        type: "dept",
        children: [{ id: 25, label: "李五四", type: "user" }]
    },
    {
        id: 14,
        label: "IT部1",
        type: "dept",
        children: [{ id: 215, label: "李五四1", type: "user" }]
    },
    {
        id: 13,
        label: "IT部2",
        type: "dept",
        children: [{ id: 251, label: "李五四1", type: "user" }]
    },
    {
        id: 12,
        label: "IT部3",
        type: "dept",
        children: [{ id: 125, label: "李五四1", type: "user" }]
    }
]);

// 部门树配置
const deptProps = {
    children: "children",
    label: "label"
};

// 搜索查询
const searchQuery = ref("");
const deptTree = ref<any>(null);

// 处理搜索
const handleSearch = () => {
    deptTree.value?.filter(searchQuery.value);
};

// 关闭弹窗回调（清空临时数据）
const handleModalClose = () => {
    userData.value = [];
    selectedUserIds.value = [];
};

// 部门树复选事件（核心修改）
const handleDeptCheck = (data: any, checked: any) => {
    userData.value = checked.checkedNodes.filter((item: any) => {
        return item.type === "user";
    });
    userData.value.forEach((item: any) => {
        selectedUserIds.value.push(item.id);
    });
};

// 用户数据和选中ID
const userData = ref<any[]>([]);
const selectedUserIds = ref<number[]>([]);

// 确认选择
const handleConfirm = () => {
    if (selectedUserIds.value.length === 0) {
        ElMessage.warning("请选择至少一个用户");
        return;
    }

    // 处理选中的用户
    const selectedUsers = userData.value;
    // 拼接用户名
    const userNames = selectedUsers.map((item: any) => item.label).join(",");
    selectedUser.value = userNames;

    // 更新设计器数据（双向同步）
    if (designer?.state?.selectedNode) {
        designer.state.selectedNode.componentProps.defaultValue = userNames;
        designer.state.selectedNode.componentProps.defaultValueClone = selectedUsers;
    }
    // 触发v-model更新（确保表单能获取到值）
    emit("update:modelValue", userNames);

    isModalVisible.value = false;
    // 清空临时数据，避免下次打开残留
    userData.value = [];
    selectedUserIds.value = [];
};

// 关闭弹窗
const handleClose = () => {
    isModalVisible.value = false;
    userData.value = [];
    selectedUserIds.value = [];
};

// 显示在输入框的文本
const displayValue = computed(() => {
    return selectedUser.value || "";
});

// 监听设计器选中状态变化
watch(
    () => designer?.state.selectedNode?.field,
    newField => {
        isSelected.value = newField === props.componentSchema.field;
    },
    { immediate: true }
);

// 监听modelValue变化（外部更新时同步）
watch(
    () => props.modelValue,
    newValue => {
        selectedUser.value = newValue;
    },
    { immediate: true }
);

// 监听按钮触发的全局事件
const handleGlobalTrigger = () => {
    if (isSelected.value && !props.componentSchema.disabled) {
        isModalVisible.value = true;
        // 初始化已选数据（从设计器中读取）
        const savedUsers = designer?.state?.selectedNode?.componentProps?.defaultValueClone || [];
        if (savedUsers.length) {
            userData.value = savedUsers;
            selectedUserIds.value = savedUsers.map((item: any) => item.id);
            // 默认展开包含已选用户的部门（优化体验）
            const deptIds = deptData.value.map(dept => dept.id);
            defaultExpandedKeys.value = deptIds;
        }
    }
};

// 事件监听
onMounted(() => {
    $Bus.on("trigger-user-select-modal", handleGlobalTrigger);
});

// 清理事件监听
onUnmounted(() => {
    $Bus.off("trigger-user-select-modal", handleGlobalTrigger);
});
</script>

<style scoped lang="scss">
.user-select-component {
    width: 100%;
}

/* ::v-deep .el-input__inner {
    cursor: pointer;
} */

/* 选中状态样式 */
.selected {
    /* .el-input__inner {
        border-color: #409eff;
        box-shadow: 0 0 0 2px rgb(64 158 255 / 20%);
    } */
}

/* 弹窗样式 */
.user-select-container {
    display: flex;
    height: 400px;
    padding: 10px;
    margin-top: 20px;
    border: 1px solid #eeeeee;
}
.dept-tree {
    width: 300px;
    padding-right: 20px;
    overflow-y: auto;
    border-right: 1px solid #eeeeeeee;
}
.search-input {
    margin-bottom: 10px;
}
.user-transfer {
    flex: 1;
    padding-left: 20px;
    overflow-y: auto; /* 增加滚动，避免用户过多溢出 */
}
</style>
