<template>
    <div class="person-picker">
        <el-row :gutter="20" style="padding-bottom: 30px">
            <el-col :span="16">
                <!-- Tabs 切换 -->
                <el-tabs v-model="activeTab" @tab-change="handleTabChange">
                    <el-tab-pane label="人员" name="person">
                        <template #label>
                            <span>人员</span>
                            <el-badge
                                v-if="selectedPersonCount > 0"
                                :value="selectedPersonCount"
                                class="tab-badge"
                            />
                        </template>
                    </el-tab-pane>
                    <el-tab-pane label="分组" name="group">
                        <template #label>
                            <span>分组</span>
                            <el-badge
                                v-if="selectedGroupCount > 0"
                                :value="selectedGroupCount"
                                class="tab-badge"
                            />
                        </template>
                    </el-tab-pane>
                </el-tabs>

                <!-- 搜索栏 -->
                <div class="search-bar">
                    <el-input
                        v-if="activeTab === 'person'"
                        v-model.trim="searchKeyword"
                        placeholder="输入关键字"
                        clearable
                        prefix-icon="Search"
                        @input="handleSearch"
                    />
                    <el-input
                        v-else
                        v-model.trim="groupSearchKeyword"
                        placeholder="输入关键字"
                        clearable
                        prefix-icon="Search"
                        @input="handleGroupSearch"
                    />
                </div>

                <!-- 人员表格 -->
                <el-table
                    v-if="activeTab === 'person'"
                    border
                    ref="personTableRef"
                    :data="filteredPersonList"
                    height="400"
                    @selection-change="onPersonSelectionChange"
                >
                    <el-table-column type="selection" width="50" align="center" />
                    <el-table-column
                        show-overflow-tooltip
                        prop="orgName"
                        label="人员所属"
                        align="center"
                    />
                    <el-table-column
                        show-overflow-tooltip
                        prop="workerName"
                        label="姓名"
                        width="120"
                        align="center"
                    />
                    <el-table-column show-overflow-tooltip prop="sex" label="性别" align="center">
                        <template #default="{ row }">
                            {{ row.sex == 1 ? '男' : '女' }}
                        </template>
                    </el-table-column>
                    <el-table-column
                        show-overflow-tooltip
                        prop="phone"
                        label="电话"
                        align="center"
                    />
                </el-table>

                <!-- 分组表格 -->
                <el-table
                    v-else
                    border
                    ref="groupTableRef"
                    :data="filteredGroupList"
                    height="400"
                    @selection-change="onGroupSelectionChange"
                >
                    <el-table-column type="selection" width="50" align="center" />
                    <el-table-column
                        show-overflow-tooltip
                        prop="groupName"
                        label="分组名称"
                        align="center"
                    />
                </el-table>
            </el-col>

            <!-- 右侧已选人员 -->
            <el-col :span="8">
                <div class="selected-persons">
                    <div class="selected-header">
                        <span>已选人员</span>
                        <el-button
                            type="text"
                            size="small"
                            @click="handleClearAll"
                            :disabled="allSelectedPersons.length === 0"
                        >
                            清空
                        </el-button>
                    </div>
                    <div class="selected-list">
                        <div
                            v-for="person in allSelectedPersons"
                            :key="person.id"
                            class="selected-item"
                        >
                            <span>{{ person.workerName }}</span>
                            <el-icon class="remove-icon" @click="handleRemovePerson(person.id)">
                                <Close />
                            </el-icon>
                        </div>
                        <div v-if="allSelectedPersons.length === 0" class="empty-tip">
                            暂未选择人员
                        </div>
                    </div>
                </div>
            </el-col>
        </el-row>
    </div>
</template>

<script setup name="PersonPicker">
import { ref, computed, watch, nextTick, onMounted } from 'vue'
import { Close } from '@element-plus/icons-vue'
import { getAllPersonAPI } from '@/api/personManage/person.js'
import { getAllGroupAPI } from '@/api/basicManage/groupManage.js'

const props = defineProps({
    modelValue: {
        type: Array,
        default: () => [],
    },
})

const emit = defineEmits(['update:modelValue', 'confirm'])

const activeTab = ref('person')
const searchKeyword = ref('')
const groupSearchKeyword = ref('')
const personTableRef = ref(null)
const groupTableRef = ref(null)

// 数据列表
const personList = ref([])
const groupList = ref([])

// 直接选择的人员ID列表（只在人员tab中选择的）
const directSelectedPersonIds = ref([])

// 选中的分组ID列表
const selectedGroupIds = ref([])

// 标志位：是否正在同步选中状态
const isSyncing = ref(false)

// 过滤后的人员列表
const filteredPersonList = computed(() => {
    if (!searchKeyword.value) {
        return personList.value
    }
    const keyword = searchKeyword.value.toLowerCase()
    return personList.value.filter((item) => {
        const orgName = (item.orgName || '').toLowerCase()
        const workerName = (item.workerName || '').toLowerCase()
        return orgName.includes(keyword) || workerName.includes(keyword)
    })
})

// 过滤后的分组列表
const filteredGroupList = computed(() => {
    if (!groupSearchKeyword.value) {
        return groupList.value
    }
    const keyword = groupSearchKeyword.value.toLowerCase()
    return groupList.value.filter((item) => {
        const groupName = (item.groupName || '').toLowerCase()
        return groupName.includes(keyword)
    })
})

// 选中的分组数量
const selectedGroupCount = computed(() => selectedGroupIds.value.length)

// 所有已选人员（包括直接选择的人员和从分组中选择的人员）
const allSelectedPersons = computed(() => {
    const personMap = new Map()

    // 添加直接选择的人员
    directSelectedPersonIds.value.forEach((personId) => {
        const person = personList.value.find((p) => p.id === personId)
        if (person) {
            personMap.set(person.id, {
                id: person.id,
                workerName: person.workerName,
                orgName: person.orgName,
                sex: person.sex,
                phone: person.phone,
            })
        }
    })

    // 添加从分组中选择的人员（去重）
    selectedGroupIds.value.forEach((groupId) => {
        const group = groupList.value.find((g) => g.id === groupId)
        if (group && group.workerList && Array.isArray(group.workerList)) {
            group.workerList.forEach((worker) => {
                if (worker && worker.id) {
                    // 如果已存在，不覆盖（保持直接选择的数据）
                    if (!personMap.has(worker.id)) {
                        personMap.set(worker.id, {
                            id: worker.id,
                            workerName: worker.workerName || worker.name || '',
                            orgName: worker.orgName || '',
                            sex: worker.sex,
                            phone: worker.phone || '',
                        })
                    }
                }
            })
        }
    })

    return Array.from(personMap.values())
})

// 直接选择的人员数量
const selectedPersonCount = computed(() => {
    return directSelectedPersonIds.value.length
})

// Tab切换
const handleTabChange = (tabName) => {
    searchKeyword.value = ''
    groupSearchKeyword.value = ''
    nextTick(() => {
        if (tabName === 'person') {
            syncPersonTableSelection()
        } else {
            syncGroupTableSelection()
        }
    })
}

// 搜索处理
const handleSearch = () => {
    nextTick(() => {
        syncPersonTableSelection()
    })
}

const handleGroupSearch = () => {
    nextTick(() => {
        syncGroupTableSelection()
    })
}

// 人员选择变化
const onPersonSelectionChange = (selection) => {
    if (isSyncing.value) {
        return
    }

    // 更新直接选择的人员ID列表
    directSelectedPersonIds.value = selection.map((item) => item.id)

    // 触发更新，合并所有选中的人员
    updateSelectedPersons()
}

// 更新选中的所有人（合并直接选择的人员和分组中的人员）
const updateSelectedPersons = () => {
    const personMap = new Map()

    // 添加直接选择的人员
    directSelectedPersonIds.value.forEach((personId) => {
        const person = personList.value.find((p) => p.id === personId)
        if (person) {
            personMap.set(person.id, {
                id: person.id,
                workerName: person.workerName,
                orgName: person.orgName,
                sex: person.sex,
                phone: person.phone,
            })
        }
    })

    // 添加从分组中选择的人员（去重）
    selectedGroupIds.value.forEach((groupId) => {
        const group = groupList.value.find((g) => g.id === groupId)
        if (group && group.workerList && Array.isArray(group.workerList)) {
            group.workerList.forEach((worker) => {
                if (worker && worker.id) {
                    // 如果已存在，不覆盖（保持直接选择的数据）
                    if (!personMap.has(worker.id)) {
                        personMap.set(worker.id, {
                            id: worker.id,
                            workerName: worker.workerName || worker.name || '',
                            orgName: worker.orgName || '',
                            sex: worker.sex,
                            phone: worker.phone || '',
                        })
                    }
                }
            })
        }
    })

    // 触发更新事件
    emit('update:modelValue', Array.from(personMap.values()))
}

// 分组选择变化
const onGroupSelectionChange = (selection) => {
    if (isSyncing.value) {
        return
    }

    selectedGroupIds.value = selection.map((group) => group.id)

    // 触发更新，合并所有选中的人员
    updateSelectedPersons()
}

// 同步人员表格选中状态
const syncPersonTableSelection = () => {
    if (!personTableRef.value || directSelectedPersonIds.value.length === 0) {
        if (personTableRef.value) {
            isSyncing.value = true
            personTableRef.value.clearSelection()
            nextTick(() => {
                isSyncing.value = false
            })
        }
        return
    }

    isSyncing.value = true
    const selectedIds = new Set(directSelectedPersonIds.value.map((id) => Number(id)))

    nextTick(() => {
        personTableRef.value.clearSelection()
        filteredPersonList.value.forEach((row) => {
            const rowId = Number(row.id)
            if (selectedIds.has(rowId)) {
                personTableRef.value.toggleRowSelection(row, true)
            }
        })
        nextTick(() => {
            isSyncing.value = false
        })
    })
}

// 同步分组表格选中状态
const syncGroupTableSelection = () => {
    if (!groupTableRef.value || selectedGroupIds.value.length === 0) {
        if (groupTableRef.value) {
            isSyncing.value = true
            groupTableRef.value.clearSelection()
            nextTick(() => {
                isSyncing.value = false
            })
        }
        return
    }

    isSyncing.value = true
    const selectedIds = new Set(selectedGroupIds.value.map((id) => Number(id)))

    nextTick(() => {
        groupTableRef.value.clearSelection()
        filteredGroupList.value.forEach((row) => {
            const rowId = Number(row.id)
            if (selectedIds.has(rowId)) {
                groupTableRef.value.toggleRowSelection(row, true)
            }
        })
        nextTick(() => {
            isSyncing.value = false
        })
    })
}

// 移除单个人员
const handleRemovePerson = (personId) => {
    // 检查该人员是否来自分组
    const groupsToRemove = []

    selectedGroupIds.value.forEach((groupId) => {
        const group = groupList.value.find((g) => g.id === groupId)
        if (group && group.workerList && Array.isArray(group.workerList)) {
            const hasPerson = group.workerList.some((w) => w.id === personId)
            if (hasPerson) {
                groupsToRemove.push(groupId)
            }
        }
    })

    if (groupsToRemove.length > 0) {
        // 如果人员来自分组，移除对应的分组
        selectedGroupIds.value = selectedGroupIds.value.filter((id) => !groupsToRemove.includes(id))
        updateSelectedPersons()
        nextTick(() => {
            syncGroupTableSelection()
        })
    } else {
        // 如果人员是直接选择的，从直接选择列表中移除
        directSelectedPersonIds.value = directSelectedPersonIds.value.filter(
            (id) => id !== personId,
        )
        updateSelectedPersons()
    }

    // 同步人员表格
    nextTick(() => {
        syncPersonTableSelection()
    })
}

// 清空所有选择
const handleClearAll = () => {
    isSyncing.value = true
    directSelectedPersonIds.value = []
    selectedGroupIds.value = []
    emit('update:modelValue', [])
    if (personTableRef.value) {
        personTableRef.value.clearSelection()
    }
    if (groupTableRef.value) {
        groupTableRef.value.clearSelection()
    }
    nextTick(() => {
        isSyncing.value = false
    })
}

// 获取人员列表
const getPersonList = async () => {
    try {
        const result = await getAllPersonAPI()
        if (result.code === 200 && result.rows) {
            personList.value = result.rows || []
            nextTick(() => {
                syncPersonTableSelection()
            })
        }
    } catch (error) {
        console.error('获取人员列表失败:', error)
    }
}

// 获取分组列表
const getGroupList = async () => {
    try {
        const result = await getAllGroupAPI()
        if (result.code === 200 && result.rows) {
            groupList.value = result.rows || []
            nextTick(() => {
                syncGroupTableSelection()
            })
        }
    } catch (error) {
        console.error('获取分组列表失败:', error)
    }
}

// 监听 modelValue 变化，同步表格选中状态和区分直接选择的人员
watch(
    () => props.modelValue,
    (newVal) => {
        if (!newVal || newVal.length === 0) {
            directSelectedPersonIds.value = []
            return
        }

        // 区分哪些是直接选择的人员，哪些是来自分组的
        const directSelectedIds = []
        const groupPersonIds = new Set()

        // 收集所有分组中的人员ID
        selectedGroupIds.value.forEach((groupId) => {
            const group = groupList.value.find((g) => g.id === groupId)
            if (group && group.workerList && Array.isArray(group.workerList)) {
                group.workerList.forEach((worker) => {
                    if (worker && worker.id) {
                        groupPersonIds.add(worker.id)
                    }
                })
            }
        })

        // 如果人员不在分组中，则认为是直接选择的
        newVal.forEach((person) => {
            if (person && person.id && !groupPersonIds.has(person.id)) {
                directSelectedIds.push(person.id)
            }
        })

        directSelectedPersonIds.value = directSelectedIds

        if (activeTab.value === 'person') {
            syncPersonTableSelection()
        }
    },
    { deep: true, immediate: true },
)

onMounted(() => {
    getPersonList()
    getGroupList()
})
</script>

<style lang="scss" scoped>
.person-picker {
    .search-bar {
        margin-bottom: 10px;
    }

    .selected-persons {
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        background: #fff;
        height: 100%;
        display: flex;
        flex-direction: column;

        .selected-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 15px;
            border-bottom: 1px solid #dcdfe6;
            font-weight: 500;
        }

        .selected-list {
            flex: 1;
            padding: 10px;
            overflow-y: auto;
            max-height: 400px;

            .selected-item {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 2px 10px;
                margin-bottom: 5px;
                background: #f0f9ff;
                border: 1px solid #b3d8ff;
                border-radius: 4px;
                cursor: pointer;
                transition: all 0.3s;

                &:hover {
                    background: #e1f3ff;
                    border-color: #409eff;
                }

                .remove-icon {
                    color: #909399;
                    cursor: pointer;
                    font-size: 16px;

                    &:hover {
                        color: #f56c6c;
                    }
                }
            }

            .empty-tip {
                text-align: center;
                color: #909399;
                padding: 20px;
            }
        }
    }

    :deep(.el-tabs) {
        margin-bottom: 10px;

        .el-tabs__header {
            margin-bottom: 10px;
        }

        .tab-badge {
            margin-left: 8px;
        }
    }
}
</style>

