<template>
    <div class="user-container">
        <el-card class="search">

            <el-input v-model="query.name" placeholder="请输入关键字" style="width: 200px; margin-right: 12px;"></el-input>
            <el-button type="primary" icon="Search" @click="search">查询</el-button>
            <!-- <el-button type="danger" icon="Delete" @click="selectionDelete">批量删除</el-button> -->
            <el-button type="primary" @click="handeleAddGroup" style="float: right">

                <el-icon style="margin-right: 4px;">
                    <Plus></Plus>
                </el-icon>
                新增标签
            </el-button>
        </el-card>
        <el-card class="table-card">

            <el-scrollbar>
                <div class="scrollbar-flex-content">
                    <div class="scrollbar-demo-item" v-for="(item, num) in tabGroups" :key="item">
                        <el-card>
                            <template #header>
                                <div class="card-header">
                                    <div class="card-header-title">
                                        <span>{{ item.name }}</span>

                                        <el-popover @click.stop placement="bottom" width="120px" trigger="hover"
                                            hide-after="0">
                                            <template #reference>
                                                <span class="edit-icon" @click.stop>
                                                    <el-icon>
                                                        <MoreFilled />
                                                    </el-icon>
                                                </span>
                                            </template>
                                            <template #default>
                                                <ul class="popover-list" @click.stop>
                                                    <li class="edit-icon" @click.stop="addContact(item)">
                                                        <el-icon>
                                                            <svg>
                                                                <use xlink:href="#icon-tianjiahaoyou1"></use>
                                                            </svg>
                                                        </el-icon> 添加客户
                                                    </li>
                                                    <li class="edit-icon" @click.stop="handleEdit(item)">
                                                        <el-icon>
                                                            <Edit></Edit>
                                                        </el-icon> 编辑
                                                    </li>
                                                    <li class="remove-icon" @click.stop="handleDelete(item, num)">
                                                        <el-icon>
                                                            <Delete />
                                                        </el-icon> 删除
                                                    </li>
                                                </ul>
                                            </template>

                                        </el-popover>
                                    </div>
                                    <p class="user-count" style="margin-top: 10px;"><span>客户数： {{ item.contact_list.total }}</span>
                                    </p>
                                    <p class="user-count"><span>描述： {{ item.description }}</span></p>

                                </div>
                            </template>

                            <div @v-infinite-scroll="loadScroll(item, num)" class="infinite-list"
                                style="overflow: auto">
                                <draggable v-model="item.contact_list.list" @start="startDraggable" :group="'tags'"
                                    @update="endDraggable" @choose="(e) => { changeChoose(e) }"
                                    @add="(e) => { changeAdd(e, num) }" :data-group-index="num"
                                    style="padding-bottom: 20px;">

                                    <template #item="{ element, index }">
                                        <div class="infinite-list-item">
                                            <el-image :src="element.avatar"
                                                style="width: 36px;height: 36px;"></el-image>
                                            &nbsp;&nbsp;
                                            <div class="user-info">
                                                <div class="user-name">{{ element.nickname }}</div>
                                                <div class="tag-time">打标签时间：{{ element.tag_at }}</div>
                                            </div>
                                            <el-icon class="delete-icon"
                                                @click.stop="removeMember(element, item, index)">
                                                <Delete />
                                            </el-icon>
                                        </div>

                                    </template>
                                </draggable>
                            </div>
                        </el-card>
                    </div>
                </div>
            </el-scrollbar>
        </el-card>
        <el-dialog v-model="dialogVisible" :title="dialogGroupTitle" width="600px" align-center destroy-on-close>
            <div class="dialog-box">
                <el-form :model="groupForm" :rules="groupRule" ref="groupFormRef">
                    <el-form-item label="标签名称" prop="name">
                        <el-input v-model="groupForm.name" placeholder="请输入标签名称" />
                    </el-form-item>
                    <el-form-item label="标签描述">
                        <el-input type="textarea" v-model="groupForm.description" placeholder="请输入标签描述" />
                    </el-form-item>

                </el-form>

            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="groupFormSubmit" :class="{ 'no-click': submitGrouploading }">
                        <el-icon v-if="submitGrouploading" class="mht-loading" style="margin-right: 4px;">
                            <Loading />
                        </el-icon>
                        <el-icon v-else style="margin-right: 4px;">
                            <svg class="icon" aria-hidden="true">
                                <use xlink:href="#icon-baocun"></use>
                            </svg>
                        </el-icon>
                        保 存

                    </el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog v-model="dialogUser" title="选择关联用户" width="600px" align-center destroy-on-close
            :close-on-click-modal="false">
            <div class="dialog-box" style="min-height: 200px;">
                <el-select-v2 v-model="user_ids" popper-class="costom-select" :options="robotUser" placeholder="请选择用户"
                    :props="v2props" filterable @change="changeUser" multiple>
                    <template #default="{ item }">
                        <div class="costom-select-item">
                            <el-image :src="item.avatar"></el-image>
                            <span>{{ item.nickname }}</span>
                        </div>
                    </template>
                    <template #footer v-if="UserTotal > 100">
                        <el-pagination v-model:current-page="queryUser.page" :page-size="queryUser.page_size"
                            size="small" background layout="prev, pager, next" :total="UserTotal" class="mt-4"
                            @current-change="currentChange" />
                    </template>
                </el-select-v2>

            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogUser = false">取 消</el-button>
                    <el-button type="primary" @click="submitBind" :class="{ 'no-click': submitBindloading }">
                        <el-icon v-if="submitBindloading" class="mht-loading" style="margin-right: 4px;">
                            <Loading />
                        </el-icon>
                        <el-icon v-else style="margin-right: 4px;">
                            <svg class="icon" aria-hidden="true">
                                <use xlink:href="#icon-baocun"></use>
                            </svg>
                        </el-icon>
                        保 存

                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, watch } from 'vue'
import { tagList, addTag, deleteTag, upTag, tagContacts, tagBindContact, tagUnBindContact, tagSwitchContact, getAllTagsUsers } from '@/api/tags'
import { robotList } from '@/api/robot'
import { userList } from '@/api/user'
import { ElNotification } from 'element-plus';
import { useRoute } from 'vue-router';
import robotStore from '@/store/modules/robotStore'
import draggable from 'vuedraggable'

const route = useRoute()
const userRobotStore = robotStore()

const dialogVisible = ref(false)
const query = reactive({
    name: '',
    user_id: '',
    page: 1,
    page_size: 100
})
const robot_id = ref('')
const tabGroups = ref([])
const robotCards = ref([])
// const total = ref(0)

const tableLoading = ref(false)
const getTable = async () => {
    tableLoading.value = true
    try {

        const res = await getAllTagsUsers({
            robot_id: route.query.robot_id,
            tag_group_id: route.query.tag_group_id,
            ...query
        })
        console.log(res)
        tabGroups.value = res.list
        // total.value = res.total;
        // return
        // const res = await tagList({ robot_id: route.query.robot_id, tag_group_id: route.query.tag_group_id, ...query })

        // // Create a temporary array to hold the original list
        // const tagsList = [...res.list];

        // // Use Promise.all to wait for all async operations to complete
        // const tagsWithChildren = await Promise.all(
        //     tagsList.map(async (el) => {
        //         try {
        //             const contactsRes = await tagContacts({
        //                 robot_id: route.query.robot_id,
        //                 tag_group_id: route.query.tag_group_id,
        //                 tag_id: el.id,
        //                 user_id: '',
        //                 page: 1,
        //                 page_size: 100
        //             });
        //             return {
        //                 ...el,
        //                 page: 1,
        //                 page_size: 100,
        //                 total: contactsRes.total,
        //                 children: contactsRes.list || []
        //             };
        //         } catch (error) {
        //             console.error(`Error fetching contacts for tag ${el.id}:`, error);
        //             return {
        //                 ...el,
        //                 children: []
        //             };
        //         }
        //     })
        // );

        // // Update the reactive reference with the resolved data
        // tabGroups.value = tagsWithChildren;
        // console.log(tabGroups.value)
        // total.value = res.total;
    } catch (error) {
        console.error('Error fetching tag list:', error);
        tabGroups.value = [];
        // total.value = 0;
    } finally {
        tableLoading.value = false;
    }
}

const search = () => {
    query.page = 1
    getTable()
}

const handleSizeChange = (e) => {
    query.page = 1
    query.page_size = e
    getTable()
}
const handleCurrentChange = (e) => {
    query.page = e
    getTable()
}
const loading = ref(false)






const handleDelete = async (row) => {

    ElMessageBox.confirm(
        '确认删除该标签吗?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            await deleteTag(row.id)
            ElNotification({
                type: 'success',
                message: '操作成功'
            })
            query.page = 1
            getTable()
        })
        .catch(() => {

        })
}


// 标签组操作
// 标签组表单
let tagGroup_id = ''
const dialogGroupTitle = ref('')
const handeleAddGroup = () => {
    tagGroup_id = ''
    dialogGroupTitle.value = '新增标签'
    groupForm.value.name = ''
    groupForm.value.description = ''
    dialogVisible.value = true

}
const groupForm = ref({
    name: '',
    description: ''
})
const groupRule = ref({
    name: [{ required: true, message: '请输入标签名称', trigger: 'blur' }],
})
const groupFormRef = ref()

const submitGrouploading = ref(false)
const groupFormSubmit = () => {
    groupFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                submitGrouploading.value = true
                if (tagGroup_id) {
                    await upTag({ ...groupForm.value, robot_id: Number(route.query.robot_id), tag_group_id: Number(route.query.tag_group_id) }, tagGroup_id)
                    ElNotification({
                        type: 'success',
                        message: '更新成功'
                    })
                    dialogVisible.value = false
                    submitGrouploading.value = false
                    groupForm.value.name = ''
                    groupForm.value.description = ''
                    getTable()
                } else {
                    await addTag({ ...groupForm.value, robot_id: Number(route.query.robot_id), tag_group_id: Number(route.query.tag_group_id) })
                    ElNotification({
                        type: 'success',
                        message: '新增成功'
                    })
                    dialogVisible.value = false
                    submitGrouploading.value = false
                    groupForm.value.name = ''
                    groupForm.value.description = ''
                    query.page = 1
                    getTable()
                }
            } catch (err) {

                submitGrouploading.value = false
            }
        }
    })
}

const handleEdit = (row) => {
    tagGroup_id = row.id
    dialogGroupTitle.value = '编辑标签'
    groupForm.value.name = row.name
    groupForm.value.description = row.description
    dialogVisible.value = true
}



const exhandleChange = (a, b) => {
    console.log(a, b.length)
}


const loadScroll = async (row, index) => {
    // tabGroups.value
    if (row.contact_list.total > row.contact_list.list.length) {
        row.contact_list.page++
        const res = await tagContacts({
            robot_id: route.query.robot_id,
            tag_group_id: route.query.tag_group_id,
            tag_id: row.id,
            user_id: '',
            page: row.contact_list.page,
            page_size: 100
        })
        row.contact_list.total = res.total
        row.contact_list.list = [...row.contact_list.list, ...res.list]
    }
}

const dialogUser = ref(false)
const user_ids = ref([])
const robotUser = ref([])
const queryUser = reactive({
    page: 1,
    page_size: 100,
})
const UserTotal = ref(0)
let tag_Details = {}
const v2props = ref({
    value: 'user_id',
    label: 'nickname'
})
const addContact = (row) => {
    tag_Details = row
    queryUser.page = 1
    user_ids.value = []
    robotUser.value = []
    dialogUser.value = true
    getUsers()
}
const getUsers = async () => {
    try {
        // 获取所有用户
        const res = await userList({
            robot_id: route.query.robot_id,
            page: queryUser.page,
            page_size: 100
        })

        // 获取当前标签组中所有标签已绑定的用户ID列表
        const boundUserIds = new Set()

        // 遍历所有标签组
        for (const group of tabGroups.value) {
            // 跳过当前正在添加用户的标签组
            // if (group.id === tag_Details.id) continue

            // 将该标签组下所有用户ID添加到集合中
            for (const user of group.contact_list.list) {
                boundUserIds.add(user.user_id)
            }
        }

        // 过滤掉已经绑定的用户
        const filteredUsers = res.list.filter(user => !boundUserIds.has(user.user_id))

        UserTotal.value = filteredUsers.length
        robotUser.value = filteredUsers

        console.log('可选用户数量:', filteredUsers.length)
    } catch (error) {
        console.error('获取用户列表失败:', error)
        UserTotal.value = 0
        robotUser.value = []
    }
}


const currentChange = (e) => {
    queryUser.page = e
    getUsers()
}

const submitBindloading = ref(false)

const submitBind = async () => {
    try {
        submitBindloading.value = true
        const res = await tagBindContact({
            robot_id: Number(route.query.robot_id),
            tag_group_id: Number(route.query.tag_group_id),
            tag_id: tag_Details.id,
            user_list: user_ids.value

        })
        dialogUser.value = false
        submitBindloading.value = false
        tag_Details.contact_list.page = 1
        const res2 = await tagContacts({
            robot_id: route.query.robot_id,
            tag_group_id: route.query.tag_group_id,
            tag_id: tag_Details.id,
            user_id: '',
            page: 1,
            page_size: 100
        })
        tag_Details.contact_list.total = res2.total
        tag_Details.contact_list.list = res2.list
    } catch (error) {
        submitBindloading.value = false

    }

}

const removeMember = async (e, row, index) => {
    console.log(e, row, index)
    await tagUnBindContact({
        tag_id: row.id,
        user_list: [e.user_id]
    })
    row.contact_list.list.splice(index, 1)
}

const endDraggable = (e) => {
    console.log(e)
}
const changeChoose = (e) => {
    console.log(e)
}
let draggedElement = {}
const changeAdd = (e, toGroupIndex) => {
    // 获取拖拽元素的数据
    // const draggedElement = e.item.__draggable_context.element

    // 获取源组的索引 - 从e.from的data属性中获取
    const fromGroupIndex = parseInt(e.from.getAttribute('data-group-index'))

    // 获取源组和目标组
    const fromGroup = tabGroups.value[fromGroupIndex]
    const toGroup = tabGroups.value[toGroupIndex]

    console.log('从标签组:', fromGroup, '拖动到标签组:', toGroup)
    console.log('拖动的元素:', draggedElement)
    tagSwitchContact({
        new_tag_id: toGroup.id,
        old_tag_id: fromGroup.id,
        user_list: [draggedElement.user_id]
    })
    fromGroup.contact_list.total--
    toGroup.contact_list.total++

}
const startDraggable = (e) => {
    console.log(e)
    draggedElement = e.item.__draggable_context.element
}

// 添加时间格式化函数
const formatTime = (timestamp) => {
    if (!timestamp) return '未知时间';

    const date = new Date(timestamp * 1000); // 假设时间戳是秒级的，如果是毫秒级则不需要乘1000

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}`;
}

onMounted(() => {
    getTable()

})
</script>
<style lang="scss" scoped>
.user-container {
    padding: var(--el-main-padding);
    // overflow: hidden;

    // height: 100%;
    .el-card {
        background-color: var(--el-bg-color);
    }

    .table-card {
        margin-top: 20px;
        height: calc(100vh - 193px);

        .table-card-center {
            height: calc(100vh - 232px);
        }

        .table-box {
            height: calc(100% - 60px);
        }
    }

    .pagination-box {
        overflow: hidden;
        margin-top: 25px;
        text-align: right;

        .el-pagination {
            float: right;
        }
    }

    .operations {
        font-size: 14px;
        // color: var(--el-color-primary);
        cursor: pointer;

        .el-icon {
            position: relative;
            top: 2px;
        }

        &:hover {
            color: var(--el-color-primary);
        }
    }

    .user-phone {
        color: var(--el-color-primary);
        cursor: pointer;

    }

    .send-user {
        overflow: hidden;
        line-height: 30px;

        span {
            float: left;
        }

        .el-image {
            float: left;
            width: 30px;
            height: 30px;
            border-radius: 6px;
            margin-bottom: 10px;
            margin-right: 12px;
        }

    }

}


.scrollbar-flex-content {
    display: flex;
}


.scrollbar-demo-item {
    flex-shrink: 0;
    // display: flex;
    // align-items: center;
    // justify-content: center;
    width: 300px;
    margin: 10px;
    max-height: calc(100vh - 250px);
    // text-align: center;
    // border-radius: 4px;
    // background: var(--el-color-danger-light-9);
    // color: var(--el-color-danger);

    .infinite-list {
        max-height: calc(100vh - 300px);
        padding: 15px;

        .infinite-list-item {
            font-size: 14px;
            padding: 10px;
            // border: 1px solid var(--el-border-color-light);
            box-shadow: var(--el-box-shadow-light);
            position: relative;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            margin-bottom: 10px;
            cursor: pointer;
            display: flex;
            align-items: center;

            .el-image {
                vertical-align: middle;
            }

            .user-info {
                flex: 1;
                overflow: hidden;
                margin-left: 8px;

                .user-name {
                    font-weight: 500;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                }

                .tag-time {
                    font-size: 12px;
                    color: var(--el-text-color-secondary);
                    margin-top: 6px;
                }
            }
        }
    }
}

.card-header {
    position: relative;

    .edit-icon {
        position: absolute;
        right: 0;
        cursor: pointer;
        color: var(--el-color-primary);
    }
}

.delete-icon {
    color: var(--el-color-danger);
    position: absolute;
    right: 10px;
    cursor: pointer;
    top: 50%;
    transform: translateY(-50%);
}

.sortable-chosen {
    background-color: var(--el-color-primary-light-7);
}

.user-count {
    font-size: 12px;
    color: var(--el-text-color-secondary);
    line-height: 20px;
}

.popover-list {
    li {
        height: 32px;
        line-height: 32px;
        padding-left: 10px;
        // border-radius: 6px;
        cursor: pointer;

        // color: var(--el-color-primary);
        .el-icon {
            position: relative;
            top: 2px;
            margin-right: 4px;
        }

        &:hover {
            background-color: var(--el-color-primary-light-9);
        }
    }

    .rizhi-icon {
        color: var(--el-color-warning);
    }

    .edit-icon {
        color: var(--el-color-primary);
    }

    .remove-icon {
        color: var(--el-color-danger);
    }
}
</style>

<style lang="scss">
.scrollbar-demo-item {
    .el-card__body {
        padding: 0;
    }
}
</style>