<template>
    <div class="group-container">
        <div class="search">
            <el-button type="primary" @click="handleAdd">添加客服</el-button>
        </div>

        <div class="table-card">
            <div class="table-card-center">
                <div class="table-box">
                    <el-table :data="robotCards" style="width: 100%" max-height="calc(100vh - 285px)"
                        @selection-change="handleSelectionChange" row-key="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="username" label="客服名称" />
                        <el-table-column prop="nickname" label="客服昵称" />
                        <el-table-column prop="mobile" label="电话" />

                        <el-table-column prop="created_at" label="添加时间" align="center"
                            min-width="160"></el-table-column>

                        <el-table-column prop="" label="操作" align="center" fixed="right" width="220">
                            <template #default="scoped">
                                <div class="mht-operations">

                                    <el-button type="primary" link @click="handleEdit(scoped.row)">
                                        编辑
                                    </el-button>

                                    <el-button type="primary" link @click="handleBindApp(scoped.row)">
                                        绑定小程序
                                    </el-button>
                                    <el-button type="danger" link @click="handleDelete(scoped.row)">
                                        删除
                                    </el-button>
                                </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="sizeChange"
                        @current-change="currentChange" />
                </div>
            </div>
        </div>

        <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑客服' : '添加客服'" width="600px" align-center
            :before-close="handleClose">
            <div class="dialog-box">

                <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules">
                    <el-form-item label="客服名称" prop="username">
                        <el-input v-model="ruleForm.username" placeholder="请输入客服名称" size="large" />
                    </el-form-item>
                    <el-form-item label="客服昵称" prop="nickname">
                        <el-input v-model="ruleForm.nickname" placeholder="请输入客服昵称" size="large" />
                    </el-form-item>
                    <el-form-item label="客服密码" prop="password">
                        <el-input v-model="ruleForm.password" type="password"
                            :placeholder="isEdit ? '留空则不修改密码' : '请输入客服密码'" size="large" />
                        <div v-if="isEdit" style="font-size: 12px; color: #999; margin-top: 4px;">
                            留空则不修改密码
                        </div>
                    </el-form-item>
                    <el-form-item label="客服手机号">
                        <el-input v-model="ruleForm.mobile" placeholder="请输入客服手机号" size="large" />
                    </el-form-item>
                    <el-form-item label="头像">
                        <Upload v-model="ruleForm.avatar" type="image" accept="image/*" :action="robotHost"
                            @change="changeFile" @success="uploadSuccess" @error="uploadError"></Upload>
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitRobot" :class="{ 'no-click': mhtLoading }">
                        <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>
                        {{ isEdit ? '保 存' : '添 加' }}
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog v-model="dialogLog" title="绑定小程序" width="1000px" align-center :before-close="handleClose"
            destroy-on-close>
            <div class="dialog-box">

                <el-table ref="appTableRef" :data="logList" style="width: 100%" max-height="500px" row-key="id"
                    @selection-change="appSelectionChange" v-loading="tableLoading">
                    <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="name" label="小程序名称" />
                    <el-table-column prop="app_id" label="小程序ID" />
                    <el-table-column prop="description" label="描述" />

                    <el-table-column prop="created_at" label="添加时间" align="center" min-width="160"></el-table-column>
                </el-table>
                <div class="pagination-box">
                    <el-pagination v-model:current-page="logQuery.page" v-model:page-size="logQuery.page_size"
                        :page-sizes="[10, 20, 30, 40, 50]" :size="logQuery.page_size" background
                        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange" />
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogLog = false">取消</el-button>
                    <el-button type="primary" @click="saveBind">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>

    </div>
</template>
<script setup>
import { ref, onMounted, reactive, nextTick } from 'vue'
import { robotList, addRobot, deleteRobot, editRobot, robotLog, robot_monitor, bindApps } from '@/api/customerService'
import { appList } from '@/api/miniProgram'
import { ElNotification } from 'element-plus';
import robotStore from '@/store/modules/robotStore'
import { useRouter } from 'vue-router';
import md5 from 'js-md5'
const userRobotStore = robotStore()
const router = useRouter()
const robotCards = ref([])
const dialogVisible = ref(false)
const loading = ref(false)
const ruleFormRef = ref()
const ruleForm = ref({})
const isEdit = ref(false)
const newRobotId = ref('')
let robotCopy = {}
// 动态验证规则，根据是否为编辑模式调整密码验证
const getRules = () => {
    const baseRules = {
        username: [
            {
                required: true,
                message: '请输入客服名称',
                trigger: 'blur',
            }
        ],
        nickname: [{
            required: true,
            message: '请输入客服昵称',
            trigger: 'blur',
        }],
        mobile: [{
            required: true,
            message: '请输入客服手机号',
            trigger: 'blur',
        }],
        avatar: [{
            required: true,
            message: '请上传客服头像',
            trigger: 'change',
        }],
    }

    // 在创建模式下，密码是必填的；在编辑模式下，密码是可选的
    if (!isEdit.value) {
        baseRules.password = [{
            required: true,
            message: '请输入客服密码',
            trigger: 'blur',
        }]
    } else {
        baseRules.password = [{
            required: false,
            message: '请输入客服密码',
            trigger: 'blur',
        }]
    }

    return baseRules
}

const rules = ref(getRules())
const query = reactive({
    username: '',
    nikename: '',
    page: 1,
    page_size: 10
})
const total = ref(0)
const mpTable = ref([])
const getTable = async () => {
    tableLoading.value = true
    const res = await robotList(query).then(res => {
        robotCards.value = res.list
        total.value = res.total
        tableLoading.value = false
    }).catch(() => {
        tableLoading.value = false
    })
}

const listLoad = () => {
    console.log('到底了')
    if (robtoTotal > robotCards.value.length) {
        query.page++
        getTable()
    }

}
const handleAdd = () => {
    if (robotCards.value.length > 100) {
        ElNotification({
            title: '提示',
            message: '最多添加100个客服',
            type: 'warning',
            duration: 2000
        })
        return
    }
    isEdit.value = false
    rules.value = getRules() // 更新验证规则
    dialogVisible.value = true
    nextTick(() => {
        ruleForm.value = {}
        ruleFormRef.value.resetFields()
    })
}
let editItem = {}
let editIndex = 0
const handleEdit = (item) => {
    isEdit.value = true
    rules.value = getRules() // 更新验证规则
    ruleForm.value = JSON.parse(JSON.stringify(item))
    // 清空密码字段，避免显示原密码
    ruleForm.value.password = ''
    dialogVisible.value = true
}
const mhtLoading = ref(false)
const submitRobot = async () => {
    mhtLoading.value = true
    await ruleFormRef.value.validate(async (valid, fields) => {
        if (valid) {
            if (isEdit.value) {
                try {
                    // 编辑时的数据对象
                    const editData = {
                        username: ruleForm.value.username,
                        nickname: ruleForm.value.nickname,
                        avatar: ruleForm.value.avatar,
                        mobile: ruleForm.value.mobile,
                    }

                    // 只有当密码字段有值且不为空时才传入密码字段
                    if (ruleForm.value.password && ruleForm.value.password.trim() !== '') {
                        editData.password = md5(ruleForm.value.password)
                    }

                    const res = await editRobot(ruleForm.value.id, editData)
                    dialogVisible.value = false
                    mhtLoading.value = false
                    getTable()
                    ElNotification({
                        type: 'success',
                        message: '操作成功'
                    })
                } catch {
                    mhtLoading.value = false
                }
            } else {
                try {
                    // 创建时对密码进行MD5加密
                    const createData = {
                        ...ruleForm.value,
                        password: md5(ruleForm.value.password)
                    }

                    const res = await addRobot(createData)
                    robotCards.value.push({
                        ...ruleForm.value,
                    })
                    dialogVisible.value = false
                    mhtLoading.value = false
                    getTable()
                    ElNotification({
                        type: 'success',
                        message: '操作成功'
                    })
                } catch {
                    mhtLoading.value = false
                }
            }

        } else {
            mhtLoading.value = false
        }
    })

}


const handleDelete = (item, index) => {
    ElMessageBox.confirm(
        '确认删除该客服吗?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {

            await deleteRobot({
                ids: String(item.id)
            })
            robotCards.value.splice(index, 1)
            ElNotification({
                message: '删除成功',
                type: 'success',
                duration: 2000
            })

        })
        .catch(() => {

        })
}
const handleRobot = (row) => {
    // newRobotId.value = row.id
    userRobotStore.robotInfo = row
    router.push('/dashboard')
}
const logQuery = reactive({
    page: 1,
    page_size: 10
})
const dialogLog = ref(false)
const logList = ref([])
let robot_data = ''
const tableLoading = ref(false)
let appSelects = []
const appTableRef = ref(null)
let isInitializing = false // 标记是否正在初始化

const bandAppIds = ref([])

// 设置已绑定小程序的选中状态
const setSelectedApps = () => {
    isInitializing = true // 设置初始化标志，防止appSelectionChange错误更新
    nextTick(() => {
        console.log(bandAppIds.value)
        if (appTableRef.value && logList.value.length > 0) {
            logList.value.forEach(row => {
                if (bandAppIds.value.includes(row.id)) {
                    appTableRef.value.toggleRowSelection(row, true)
                }
            })
        }
        // 设置完成后，确保appSelects包含所有已绑定的ID（不仅仅是当前页的）
        appSelects = [...new Set([...appSelects, ...bandAppIds.value])]
        isInitializing = false // 初始化完成
    })
}

// const openLog = async () => {
//     dialogLog.value = true
//     appSelects = []
//     getApps()
//     getActApps()


// }

const getApps = async () => {
    tableLoading.value = true
    const res = await appList(logQuery).then(res => {
        logList.value = res.list
        total.value = res.total
        tableLoading.value = false
        return res
    }).catch(() => {
        tableLoading.value = false
        return null
    })
    return res
}

const getActApps = async () => {
    tableLoading.value = true
    const res2 = await appList({
        admin_id: robot_data.id,
        page: 1,
        page_size: 100
    }).then(res => {
        bandAppIds.value = res.list.map(item => item.id)
        // 初始化 appSelects 包含已绑定的小程序
        console.log(bandAppIds.value)
        console.log(appSelects)
        appSelects = [...bandAppIds.value]
        tableLoading.value = false
        return res
    }).catch(() => {
        tableLoading.value = false
        return null
    })
    return res2
}
const handleBindApp = async (row) => {
    robot_data = row
    dialogLog.value = true
    logQuery.page = 1
    logQuery.page_size = 10
    // 重置已绑定列表和选中列表，因为切换了客服
    bandAppIds.value = []
    appSelects = []
    // 清空表格选中状态
    nextTick(() => {
        if (appTableRef.value) {
            appTableRef.value.clearSelection()
        }
    })
    // 先加载小程序列表，再加载已绑定列表，最后设置选中状态
    await getApps()
    await getActApps()
    // 数据加载完成后再设置选中状态（setSelectedApps内部会处理isInitializing标志）
    setSelectedApps()
}

const isSelectable = (row) => {
    // 如果小程序ID在已绑定列表中,则不可选择
    return !bandAppIds.value.includes(row.id)
}

const appSelectionChange = (e) => {
    // 获取当前选中的小程序ID
    const selectedIds = e.map(item => item.id)

    // 如果不是初始化阶段，才处理取消勾选的逻辑
    if (!isInitializing) {
        // 找出被取消勾选的已绑定项目，从bandAppIds中移除
        bandAppIds.value.forEach(id => {
            if (!selectedIds.includes(id)) {
                // 如果这个已绑定的ID不在当前选中列表中，说明被取消了，从bandAppIds中移除
                const index = bandAppIds.value.indexOf(id)
                if (index > -1) {
                    bandAppIds.value.splice(index, 1)
                }
            }
        })
    }

    // appSelects 保存当前选中的所有ID（包括未取消的已绑定项和新选中的项）
    appSelects = selectedIds
}

const saveBind = (val) => {
    // 合并已选列表和已绑定列表
    const finalIds = [...new Set([...appSelects, ...bandAppIds.value])]
    console.log(finalIds)
    // return
    if (finalIds.length == 0) {
        ElNotification({
            message: '请选择小程序',
            type: 'warning'
        })
    } else {
        bindApps(robot_data.id, {
            ids: finalIds.join(',')
        }).then(res => {
            dialogLog.value = false
            ElNotification({
                message: '绑定成功',
                type: 'success'
            })
        })
    }

}
const sizeChange = (e) => {
    query.page = 1
    query.page_size = e
    getTable()
}
const currentChange = (e) => {
    query.page = e
    getTable()
}
const handleSizeChange = async (e) => {
    logQuery.page = 1
    logQuery.page_size = e
    await getApps()
    // 翻页后重新设置选中状态
    setSelectedApps()
}
const handleCurrentChange = async (e) => {
    logQuery.page = e
    await getApps()
    // 翻页后重新设置选中状态
    setSelectedApps()
}

const rowClassname = (e) => {
    if (e.row.status == 1) {
        return 'row-success'
    } else {
        return 'row-danger'
    }
}
const xjLoading = ref(false)
const setMonitor = async (e) => {
    if (xjLoading.value == true) return
    try {
        xjLoading.value = true
        const res = await robot_monitor({
            robot_id: e.id
        })
        e.status_text = res.status_text
        e.status = res.status
        xjLoading.value = false
        ElNotification({
            type: 'success',
            message: '监听成功'
        })
    } catch (e) {
        xjLoading.value = false
    }

}
const robotHost = import.meta.env.VITE_APP_BASE_API + 'admin/upload/image'
const disabledBtn = ref(true)
const changeFile = () => {
    disabledBtn.value = true
}
const uploadSuccess = (e) => {
    ruleForm.value.avatar = import.meta.env.VITE_APP_BASE_API_img + e.preview_image_url

    disabledBtn.value = false
}

const handleDetail = (row) => {
    router.push({ path: '/chat', query: { app_id: row.app_id } })
}
onMounted(() => {
    query.page = 1
    robotCards.value = []
    getTable()
    // newRobotId.value = userRobotStore.robotInfo.id ? userRobotStore.robotInfo.id : ''
})
</script>
<style></style>
<style lang="scss" scoped>
.group-container {
    height: 100%;
    padding: 20px;
    background-color: #fff;

    .infinite-list {
        height: 100%;
        padding: var(--el-main-padding);
        padding-right: 0;
    }

    .el-card {


        :deep(.el-card__body) {
            height: 100%;
        }

        .robot-title {
            overflow: hidden;
            margin-bottom: 10px;

            .robot-head {
                float: left;
                width: 64px;
                height: 64px;
                border-radius: 10px;
            }

            .robot-name-box {
                float: left;
                padding-left: 12px;
                width: calc(100% - 66px);

                label {
                    display: block;
                    line-height: 16px;
                    margin-bottom: 6px;
                    font-size: 14px;
                }
            }
        }



        .name {
            font-size: 15px;
            font-weight: bold;
            margin-top: 4px;
        }

        .wx_name {
            display: block;
            color: var(--el-text-color-regular);
        }

        .description {
            width: 86%;
            font-size: 14px;
            line-height: 20px;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            /* 设置垂直排列 */
            -webkit-line-clamp: 2;
            /* 设置行数 */
            overflow: hidden;
            /* 设置超出省略 */
            text-overflow: ellipsis;
            /* 设置省略以...结尾 */

            color: var(--el-text-color-secondary);
        }

        .success {
            position: absolute;
            right: 20px;
            bottom: 21px;
            font-size: 12px;
            color: var(--el-color-success);

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

        .danger {
            position: absolute;
            right: 20px;
            bottom: 21px;
            font-size: 12px;
            color: var(--el-color-danger);

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

        &:hover {
            transform: translateY(-6px);
            background-color: var(--el-color-primary-light-7);
        }

        .icon-robot {
            font-size: 66px;
        }

        .act-icon {
            position: absolute;
            font-size: 40px;
            right: -2px;
            bottom: -8px;
            opacity: 0;
        }

    }

    .active-robot {
        .act-icon {
            opacity: 0.6;
        }
    }

    .add-robot {

        background-image: url('@/assets/images/add_robot_bg.png');
        background-color: var(--el-color-primary-light-5);
        background-size: 100% auto;

        &:hover {
            transform: translateY(-10px);
        }

        .add-box {
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            color: var(--el-color-primary);

            .el-icon {
                position: relative;
                top: -1px;
                margin-right: 3px;
            }
        }
    }

    .edit-icon {
        position: absolute;
        right: 15px;
        top: 14px;
        // display: none;
        height: 30px;
        width: 30px;
        text-align: center;
        line-height: 30px;
        border-radius: 8px;
        transition: all 0.1s;

        i {
            position: relative;
            left: 2px;
            top: 3px;
            color: var(--el-color-primary);
            // color: #fff;
            // transition: all 0.1s;
            // transform: rotate(90deg);
        }


    }


}

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

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