<template>
    <div class="user-container">
        <el-row :gutter="20" style="height: 100%;">
            <el-col :span="15">
                <el-card class="">
                    <div class="user-avatar-name">
                        <!-- <el-image class="user-avatar" :src="groupInfo.avatar" /> -->
                        <div class="user-name">
                            <p>群名称：{{ groupInfo.room_name }} </p>
                            <p>成员数：{{ groupInfo.members_count }}</p>
                        </div>
                    </div>
                    <div class="time">
                        <el-icon>
                            <Clock />
                        </el-icon>添加时间： {{ groupInfo.create_time }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        <el-icon>
                            <Clock />
                        </el-icon>同步时间： {{ groupInfo.sync_time }}
                    </div>
                    <el-button type="primary" @click="addMember">
                        <svg class="icon" aria-hidden="true" style="margin-right: 6px;">
                            <use xlink:href="#icon-Invitation"></use>
                        </svg>

                        邀请好友进群 </el-button>
                    <el-button type="primary" @click="handleSend">
                        <svg class="icon" aria-hidden="true" style="margin-right: 6px;">
                            <use xlink:href="#icon-fasong"></use>
                        </svg>

                        发送群消息 </el-button>
                    <el-button type="primary" @click="handelTopic">
                        <svg class="icon" aria-hidden="true" style="margin-right: 6px;">
                            <use xlink:href="#icon-fasong"></use>
                        </svg>

                        发布群公告 </el-button>
                    <el-button type="primary" @click="handleSyncMember" :class="{ 'no-click': syncLoading }">
                        <!-- <el-icon v-if="syncLoading" class="mht-loading" style="margin-right: 4px;">
                            <Loading />
                        </el-icon> -->
                        <el-icon :class="{'mht-loading': syncLoading}" style="margin-right: 4px;">
                            <Refresh></Refresh>
                        </el-icon>同步成员</el-button>
                        <el-button type="primary" @click="toChatRecord">
                            查看聊天记录
                        </el-button>
                    <el-button type="danger" icon="Delete" @click="handelDelete">解散群聊</el-button>
                </el-card>
                <el-card class="" style="margin-bottom: 0;">
                    <div class="user-group">
                        <div class="title">群成员</div>
                        <div style="height: 50px;">
                            <!-- <span class="group-span">群名称： {{ groupInfo.nickname }}</span> -->
                            <el-input v-model="memberQuery.nickname" placeholder="请输入昵称"
                                style="width: 200px; margin-right: 12px;"></el-input>
                            <el-button type="primary" icon="Search" @click="searchMember">查询</el-button>
                            <el-button type="primary" @click="selectionAdd"><el-icon style="margin-right: 6px">
                                    <svg class="icon" aria-hidden="true">
                                        <use xlink:href="#icon-tianjiahaoyou1"></use>
                                    </svg>
                                </el-icon>批量添加好友</el-button>
                            <el-button type="danger" icon="Delete" @click="selectionDelete">批量移除</el-button>

                        </div>
                        <div class="table-box">
                            <el-table :data="userTable" max-height="calc(100vh - 480px)"
                                @selection-change="handleSelectionChange" row-key="user_id">
                                <template #empty>
                                    <span v-if="tableLoading">加载中...</span>
                                    <span v-if="!tableLoading">暂无数据</span>
                                </template>
                                <el-table-column type="selection" width="55" :reserve-selection="true" />

                                <el-table-column prop="avatar" label="头像" align="center">
                                    <template #default="scoped">
                                        <el-image style="width: 30px;display: block;margin: auto;border-radius: 4px;"
                                            :src="scoped.row.avatar" />
                                    </template>
                                </el-table-column>
                                <el-table-column prop="nickname" label="昵称" min-width="100" />
                                <!--  <el-table-column prop="realname" label="姓名" /> -->
                                <el-table-column prop="sex" label="性别" align="center" />
                                <el-table-column prop="inviter" label="邀请人" align="center" />
                                <!-- <el-table-column prop="remark_phone_1" label="电话" align="center" min-width="110" /> -->
                                <el-table-column prop="real_remarks" label="备注" />
                                <el-table-column prop="remarks" label="描述" />
                                <el-table-column prop="join_time" label="加入时间" align="center" min-width="180" />
                                <!-- <el-table-column prop="sync_time" label="同步时间" align="center" min-width="180" /> -->
                                <el-table-column prop="" label="操作" width="100" align="center" fixed="right">
                                    <template #default="scoped">
                                        <div class="mht-operations">
                                            <el-tooltip class="box-item" effect="dark" content="添加好友"
                                                placement="bottom">
                                                <el-icon v-if="!scoped.row.is_friend" @click="handelMember(scoped.row)">
                                                    <svg class="icon" aria-hidden="true">
                                                        <use xlink:href="#icon-tianjiahaoyou1"></use>
                                                    </svg>
                                                </el-icon>
                                            </el-tooltip>
                                            <el-tooltip v-if="scoped.row.is_friend" class="box-item" effect="dark" content="成员详情"
                                                placement="bottom">
                                                <el-icon @click="toDetail(scoped.row)">
                                                    <svg class="icon" aria-hidden="true">
                                                        <use xlink:href="#icon-xiangqingye-43"></use>
                                                    </svg>
                                                </el-icon>
                                            </el-tooltip>
                                            <el-tooltip class="box-item" effect="dark" content="删除成员"
                                                placement="bottom">
                                                <el-icon @click="deleteMember(scoped.row)" class="el-icon-danger">
                                                    <Delete />
                                                </el-icon>
                                            </el-tooltip>
                                        </div>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                        <div class="pagination-box">
                            <el-pagination v-model:current-page="memberQuery.page"
                                v-model:page-size="memberQuery.page_size" :page-sizes="[10, 20, 30, 40, 50]"
                                :size="memberQuery.page_size" background
                                layout="total, sizes, prev, pager, next, jumper" :total="memberTotal"
                                @size-change="handleMemberSizeChange" @current-change="handleMemberCurrentChange" />
                        </div>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="9" style="height: 100%;">
                <el-card class="" style="height: 145px; position: relative;">
                    <div class="title">智能体</div>
                        <div class="agent-no" v-if="!agentInfo.agent_id && !skeleton">
                            <el-button icon="Plus" type="primary" @click="checkAgent">添加智能体</el-button>
                        </div>
                        <template v-if="agentInfo.agent_id && !skeleton">

                            <div class="agent-info">
                                <el-image v-if="agentInfo.agent_type == 1" :src="dify"></el-image>
                                <el-image v-if="agentInfo.agent_type == 2" :src="coze"></el-image>
                                <div class="robot-icon" v-if="agentInfo.agent_type == 3"><span>FastGPT</span></div>
                                <div class="agent-box">
                                    <p style="margin-top: 2px;" class="name">{{ agentInfo.agent_name }}</p>
                                    <p style="margin-top: 2px;font-size: 12px;">{{ agentInfo.effect_type == 1 ? '@机器人时生效' : '无论是否@都生效' }}</p>
                                </div>

                            </div>
                            <p class="description">描述：{{ agentInfo.agent_description }}</p>
                            <div class="setting">
                                <el-icon @click="handleSetting">
                                    <Setting />
                                </el-icon>
                                <br />
                                <span v-if="agentInfo.status == 1" class="enable">启用中</span>
                                <span v-if="agentInfo.status == 2" class="disable">已禁用</span>
                                <br />
                                <span class="delete" @click="deleteAi">删除</span>
                            </div>

                        </template>
                        <el-skeleton style="margin-top: 10px;" v-if="skeleton" :rows="2" animated />
                </el-card>
                <el-card class="" style="height: calc(140px);">
                    <div class="title">公告</div>
                    <div class="notice" style="height: calc(100% - 20px);overflow: auto;">
                        <pre>{{ groupInfo.notice_content }}</pre>
                    </div>

                </el-card>
                <el-card class="" style="height: calc(100% - 325px);">
                    <div class="title">任务</div>
                    <div v-if="!skeleton2" class="task" style="height: calc(100% - 20px);">
                        <ul v-infinite-scroll="taskLoad" class="infinite-list" style="overflow: auto"
                            :infinite-scroll-immediate="false" infinite-scroll-distance="5">
                            <li v-for="item in taskList" :key="item.user_id" class="infinite-list-item"
                                style="height: 38px;line-height: 38px;">
                                <span>{{ item.task_name }}</span>
                                <span style="margin-left: 15px; color: var(--el-color-warning);">{{ item.type_text
                                    }}</span>
                                <span class="time">&nbsp; {{ item.created_at }}</span>
                            </li>
                        </ul>
                    </div>
                    <el-skeleton style="margin-top: 20px;" v-if="skeleton2" :rows="3" animated />
                </el-card>

            </el-col>
        </el-row>
        <el-dialog v-model="dialogVisibleGruop" title="邀请好友进群" width="600px" align-center destroy-on-close>
            <div class="dialog-box">
                <el-select-v2 v-model="member_list" popper-class="costom-select" :options="robotUserList"
                    placeholder="请选择好友" style="width:100%" :props="v2props" multiple collapse-tags collapse-tags-tooltip
                    filterable>
                    <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="cardTotal > 100">
                        <el-pagination v-model:current-page="cardPage" :page-size="100" size="small" background
                            layout="prev, pager, next" :total="cardTotal" class="mt-4"
                            @current-change="currentChange" />
                    </template>
                </el-select-v2>


            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submit" :class="{ 'no-click': loading }">
                        <el-icon v-if="loading" class="mht-loading" style="margin-right: 4px;">
                            <Loading />
                        </el-icon>
                        确 定
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog v-model="dialogTopic" title="发布群公告" width="600px" align-center destroy-on-close>
            <div class="dialog-box">
                <el-input type="textarea" v-model="topicCentent" placeholder="请输入公告内容" rows="5"></el-input>


            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitTopic" :class="{ 'no-click': loadingFs }">
                        <el-icon style="margin-right: 4px;" v-if="!loadingFs">
                            <svg class="icon" aria-hidden="true">
                                <use xlink:href="#icon-fasong"></use>
                            </svg>

                        </el-icon>
                        <el-icon v-if="loadingFs" class="mht-loading" style="margin-right: 4px;">
                            <Loading />
                        </el-icon>
                        发 送
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog v-model="dialogVisible" title="发送消息" width="1000px" align-center destroy-on-close>
            <div class="dialog-box">

                <UserMessage :messageMain="ruleForm" @hideMessage="hideMessage" :sendGroup="'sendGroup'"></UserMessage>

            </div>

        </el-dialog>

        <el-dialog v-model="dialogAgent" title="配置智能体" width="600px" align-center destroy-on-close>
            <div class="dialog-box">
                <el-form ref="ruleFormRef" :model="agentForm" :rules="rules">
                    <el-form-item label="选择智能体" prop="agent_id">
                        <el-select v-model="agentForm.agent_id">
                            <el-option v-for="item in agent_lis" :value="item.id" :label="item.name"
                                :key="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="选择生效方式" prop="effect_type">
                        <el-radio-group v-model="agentForm.effect_type">
                            <el-radio :label="1" size="large">@机器人时生效</el-radio>
                            <el-radio :label="2" size="large">无论是否@都生效</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="是否启用" prop="status">
                        <el-radio-group v-model="agentForm.status">
                            <el-radio :label="1" size="large">启用</el-radio>
                            <el-radio :label="2" size="large">禁用</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitAgent" :class="{ 'no-click': mhtLoading }">

                        <el-icon v-if="mhtLoading" class="mht-loading" style="margin-right: 4px;">
                            <Loading />
                        </el-icon>
                        <el-icon style="margin-right: 4px;" v-else>
                            <svg class="icon" aria-hidden="true">
                                <use xlink:href="#icon-baocun"></use>
                            </svg>

                        </el-icon>
                        保 存
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <MhtMessageBox title="提示" :boxText="boxText" :show="dialogDelete" @confirm="submitDelete"
            @close="dialogDelete = false" :mhtLoading="loading"></MhtMessageBox>


        <el-drawer v-model="drawer" direction="rtl">
            <!-- <template #header>
                <h4>set title by slot</h4>
            </template> -->
            <template #default>
                <div class="drawer-box">
                    <div>
                        <label>生效条件：</label>
                        <el-radio-group v-model="agentForm.effect_type">
                            <el-radio :label="1" size="large">@机器人时生效</el-radio>
                            <el-radio :label="2" size="large">无论是否@都生效</el-radio>
                        </el-radio-group>
                    </div>
                    <div>
                        <label>是否启用：</label>
                        <el-radio-group v-model="agentForm.status">
                            <el-radio :label="1" size="large">启用</el-radio>
                            <el-radio :label="2" size="large">禁用</el-radio>
                        </el-radio-group>
                    </div>
                </div>
            </template>
            <template #footer>
                <div style="flex: auto">
                    <el-button @click="drawer = false">取 消</el-button>
                    <el-button type="primary" @click="confirmClick">确 认</el-button>
                </div>
            </template>
        </el-drawer>

        <el-drawer v-model="drawerMsg" direction="rtl" size="600px">
            <template #header>
                <div class="drawer-header">
                    <span>聊天记录 - 仅文本</span>
                    <div style="margin-top: 15px;">
                        <el-date-picker v-model="month" type="month" placeholder="选择月份" @change="handleReMonth" format="YYYY-MM"
                        value-format="YYYY-MM" :disabled-date="disabledDate" :clearable="false" />
                        <el-button type="primary" icon="Search" style="margin-left: 12px;" @click="search">查询</el-button>
                    </div>
                </div>
            </template>
            <template #default>
                <div class="drawer-box-msg">
                    
                    <div class="chat-record-box" @scroll="handleScroll" :infinite-scroll-immediate="false"
                    infinite-scroll-distance="5">
                        <div class="loading-box" v-if="msgLoading">
                            <el-icon class="mht-loading">
                                <Loading />
                            </el-icon>
                        </div>
                        <ChatRecord :msgList="msgList" :sendeInfo="sendeInfo" msgType="group"></ChatRecord>
                    </div>
                </div>
            </template>
            <template #footer>
                <div style="flex: auto">
                    <el-button type="primary" @click="drawer = false">确 认</el-button>
                </div>
            </template>
        </el-drawer>
    </div>
</template>
<script setup>
import { ref, reactive, onMounted, nextTick, watch, computed } from 'vue'
import { groupMemberList, syncGroupMember, removeMember, inviteMember, sendTopic, tasks, groupAgent, setAgent, deleteAgent, groupChatRecord } from '@/api/group'
import { userList, addFromgroup } from '@/api/user'
import { getAgents } from '@/api/ai'
import detailStore from '@/store/modules/detailStore'
import robotStore from '@/store/modules/robotStore'
import { useRouter } from 'vue-router';
import coze from '@/assets/images/coze.png'
import dify from '@/assets/images/dify.png'
const router = useRouter()
const userRobotStore = robotStore()
const detailInfo = detailStore()
const groupInfo = computed(() => {
    return detailInfo.groupDetails
})
const loadingFs = ref(false)
const loading = ref(false)
const v2props = {
    value: 'user_id',
    label: 'nickname'
}
const memberQuery = reactive({
    nickname: '',
    page: 1,
    page_size: 10,
    room_id: ''
})
const memberTotal = ref(0)
const userTable = ref([])
const searchMember = () => {
    memberQuery.page = 1
    getMembers()
}

const tableLoading = ref(false)
const getMembers = async () => {
    tableLoading.value = true
    const res = await groupMemberList({ robot_id: groupInfo.value.robot_id, ...memberQuery })
    tableLoading.value = false
    userTable.value = res.list
    memberTotal.value = res.total
}
const handleMemberSizeChange = (e) => {
    memberQuery.page = 1
    memberQuery.page_size = e
    getMembers()
}
const handleMemberCurrentChange = (e) => {
    memberQuery.page = e
    getMembers()
}
const syncLoading = ref(false)
const handleSyncMember = async () => {
    try {
        syncLoading.value = true
        await syncGroupMember({
            "robot_id": groupInfo.value.robot_id,
            "room_id": memberQuery.room_id
        })
        syncLoading.value = false
        ElNotification({
            type: 'success',
            message: '同步成功'
        })
        memberQuery.page = 1
        getMembers()
    } catch (e) {
        syncLoading.value = false

    }

}
let boxText = ''
const dialogDelete = ref(false)
let deleteType = 0
let deleteData = {}
const deleteMember = (row) => {
    boxText = '确认移除该成员吗'
    deleteData = row
    deleteType = 0
    dialogDelete.value = true
    // ElMessageBox.confirm(
    //     '确认移除该成员吗?',
    //     '提示',
    //     {
    //         confirmButtonText: '确定',
    //         cancelButtonText: '取消',
    //         type: 'warning',
    //     }
    // )
    //     .then(async () => {
    //         await removeMember({
    //             member_list: [row.user_id],
    //             robot_id: userRobotStore.robotInfo.id,
    //             room_id: detailInfo.groupDetails.room_id
    //         })
    //         allUser_ids = []
    //         memberQuery.page = 1
    //         getMembers()
    //     })
    //     .catch(() => {

    //     })
}
let allUser_ids = []

const selectionDelete = () => {
    if (allUser_ids.length == 0) {
        ElNotification({
            type: 'warning',
            message: '请选择列表成员'
        })
        return
    }
    boxText = '确认批量移除选中成员吗'
    deleteType = 1
    dialogDelete.value = true
    // ElMessageBox.confirm(
    //     '确认批量移除选中成员吗?',
    //     '提示',
    //     {
    //         confirmButtonText: '确定',
    //         cancelButtonText: '取消',
    //         type: 'warning',
    //     }
    // )
    //     .then(async () => {
    //         await removeMember({
    //             member_list: allUser_ids,
    //             robot_id: userRobotStore.robotInfo.id,
    //             room_id: detailInfo.groupDetails.room_id
    //         })
    //         memberQuery.page = 1
    //         getMembers()
    //     })
    //     .catch(() => {

    //     })
}

const handelMember = async (row) => {
    ElMessageBox.prompt('发送好友申请消息', '好友申请', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        inputPattern: '',
        customClass: 'customClass'
    })
        .then(async ({ value }) => {
            await addFromgroup({
                content: value,
                "robot_id": groupInfo.value.robot_id,
                "room_id": groupInfo.value.room_id,
                "sleep_max_second": 0,
                "user_id": row.user_id
            })
        })
        .catch(() => {

        })


}
const selectionAdd = () => {
    if (allUser_ids.length == 0) {
        ElNotification({
            type: 'warning',
            message: '请选择列表成员'
        })
        return
    }
    ElMessageBox.prompt('发送好友申请消息', '批量好友申请', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        inputPattern: '',
        customClass: 'customClass'
    })
        .then(async ({ value }) => {
            await addFromgroup({
                content: value,
                "robot_id": groupInfo.value.robot_id,
                "room_id": groupInfo.value.room_id,
                "sleep_max_second": 5,
                "user_id": allUser_ids.join(',')
            })
        })
        .catch(() => {

        })
}
const handelDelete = (row) => {
    boxText = '确认批量移除选中成员吗'
    deleteData = row
    deleteType = 2
    dialogDelete.value = true
    // ElMessageBox.confirm(
    //     '确认解散该群聊吗?',
    //     '提示',
    //     {
    //         confirmButtonText: '确定',
    //         cancelButtonText: '取消',
    //         type: 'warning',
    //     }
    // )
    //     .then(async () => {
    //         await deleteGroup({
    //             robot_id: userRobotStore.robotInfo.id,
    //             sleep_max_second: 0,
    //             room_id: detailInfo.groupDetails.room_id
    //         })
    //         query.page = 1
    //         getTable()
    //     })
    //     .catch(() => {

    //     })
}

const submitDelete = async () => {
    loading.value = true
    try{

        if (deleteType === 0) {
            await removeMember({
                member_list: [deleteData.user_id],
                robot_id: groupInfo.value.robot_id,
                room_id: groupInfo.value.room_id
            })
            loading.value = false
            dialogDelete.value = false
            allUser_ids = []
            ElNotification({
                type: 'success',
                message: '操作成功'
            })
            memberQuery.page = 1
            getMembers()
        } else if (deleteType === 1) {
            await removeMember({
                member_list: allUser_ids,
                robot_id: groupInfo.value.robot_id,
                room_id: groupInfo.value.room_id
            })
            dialogDelete.value = false
            loading.value = false
            allUser_ids = []
            ElNotification({
                type: 'success',
                message: '操作成功'
            })
            memberQuery.page = 1
            getMembers()
        } else if (deleteType === 2) {
            await deleteGroup({
                robot_id: groupInfo.value.robot_id,
                sleep_max_second: 0,
                room_id: groupInfo.value.room_id
            })
            dialogDelete.value = false
            loading.value = false
            ElNotification({
                type: 'success',
                message: '操作成功',
            })
            query.page = 1
            getTable()

        }
    } catch {
        loading.value = false
        
    }

}


const dialogTopic = ref(false)
const topicCentent = ref('')
const handelTopic = () => {
    topicCentent.value = ''
    dialogTopic.value = true
}
const submitTopic = async () => {
    if (topicCentent.value) {
        loadingFs.value = true
        try {
            await sendTopic({
                "content": topicCentent.value,
                "robot_id": groupInfo.value.robot_id,
                "room_id": groupInfo.value.room_id,
                "sleep_max_second": 0
            })
            detailInfo.groupDetails.notice_content = topicCentent.value
            loadingFs.value = false
            dialogTopic.value = false
        } catch {
            loadingFs.value = false
        }

    }
}

const handleSelectionChange = (e) => {
    allUser_ids = e.map((el) => {
        return el.user_id
    })
}
const robotUserList = ref([])
const member_list = ref([])

const cardTotal = ref(0)
const cardPage = ref(1)
const getRobotUsers = async () => {

    const res = await userList({
        robot_id: groupInfo.value.robot_id,
        page: cardPage.value,
        page_size: 100
    })
    robotUserList.value = res.list
    cardTotal.value = res.total

}

const currentChange = (e) => {
    cardPage.value = e
    getRobotUsers()
}

const dialogVisibleGruop = ref(false)
const addMember = () => {
    member_list.value = []
    dialogVisibleGruop.value = true
}
const submit = async () => {
    try {
        loading.value = true
        await inviteMember({
            "member_list": member_list.value,
            "robot_id": groupInfo.value.robot_id,
            "room_id": groupInfo.value.room_id
        })
        dialogVisibleGruop.value = false
        loading.value = false
        memberQuery.page = 1
        getMembers()
    } catch {
        loading.value = false
    }

}
const toDetail = (e) => {
    detailInfo.userDetails = e
    router.push('/userDetails')
}


// 获取任务列表

const taskQuery = reactive({
    page: 1,
    page_size: 10,

    task_name: '',
    task_type: '',
    task_status: ''
})
let taskTotal = 0
const taskList = ref([])
const skeleton2 = ref(true)
const getTasks = async () => {
    const res = await tasks({
        robot_id: groupInfo.value.robot_id,
        group_id: groupInfo.value.room_id,
        ...taskQuery
    })
    taskList.value = res.list
    taskTotal = res.total
    skeleton2.value = false
}
const taskLoad = () => {
    if (taskTotal > taskList.value.length) {
        taskQuery.page++
        getTasks()
    }
}

// 发送群消息
const ruleForm = ref({})
const dialogVisible = ref(false)
const handleSend = () => {
    dialogVisible.value = true
    ruleForm.value = detailInfo.groupDetails

}

const hideMessage = () => {
    dialogVisible.value = false
}

const agentInfo = ref({})
const skeleton = ref(true)
const getGroupAgent = async () => {
    const res = await groupAgent({
        robot_id: groupInfo.value.robot_id,
        room_id: groupInfo.value.room_id
    })
    agentInfo.value = res
    skeleton.value = false
}


// 配置智能体
const drawer = ref(false)
const dialogAgent = ref(false)
const agent_lis = ref([])
const checkAgent = async () => {
    dialogAgent.value = true
    const res = await getAgents({
        name: '',
        type: '',
        page: 1,
        page_size: 100
    })
    agent_lis.value = res.list
}
const ruleFormRef = ref()
const agentForm = ref({})
const rules = ref({
    agent_id: [{
        required: true,
        message: '请选择智能体',
        trigger: 'change',
    }],
    effect_type: [{
        required: true,
        message: '请选择生效方式',
        trigger: 'change',
    }],
    status: [{
        required: true,
        message: '请选择启用状态',
        trigger: 'change',
    }],
})

const mhtLoading = ref(false)
const submitAgent = async () => {
    await ruleFormRef.value.validate(async (valid, fields) => {
        if (valid) {
            try {
                mhtLoading.value = true
                await setAgent({
                    robot_id: groupInfo.value.robot_id,
                    room_id: groupInfo.value.room_id,
                    ...agentForm.value
                })
                dialogAgent.value = false
                getGroupAgent()
                mhtLoading.value = false
            } catch {
                mhtLoading.value = false
            }
        }
    })
}

// 删除agent 
const deleteAi = () => {
    ElMessageBox.confirm(
        '确认删除智能体吗?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            await deleteAgent({
                agent_id: agentInfo.value.agent_id,
                robot_id: groupInfo.value.robot_id,
                room_id: groupInfo.value.room_id
            })
            agentInfo.value = {}
        })
        .catch(() => {

        })
}

const handleSetting = () => {
    drawer.value = true

    agentForm.value = JSON.parse(JSON.stringify(agentInfo.value))
}
const confirmClick = async () => {
    await setAgent({
        robot_id: groupInfo.value.robot_id,
        room_id: groupInfo.value.room_id,
        agent_id: agentForm.value.agent_id,
        effect_type: agentForm.value.effect_type,
        status: agentForm.value.status,
    })
    drawer.value = false
    getGroupAgent()
}

// 聊天记录

const drawerMsg = ref(false)
const msgList = ref([])
const msgTotal = ref(0)
const msgQuery = reactive({
    page: 1,
    page_size: 50,
    msg_type: -1,
    month: ''
})
const toChatRecord = () => {
    let date = new Date().toLocaleDateString().split('/')
    if (date[1] < 10) {
      date[1] = '0' + date[1]
    }
    month.value = date[0] + '-' + date[1]
    msgQuery.month = date[0] + date[1]
    drawerMsg.value = true
    msgList.value = []
    msgTotal.value = 0
    getMessageList()
}
const disabledDate = (time) => {

  return time.getTime() > Date.now();
}
const month = ref('')
const handleReMonth = (e) => {
  if (e) {
    let date = e.split('-')
    month.value = date[0] + '-' + date[1]
    msgQuery.month = date[0] + date[1]
    getMessageList()
  }

}
const search = () => {
    getMessageList()
}
const msgLoading = ref(false)
const getMessageList = () => {
    msgLoading.value = true
    groupChatRecord({
        robot_id: groupInfo.value.robot_id,
        room_id: groupInfo.value.room_id,
        ...msgQuery
    }).then((res) => {
        msgTotal.value = res.total
        // const arr = res.list.sort((a, b) => b.id - a.id);
        const list = res.list?.map((el) => {
            const obj = JSON.parse(el.content)
            el.content = obj.data
            // el.send_time = new Date(el.send_time).getTime()
            // if(obj.data){
            //     el.content = obj
            // } else {
            //     if(!obj.content && obj.msg){
            //         el.content.content = obj.msg
            //     } else {
            //         el.content.content = obj
            //     }
            // }
            // el.content = JSON.parse(el.content).data
            // if(!el.content.content && el.content.msg){
            //     el.content.content = el.content.msg
            // }
            // el.content.file_size = setSize(el.content.file_size)
            return el
        })//.sort((a, b) => a.id - b.id)
        
        const scrollContainer = document.querySelector('.chat-record-box');
        const oldScrollHeight = scrollContainer?.scrollHeight || 0;
        const oldScrollTop = scrollContainer?.scrollTop || 0;
        
        msgList.value = [...list, ...msgList.value]
        
        if(msgQuery.page == 1){
            nextTick(() => {
                const scrollContainer = document.querySelector('.chat-record-box');
                scrollContainer.scrollTop = scrollContainer.scrollHeight;
            })
        } else {
            // For subsequent page loads, maintain the relative scroll position
            nextTick(() => {
                const scrollContainer = document.querySelector('.chat-record-box');
                if (scrollContainer) {
                    const newScrollHeight = scrollContainer.scrollHeight;
                    const heightDifference = newScrollHeight - oldScrollHeight;
                    scrollContainer.scrollTop = heightDifference + oldScrollTop;
                }
            });
        }
        
        msgLoading.value = false
    })
}
const sendeInfo = ref({
    robotInfo: userRobotStore.robotInfo,
    groupInfo: groupInfo.value
})

const setSize = (size) => {
    let file_size = ''
        if(size > 1024*1024){
            file_size = (size / (1024*1024)).toFixed(2) + 'mb'
        }
        if(size > 1024 && size < 1024*1024){
            file_size = (size / 1024).toFixed(2) + 'kb'
        }
        if(size < 1024){
            file_size = size + 'b'
        }
    return file_size
}
const loadMore = () => {
    console.log('loadMore')
    if(msgTotal.value > msgList.value.length){
        msgQuery.page++
        getMessageList()
    }
}
const handleScroll = (event) => {
  const { scrollTop, clientHeight, scrollHeight } = event.target;
  if (scrollTop === 0) {
    loadMore();
  }
};


watch(groupInfo, () => {
    memberQuery.room_id = detailInfo.groupDetails.room_id
    memberQuery.page = 1
    getMembers()

    taskQuery.page = 1
    taskList.value = []
    getTasks()
    getGroupAgent()
})
onMounted(() => {
    memberQuery.room_id = detailInfo.groupDetails.room_id
    getMembers()
    getRobotUsers()
    getTasks()
    getGroupAgent()
})
</script>
<style lang="scss" scoped>
.user-container {
    padding: var(--el-main-padding);
    height: 100%;

    .user-avatar-name {
        display: flex;
        margin-bottom: 10px;
        font-size: 15px;
    }

    .title {
        font-size: 15px;
        font-weight: bold;
        color: var(--el-text-color-regular);
    }

    .time {
        line-height: 24px;
        font-size: 13px;
        color: var(--el-text-color-secondary);
        margin-bottom: 17px;

        .el-icon {
            color: var(--el-color-warning);
            transform: translateY(2px);
            margin-right: 10px;
        }
    }

    .user-avatar {
        height: 60px;
        width: 60px;
        border-radius: 10px;
    }

    .user-name {
        width: auto;
        font-size: 15px;
        // padding-left: 20px;
        line-height: 28px;
        // padding-top: 6px;
    }

    .task {}

    .el-card {
        margin-bottom: 20px;
    }

    .user-group {
        height: calc(100vh - 340px);

        .title {
            margin-bottom: 20px;
        }

        .table-box {

            height: calc(100vh - 480px);
        }
    }

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

        .el-pagination {
            float: right;
        }
    }

    .notice {
        margin-top: 10px;
        padding: 20px;
        padding-top: 0px;
        line-height: 20px;
        font-size: 14px
    }

    .infinite-list {
        height: 100%;
        padding: 0;
        margin-top: 10px;
        list-style: none;
    }

    .infinite-list .infinite-list-item {
        // display: flex;
        // align-items: center;
        // justify-content: center;
        height: 40px;
        line-height: 40px;
        background: var(--el-color-primary-light-9);
        margin: 5px 0;
        // color: var(--el-color-primary);
        width: 100%;
        padding: 0 10px;
        font-size: 14px;
        overflow: hidden;

        .el-image {
            width: 30px;
            height: 30px;
            border-radius: 4px;
            vertical-align: middle;
            margin-right: 10px;
        }

        .sex-icon {
            margin-left: 5px;
            transform: translateY(3px);
        }

        .time {
            float: right;
            line-height: 40px;
        }
    }

    .infinite-list .infinite-list-item+.list-item {
        margin-top: 10px;
    }

    .agent-no {
        text-align: center;
        margin-top: 25px;
    }

    .agent-info {
        margin-top: 14px;
        // padding-left: 20px;
        font-size: 14px;
        line-height: 22px;
        position: relative;
        overflow: hidden;

        .el-image {
            float: left;
            width: 50px;
            height: 50px;
            border-radius: 8px;
        }
        .robot-icon {
                float: left;
                width: 60px;
                height: 50px;
                border-radius: 8px;
                // transform: translateY(4px);
                display: flex;
                align-items: center;
                justify-content: center;
                background-color: var(--el-color-primary-light-3);
                color: #fff;
                font-size: 13px;
                font-weight: bold;
                span{
                    transform: scaleY(1.3);
                }
            }
        .agent-box {
            float: left;
            width: calc(100% - 60px);
            padding-left: 10px;
            font-size: 13px;

            .name {
                font-size: 14px;
            }
        }








    }

    .agent-btn {
        position: absolute;
        right: 20px;
        top: 20px;
        font-size: 13px;

        .el-icon {
            font-size: 18px;
            cursor: pointer;
            color: var(--el-color-primary);
        }

    }

    .setting {
        position: absolute;
        top: 20px;
        right: 20px;
        text-align: right;

        .el-icon {
            color: var(--el-color-primary);
            cursor: pointer;
            font-size: 18px;
            margin-bottom: 6px;
        }

        span {
            font-size: 12px;
            line-height: 20px;
        }

        .disable {
            position: relative;
            color: var(--el-color-danger);

            &::after {
                position: absolute;
                left: -15px;
                top: 4px;
                content: '';
                width: 8px;
                height: 8px;
                border-radius: 8px;
                background-color: var(--el-color-danger);
            }
        }

        .enable {
            position: relative;
            color: var(--el-color-success);

            &::after {
                position: absolute;
                left: -15px;
                top: 4px;
                content: '';
                width: 8px;
                height: 8px;
                border-radius: 8px;
                background-color: var(--el-color-success);
            }
        }

        .delete {
            cursor: pointer;
            margin-left: 12px;
            color: var(--el-color-danger);

            &:hover {
                opacity: 0.7;
            }
        }
    }

    .description {
        height: 18px;
        line-height: 18px;
        font-size: 13px;
        color: var(--el-text-color-regular);
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        margin-top: 10px;
        // padding-left: 20px;
    }

    .drawer-box {
        padding: 0 20px;

        label {
            display: block;
            margin-bottom: 15px;
        }
    }
    .drawer-box-msg{
        
        background-color: var(--el-color-primary-light-9);
        height: 100%;
        overflow: hidden;
        .chat-record-box{
            max-height: calc(100vh - 200px);
            overflow: auto;
            padding: 15px 20px;
        }
    }
    :deep(.el-drawer__header){
        margin-bottom: 0;
    }
    .loading-box{
        width: 100%;
        height: 26px;
        display: flex;
        justify-content: center;
        align-items: center;
        .mht-loading{
            font-size: 18px;
        }
    }
}
</style>
<style lang="scss">
.customClass {
    .el-message-box__content {
        padding: 20px 20px;
    }

    .el-message-box__btns {
        padding-right: 20px;
    }
}
</style>