<template>
    <div class="user-container">
        <el-card class="search">
            <el-select-v2 style="width: 200px;margin-right: 12px;" v-model="robot_id" popper-class="costom-select"
                :options="robotCards" placeholder="请选择机器人" :props="v2props" filterable @change="changeRobot">
                <template #default="{ item }">
                    <div class="costom-select-item">
                        <el-image :src="item.head_url"></el-image>
                        <span>{{ item.name }}</span>
                    </div>
                </template>
                <template #footer v-if="robotTotal > 100">
                    <el-pagination v-model:current-page="queryRobot.page" :page-size="queryRobot.page_size" size="small"
                        background layout="prev, pager, next" :total="robotTotal" class="mt-4"
                        @current-change="currentChange" />
                </template>
            </el-select-v2>
            <el-input v-model="query.nickname" placeholder="请输入群名称"
                style="width: 200px; margin-right: 12px;"></el-input>
            <el-button type="primary" icon="Search" @click="search">查询</el-button>
            <el-button type="primary" icon="Finished" @click="selectionSend">批量发送消息</el-button>
            <el-button type="primary" @click="selectionTopic"> <el-icon style="margin-right: 8px;">
                    <svg class="icon" aria-hidden="true">
                        <use xlink:href="#icon-tubiao_gonggao"></use>
                    </svg></el-icon>批量发送公告</el-button>
            <el-button type="danger" icon="Delete" @click="selectionDelete">批量解散</el-button>
            <el-button ref="syncRef" type="primary" @click="handleSync" style="float: right"
                :class="{ 'no-click': syncLoading }">
                <!-- <el-icon v-if="syncLoading" class="mht-loading" style="margin-right: 4px;">
                    <Loading />
                </el-icon> -->
                <el-icon style="margin-right: 4px;" :class="{ 'mht-loading': syncLoading }">
                    <Refresh></Refresh>
                </el-icon>同步群组</el-button>
            <el-button type="primary" icon="Plus" @click="handleCreate" style="float: right">新建群聊</el-button>
        </el-card>
        <el-card class="table-card">

            <div class="table-card-center">
                <div class="table-box">
                    <el-table :data="groupTable" max-height="calc(100vh - 285px)" style="width: 100%"
                        @selection-change="handleSelectionChange" row-key="room_id">
                        <template #empty>
                            <span v-if="tableLoading">加载中...</span>
                            <span v-if="!tableLoading && robot_id">暂无数据</span>
                            <span v-if="!robot_id && !tableLoading" style="font-weight: bold;">请选择一个机器人</span>
                        </template>
                        <el-table-column type="selection" width="55" :reserve-selection="true" />
                        <el-table-column prop="room_name" label="群组名称" />
                        <el-table-column prop="members_count" label="成员人数" align="center" />
                        <el-table-column prop="create_time" label="创建时间" align="center"></el-table-column>

                        <el-table-column prop="sync_time" label="同步时间" align="center" />
                        <el-table-column label="入群欢迎语" align="center">
                            <template #default="scoped">
                                <div class="mht-operations">
                                    <el-link type="primary" :underline="false"
                                        @click="readyWelcom(scoped.row)">配置</el-link>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="意图关键字" align="center">
                            <template #default="scoped">
                                <div class="mht-operations">
                                    <el-link type="primary" :underline="false" @click="setKeys(scoped.row)">查看</el-link>
                                </div>
                            </template>
                        </el-table-column>

                        <el-table-column prop="" label="操作" width="100" align="center">
                            <template #default="scoped">
                                <div class="mht-operations">
                                    <el-tooltip 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="handleSend(scoped.row)">
                                            <svg class="icon" aria-hidden="true">
                                                <use xlink:href="#icon-fasong"></use>
                                            </svg>
                                        </el-icon>
                                    </el-tooltip>
                                    <el-tooltip class="box-item" effect="dark" content="发送群公告" placement="bottom">
                                        <el-icon @click="handelTopic(scoped.row)">
                                            <svg class="icon" aria-hidden="true">
                                                <use xlink:href="#icon-tubiao_gonggao"></use>
                                            </svg>
                                        </el-icon>
                                    </el-tooltip>
                                    <el-tooltip class="box-item" effect="dark" content="删除" placement="bottom">
                                        <el-icon @click="handelDelete(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="query.page" v-model:page-size="query.page_size"
                        :page-sizes="[20, 30, 40, 50]" :size="query.page_size" background
                        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange" />
                </div>
            </div>
        </el-card>
        <el-dialog v-model="dialogVisible" title="发送消息" width="1000px" align-center destroy-on-close>
            <div class="dialog-box">
                <div class="send-user">
                    <span>发送给群：</span>
                    <el-tag v-if="allUserlist.length == 0" type="primary">{{ ruleForm.room_name }}</el-tag>
                    <el-tag v-if="allUserlist.length > 0" type="primary" v-for="item in selectList">{{ item.room_name
                        }}</el-tag>
                </div>
                <UserMessage :messageMain="ruleForm" :allUserIds="allUserlist" @hideMessage="hideMessage"
                    :sendGroup="'sendGroup'"></UserMessage>

            </div>

        </el-dialog>

        <el-dialog v-model="dialogTopic" title="发送群公告" width="600px" align-center destroy-on-close>
            <div class="dialog-box">
                <div class="send-user">
                    <span>发送给群：</span>
                    <el-tag v-if="isAllTopic" type="primary" v-for="item in selectList">{{ item.room_name
                        }}</el-tag>
                    <el-tag v-else type="primary">{{ groupData.room_name
                        }}</el-tag>
                </div>
                <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': 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="dialogCreate" title="新建群聊" width="1000px" align-center destroy-on-close>
            <div class="dialog-box">
                <el-input v-model="room_name" placeholder="群聊名称" style="margin-bottom: 20px;"></el-input>
                <UserCard :cardlist="cardlist" height="500px" v-model="cardIds" multiple @load="load" @input="input"
                    @change="changeUser">
                </UserCard>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitNewGroup" :class="{ 'no-click': createLoading }">
                        <el-icon v-if="createLoading" class="mht-loading" style="margin-right: 4px;">
                            <Loading />
                        </el-icon>
                        保 存
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog v-model="dialogKeywords" title="意图识别" width="800px" align-center destroy-on-close>
            <div class="dialog-box">
                <KeyWords :groupInfo="groupInfo" :keywordInfo="keywordInfo" @hideKey="hideKey" />
            </div>
            <!-- <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitNewGroup" :class="{ 'no-click': createLoading }">
                        <el-icon v-if="createLoading" class="mht-loading" style="margin-right: 4px;">
                            <Loading />
                        </el-icon>
                        保 存
                    </el-button>
                </div>
            </template> -->
        </el-dialog>

        <el-dialog v-model="dialogKeys" title="查看意图识别列表" width="1000px" align-center :before-close="handleClose">
            <div class="dialog-box">
                <el-input v-model="keyQuery.keyword" style="width: 230px;" placeholder="输入关键字">
                    <template #append>
                        <el-button icon="Search" @click="searchKeys" />
                    </template>
                </el-input>
                <el-button type="primary" icon="Plus" @click="addKey" style="margin-left: 12px;">添加关键字</el-button>
                <el-table :data="keyWordList" style="width: 100%; margin-top: 20px;" max-height="500px">
                    <template #empty>
                        <span v-if="tableLoading2">加载中...</span>
                        <span v-if="!tableLoading2">暂无数据</span>
                    </template>
                    <el-table-column prop="keyword" label="意图关键字" align="left" width="150" />
                    <el-table-column prop="material_type_count" label="素材类型数量" align="center">
                    </el-table-column>
                    <el-table-column prop="" label="操作" width="100" align="center">
                        <template #default="scoped">
                            <div class="mht-operations">
                                <el-tooltip class="box-item" effect="dark" content="编辑" placement="bottom">
                                    <el-icon @click="editKey(scoped.row)">
                                        <Edit />
                                    </el-icon>
                                </el-tooltip>
                                <el-tooltip class="box-item" effect="dark" content="复制" placement="bottom">
                                    <el-icon @click="handleCopy(scoped.row)">
                                        <DocumentCopy />
                                    </el-icon>
                                </el-tooltip>
                                <el-tooltip class="box-item" effect="dark" content="删除" placement="bottom">
                                    <el-icon @click="deleteKey(scoped.row)" class="el-icon-danger">
                                        <Delete />
                                    </el-icon>
                                </el-tooltip>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="pagination-box">
                    <el-pagination v-model:current-page="keyQuery.page" v-model:page-size="keyQuery.page_size"
                        :page-sizes="[20, 30, 40, 50]" :size="keyQuery.page_size" background
                        layout="total, sizes, prev, pager, next, jumper" :total="keyWordTotal"
                        @size-change="keySizeChange" @current-change="keyCurrentChange" />
                </div>
            </div>
            <!-- <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="dialogLog = false">
                        关闭
                    </el-button>
                </div>
            </template> -->
        </el-dialog>
        <el-dialog v-model="dialogWelcome" title="配置欢迎语" width="800px" align-center destroy-on-close>
            <div class="dialog-box">
                <Welcome :groupInfo="groupInfo" :welcomeType="'0'" @hideWelcome="hideWelcome" />
            </div>

        </el-dialog>
        <el-tour v-model="openTour" content-style="width: 250px;text-align: center;">
            <el-tour-step :target="syncRef?.$el" title="">
                <span>创建群组后，请点击按钮同步</span>
            </el-tour-step>
        </el-tour>

        <MhtMessageBox title="提示" :boxText="boxText" :show="dialogDelete" @confirm="submitDelete"
            @close="dialogDelete = false" :mhtLoading="loading"></MhtMessageBox>


        <el-dialog v-model="dialogCopy" title="复制意图关键字" width="550px" align-center destroy-on-close>
            <div class="dialog-box">
                <el-form ref="refCopy" :model="copyTask" :rules="rulesCopy">
                    <el-form-item label="将关键字复制给下面的群组" prop="room_id">
                        <el-select-v2 style="" v-model="copyTask.room_id" popper-class="costom-select"
                            :options="robotCardsCopy" placeholder="请选择群组" :props="v2props2" filterable
                            @change="changeRobotCopy" clearable>


                        </el-select-v2>
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogCopy = false">取 消</el-button>
                    <el-button type="primary" @click="saveCopy" :class="{ 'no-click': mhtLoading }"
                        style="margin-right: 20px;">
                        <el-icon v-if="mhtLoading" 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, onActivated } from 'vue'
import { groupList, syncGroup, groupMemberList, syncGroupMember, sendTopic, deleteGroup, createGroup, keyWordArr, deleteKeyword } from '@/api/group'
import { keywords, addKeywords, addKeywordsMaterial, keywordsMaterials, upKeyword } from '@/api/keyword'
import { userList } from '@/api/user'
import { robotList } from '@/api/robot'
import { useRouter } from 'vue-router';
import { ElNotification } from 'element-plus';
import robotStore from '@/store/modules/robotStore'
import detailStore from '@/store/modules/detailStore'
import KeyWords from '@/components/KeyWords/index.vue'
defineOptions({
  name: "groups",
});
const openTour = ref(false)
const syncRef = ref()
const detailInfo = detailStore()
const userRobotStore = robotStore()
const router = useRouter()
const dialogVisible = ref(false)
const dialogVisibleMember = ref(false)
const ruleForm = ref({})
const query = reactive({
    nickname: '',
    page: 1,
    page_size: 20
})
const robot_id = ref('')
const userTable = ref([])
const groupTable = ref([])
const robotCards = ref([])
const total = ref(0)
const tableLoading = ref(false)
const getTable = async () => {
    // if (!userRobotStore.robotInfo.id) {
    //     ElNotification({
    //         type: 'warning',
    //         message: '请在机器人页面选择机器人！'
    //     })
    //     return
    // }
    tableLoading.value = true
    const res = await groupList({ robot_id: robot_id.value, ...query })
    tableLoading.value = false
    groupTable.value = res.list
    total.value = res.total
}
// const getRobotList = async () => {
//     robotCards.value = (await robotList({
//         page: 1,
//         page_size: 30
//     })).list
//     if (robotCards.value.length > 0) {
//         query.robot_id = robotCards.value[0].id
//         getTable()
//     }
// }
const search = () => {
    if (!robot_id.value) {
        ElNotification({
            type: 'warning',
            message: '请选择机器人！'
        })
    } else {
        query.page = 1
        getTable()
    }
}

const handleSizeChange = (e) => {
    query.page = 1
    query.page_size = e
    getTable()
}
const handleCurrentChange = (e) => {
    query.page = e
    getTable()
}
const syncLoading = ref(false)
const handleSync = async () => {
    if (!robot_id.value) {
        ElNotification({
            type: 'warning',
            message: '请选择机器人'
        })
    } else {
        try {
            syncLoading.value = true

            openTour.value = false
            await syncGroup({
                robot_id: robot_id.value
            })
            syncLoading.value = false
            ElNotification({
                type: 'success',
                message: '同步成功'
            })
            query.page = 1
            getTable()
        } catch (err) {
            syncLoading.value = false
        }
    }
}




const memberQuery = reactive({
    nickname: '',
    page: 1,
    page_size: 20,
    room_id: ''
})
const memberTotal = ref(0)
const groupInfo = ref({})
const readyMember = (row) => {
    groupInfo.value = row
    memberQuery.room_id = row.room_id
    // memberQuery.robot_id = robot_id.value
    dialogVisibleMember.value = true
    getMembers()
}
const handleSyncMember = async () => {
    await syncGroupMember({
        "robot_id": robot_id.value,
        "room_id": memberQuery.room_id
    })
    ElNotification({
        type: 'success',
        message: '同步成功'
    })
    memberQuery.page = 1
    getMembers()
}
const searchMember = () => {
    memberQuery.page = 1
    getMembers()
}
const getMembers = async () => {
    const res = await groupMemberList({ robot_id: robot_id.value, ...memberQuery })
    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 allUserlist = ref('')
const handleSend = (row) => {
    dialogVisible.value = true
    allUserlist.value = ''
    ruleForm.value = row

}

let allUser_ids = []

const selectionSend = () => {
    if (allUser_ids.length == 0) {
        ElNotification({
            type: 'warning',
            message: '请选择列表群组'
        })
        return
    }
    allUserlist.value = allUser_ids.join(',')
    dialogVisible.value = true
}
// 多选
const selectList = ref([])
const handleSelectionChange = (e) => {
    selectList.value = e
    allUser_ids = e.map((el) => {
        return el.room_id
    })
}
const hideMessage = (e) => {
    dialogVisible.value = false
}
const deleteMember = () => {

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

const groupData = ref({})
const dialogTopic = ref(false)
const topicCentent = ref('')
const isAllTopic = ref(false)

const handelTopic = (row) => {
    isAllTopic.value = false
    groupData.value = row
    topicCentent.value = ''
    dialogTopic.value = true
}
const loading = ref(false)
const submitTopic = async () => {
    if (topicCentent.value) {
        loading.value = true
        try {
            await sendTopic({
                "content": topicCentent.value,
                "robot_id": robot_id.value,
                "room_id": isAllTopic.value ? allUser_ids.join(',') : groupData.value.room_id,
                "sleep_max_second": isAllTopic.value ? 5 : 0
            })
            dialogTopic.value = false
            loading.value = false
            ElNotification({
                type: 'success',
                message: '发送成功'
            })
        } catch {
            loading.value = false
        }

    }
}

const selectionTopic = () => {
    if (allUser_ids.length == 0) {
        ElNotification({
            type: 'warning',
            message: '请选择列表群组'
        })
        return
    }
    isAllTopic.value = true
    dialogTopic.value = true
}
const boxText = ref('')
const dialogDelete = ref(false)
let deleteData = {}
let deleteType = 0
const handelDelete = (row) => {
    deleteType = 0
    boxText.value = '确认解散该群聊吗?'
    dialogDelete.value = true
    deleteData = row

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

    if (deleteType === 0) {
        await deleteGroup({
            robot_id: robot_id.value,
            sleep_max_second: 0,
            room_id: deleteData.room_id
        })
        deleteData = {}
        dialogDelete.value = false
        loading.value = false
        ElNotification({
            type: 'success',
            message: '操作成功',
        })
        query.page = 1
        getTable()
    } else {
        await deleteGroup({
            robot_id: robot_id.value,
            sleep_max_second: 5,
            room_id: allUser_ids.join(',')
        })
        dialogDelete.value = false
        loading.value = false
        allUser_ids = []
        ElNotification({
            type: 'success',
            message: '操作成功',
        })
        query.page = 1
        getTable()
    }
} catch {
    loading.value = false
}
 
}

const selectionDelete = () => {
    if (allUser_ids.length == 0) {
        ElNotification({
            type: 'warning',
            message: '请选择列表群聊'
        })
        return
    }
    deleteType = 1
    boxText.value = '确认解散选中群聊吗?'
    dialogDelete.value = true

}


const dialogCreate = ref(false)
const cardlist = ref([])


const cardQuery = {
    page: 1,
    page_size: 15,

    nickname: ''
}
const cardIds = ref([])
const room_name = ref('')
let cardQueryTotal = 0
const handleCreate = () => {
    if (!robot_id.value) {
        ElNotification({
            type: 'warning',
            message: '请选择机器人'
        })
        return
    }
    room_name.value = ''
    dialogCreate.value = true
    cardQuery.page = 1
    cardQuery.nickname = ''
    cardlist.value = []
    getCardList()
}
const getCardList = async () => {
    const res = await userList({ ...cardQuery, robot_id: robot_id.value })
    cardQueryTotal = res.total
    cardlist.value = [...cardlist.value, ...res.list]
}
const load = () => {
    if (cardlist.value.length < cardQueryTotal) {
        cardQuery.page++
        getCardList()
    }
}
const input = (e) => {
    cardQuery.nickname = e
    cardQuery.page = 1
    cardlist.value = []
    getCardList()
}

const changeUser = (e) => {
}
const createLoading = ref(false)
const submitNewGroup = () => {
    if (!room_name.value || cardIds.value.length == 0) {
        return
    }
    createLoading.value = true
    // let member_list = cardIds.value.map((el) => {
    //     return el.user_id
    // })
    setTimeout(async () => {
        try {
            const res = await createGroup({
                "member_list": cardIds.value,
                "robot_id": robot_id.value,
                "room_name": room_name.value
            })
            dialogCreate.value = false
            createLoading.value = false
            openTour.value = true
            query.page = 1
            getTable()
        } catch {
            createLoading.value = false
        }

    })

}

// 一图关键字
const dialogKeys = ref(false)
const keywordInfo = ref({})
const dialogKeywords = ref(false)
const setKeys = (row) => {
    groupInfo.value = row
    dialogKeys.value = true
    keyWordList.value = []
    getKeyWords()
}
const keyQuery = reactive({
    page: 1,
    page_size: 20,
    keyword: ''
})
const keyWordList = ref([])
const keyWordTotal = ref(0)
const tableLoading2 = ref(false)
const getKeyWords = async () => {
    tableLoading2.value = true
    const res = await keyWordArr({
        room_id: groupInfo.value.room_id,
        robot_id: robot_id.value,
        ...keyQuery
    })
    tableLoading2.value = false
    keyWordList.value = res.list
    keyWordTotal.value = res.total
}
const keySizeChange = (e) => {
    keyQuery.page = 1
    keyQuery.page_size = e
    getKeyWords()
}
const keyCurrentChange = (e) => {
    keyQuery.page = e
    getKeyWords()
}

const addKey = () => {
    keywordInfo.value = {}
    dialogKeywords.value = true
}
const hideKey = () => {
    dialogKeywords.value = false
    keyQuery.page = 1
    getKeyWords()
}
const searchKeys = () => {
    keyQuery.page = 1
    getKeyWords()
}
const editKey = (row) => {
    keywordInfo.value = row
    dialogKeywords.value = true
}
const deleteKey = (row) => {
    ElMessageBox.confirm(
        '确认删除该关键字吗?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            await deleteKeyword(row.id)
            getKeyWords()
        })
        .catch(() => {

        })
}
// 查看欢迎语
const dialogWelcome = ref(false)
const readyWelcom = (row) => {
    groupInfo.value = row
    nextTick(() => {
        dialogWelcome.value = true
    })
}
const hideWelcome = () => {
    dialogWelcome.value = false
}


const v2props = ref({
    value: 'id',
    label: 'name'
})
const queryRobot = ref({
    page: 1,
    page_size: 100
})
const robotTotal = ref(0)
const getRobotList = async () => {
    const res = await robotList(queryRobot.value)
    robotCards.value = res.list
    robotTotal.value = res.total
}
const changeRobot = (e) => {
    robotCards.value.forEach(item => {
        if (item.id == e) {
            userRobotStore.robotInfo = item
        }
    })
    query.page = 1
    getTable()
}
const currentChange = (e) => {
    queryRobot.value.page = e
    getRobotList()
}

// 复制
const refCopy = ref()
const copyTask = ref({})
const rulesCopy = ref({
    room_id: [
        {
            required: true,
            message: '选择群组',
            trigger: 'change',
        }
    ]
})
const v2props2 = ref({
    value: 'room_id',
    label: 'room_name'
})
const robotCardsCopy = ref([])
const dialogCopy = ref(false)
let copyMateriaList = []
let key_data = {}
const handleCopy = (row) => {
    dialogCopy.value = true
    key_data = row
    console.log(row)
    robotCardsCopy.value = groupTable.value.filter(item => item.room_id != row.room_id)
    keywordsMaterials({
        keyword_id: row.id,
        page: 1,
        page_size: 100
    }).then(res => {
        copyMateriaList = res.list.map((el) => {
            el.content = JSON.parse(el.content)
            return el
        })
    })

}
let uploadAction = ''

let copyGroup = {}
const changeRobotCopy = (e) => {
    // robotCardsCopy.value.forEach((el) => {
    //     if (e == el.room_id) {
    //         copyGroup = el
    //     }
    // })
}

const convertImageUrlToFile = async (url, fileName) => {
    try {
        // 1. 获取图片数据
        console.log(url)
        const response = await fetch(url);
        if (!response.ok) throw new Error('图片下载失败');

        // 2. 将响应转换为 Blob
        const blob = await response.blob();
        // 创建 FormData 对象
        const formData = new FormData();
        // 生成文件名
        formData.append('file', blob, fileName);
        // // 3. 将 Blob 转换为 File 对象（模拟用户上传的文件）
        // const file = new File([blob], fileName, { type: blob.type });

        return formData;
    } catch (error) {
        console.error('转换失败:', error);
        throw error;
    }

}
const mhtLoading = ref(false)
const saveCopy = async () => {
    await refCopy.value.validate(async (valid, fields) => {
        if (valid) {
            mhtLoading.value = true
            try {
                // const obj = JSON.parse(JSON.stringify(copyTask.value))
                // obj.robot_id = String(copyTask.value.robot_id)
                const resKeys = await addKeywords({
                    "keyword": key_data.keyword,
                    "robot_id": robot_id.value,
                    room_id: copyTask.value.room_id
                })
                const key_id = resKeys.id

                await addKeywordsMaterial({
                    'material_list': copyMateriaList.map((el) => {
                        return {
                            content: JSON.stringify(el.content),
                            type: el.type,
                            interval_seconds: el.interval_seconds
                        }
                    })

                }, key_id)
                mhtLoading.value = false
                dialogCopy.value = false
                ElNotification({
                    type: 'success',
                    message: '复制成功'
                })

            } catch (err) {
                mhtLoading.value = false
            }
        }
    })

}

onMounted(() => {
    getRobotList()
    // if (userRobotStore.robotInfo.id) {
    //     getTable()
    // }
})
onActivated(() => {
    if(robot_id.id != '' && query.nickname != ''){
        query.nickname = ''
        getTable()
    }
    
})
</script>
<style lang="scss" scoped>
.user-container {
    padding: var(--el-main-padding);

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

    .table-card {
        margin-top: 20px;

        .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;
        }
    }


    .dialog-box {
        .group-span {
            margin-right: 12px;
        }
    }

    .dialog-footer {
        padding-right: 30px;
        padding-bottom: 20px;
    }

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

        span {
            float: left;
        }



        .el-tag {
            float: left;
            margin-right: 12px;
            margin-bottom: 10px;
        }
    }
}
</style>