<template>
    <div class="user-select-component">
        <el-input
            v-model:value="displayValue"
            placeholder="请选择组织"
            :disabled="componentSchema?.disabled"
            readonly
            :class="{ selected: isSelected }"
        />

        <!-- 用户选择弹窗 -->
        <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="selectedDeptIds"
                        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 selectDeptData"
                        :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 selectedDept = ref<any>(null);
const isSelected = ref(false);
const defaultExpandedKeys = ref<number[]>([]); // 用于默认展开部门节点

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

// 部门数据
const deptData = ref([
    {
        id: 1,
        label: "销售部",
        type: "deptP", // 明确标记为部门
        children: [
            { id: 2151111, label: "销售部1组", type: "dept" },
            { id: 2141111, label: "销售部2组", type: "dept" },
            { id: 2131111, label: "销售部3组", type: "dept" },
            { id: 2121111, label: "销售部4组", type: "dept" },
            { id: 2111111, label: "销售部5组", type: "dept" }
        ]
    },
    {
        id: 2,
        label: "市场部",
        type: "deptP",
        children: [
            { id: 2151111, label: "市场部1组", type: "dept" },
            { id: 2141111, label: "市场部2组", type: "dept" },
            { id: 2131111, label: "市场部3组", type: "dept" },
            { id: 2121111, label: "市场部4组", type: "dept" },
            { id: 2111111, label: "市场部5组", type: "dept" }
        ]
    },
    {
        id: 3,
        label: "开发部",
        type: "deptP",
        children: [
            { id: 215111, label: "开发部1组", type: "dept" },
            { id: 214111, label: "开发部2组", type: "dept" },
            { id: 213111, label: "开发部3组", type: "dept" },
            { id: 212111, label: "开发部4组", type: "dept" },
            { id: 211111, label: "开发部5组", type: "dept" }
        ]
    },
    {
        id: 4,
        label: "运维部",
        type: "deptP",
        children: [
            { id: 21511, label: "运维部1组", type: "dept" },
            { id: 21411, label: "运维部2组", type: "dept" },
            { id: 21311, label: "运维部3组", type: "dept" },
            { id: 21211, label: "运维部4组", type: "dept" },
            { id: 21111, label: "运维部5组", type: "dept" }
        ]
    },
    {
        id: 5,
        label: "财务部",
        type: "deptP",
        children: [
            { id: 2151, label: "财务部1组", type: "dept" },
            { id: 2141, label: "财务部2组", type: "dept" },
            { id: 2131, label: "财务部3组", type: "dept" },
            { id: 2121, label: "财务部4组", type: "dept" },
            { id: 2111, label: "财务部5组", type: "dept" }
        ]
    },

    {
        id: 14,
        label: "IT部",
        type: "deptP",
        children: [
            { id: 215, label: "IT部1组", type: "dept" },
            { id: 214, label: "IT部2组", type: "dept" },
            { id: 213, label: "IT部3组", type: "dept" },
            { id: 212, label: "IT部4组", type: "dept" },
            { id: 211, label: "IT部5组", type: "dept" }
        ]
    }
]);

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

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

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

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

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

//选择的部门
const selectDeptData = ref<any[]>([]);
const selectedDeptIds = ref<number[]>([]);

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

    // 处理选择的组织
    const selectedDepts: any = selectDeptData.value;
    // 拼接用户名
    const deptNames: any = selectedDepts.map((item: any) => item.label).join(",");
    selectedDept.value = deptNames;

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

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

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

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

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

// 监听modelValue变化（外部更新时同步）
watch(
    () => props.modelValue,
    newValue => {
        selectedDept.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) {
            selectDeptData.value = savedUsers;
            selectedDeptIds.value = savedUsers.map((item: any) => item.id);
            // 默认展开包含已选用户的部门（优化体验）
            const deptIds = selectDeptData.value.map((dept: any) => dept.id);
            defaultExpandedKeys.value = deptIds;
        }
    }
};

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

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

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

// .el-input__inner {
//     cursor: pointer;
// }

/* 选中状态样式 */
.selected {
    // .el-input__inner {
    //     border-color: red;
    //     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>
