<template>
    <div>
        <el-dialog v-model="dialogVisible" title="驾驶舱管理" width="750">
            <div style="display: flex; justify-content: end" class="mb10">
                <el-button icon="el-icon-Plus" type="primary" @click="add">新增</el-button>
            </div>
            <div style="height: 300px; max-height: 400px">
                <vxe-table
                    border
                    ref="tableRef"
                    :data="pageList.filter((item: any) => item.pagePath != 'dashboard/index')"
                    align="center"
                    height="auto"
                    v-bind="defaultAttribute"
                >
                    <vxe-column type="seq" title="序号" width="80"></vxe-column>
                    <vxe-column field="pageName" title="菜单名称"></vxe-column>

                    <vxe-column field="icon" title="图标" width="80">
                        <template #default="{ row }">
                            <Icon class="ba-icon-dark" :name="row.icon || ''" />
                        </template>
                    </vxe-column>
                    <vxe-column field="startTime" title="是否激活" width="90">
                        <template #default="{ row }">
                            <el-switch
                                v-model="row.state"
                                inline-prompt
                                :disabled="!hasAdmin && row.scope"
                                :active-value="1"
                                :inactive-value="0"
                                active-text="已激活"
                                inactive-text="未激活"
                                :before-change="() => beforeChange(row)"
                            />
                        </template>
                    </vxe-column>
                    <vxe-column field="startTime" title="是否全局" v-if="hasAdmin" width="90">
                        <template #default="{ row }">
                            <el-switch
                                v-model="row.scope"
                                inline-prompt
                                :active-value="1"
                                width="50px"
                                :inactive-value="0"
                                active-text="是"
                                inactive-text="否"
                                :before-change="() => beforeChange1(row)"
                            />
                        </template>
                    </vxe-column>
                    <vxe-column field="sort" width="80" title="排序">
                      
                    </vxe-column>
                    <vxe-column field="startTime" title="操作" width="150">
                        <template #default="{ row }">
                            <el-button type="primary" link size="small" @click="edit(row)" v-if="!(!hasAdmin && row.scope)">
                                编辑
                            </el-button>

                            <el-button type="danger" link size="small" @click="deletes(row)" v-if="!(!hasAdmin && row.scope)">
                                删除
                            </el-button>
                            <el-button type="info" link size="small"  v-if="(!hasAdmin && row.scope)">
                                管理员分配页面
                            </el-button>
                        </template>
                    </vxe-column>
                </vxe-table>
            </div>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { defaultAttribute } from '@/components/table/defaultAttribute'
import { getDashboardPageByUserId, deleteDashboard, activatePage, scopePage } from '@/api/system-boot/csstatisticalset'
import { useAdminInfo } from '@/stores/adminInfo'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useNavTabs } from '@/stores/navTabs'
import { getMenu } from '@/utils/router'

const { push } = useRouter()

const dialogVisible = ref(false)
const route = useRouter()
const navTabs = useNavTabs()
const adminInfo = useAdminInfo()
const pageList: any = ref([])
const hasAdmin = adminInfo.roleCode.some(item => item.includes('operation_manager') || item.includes('root'))||
    adminInfo.userType == 1

const open = () => {
    dialogVisible.value = true
    init()
}
const init = () => {
    getDashboardPageByUserId({ id: adminInfo.id, state: false }).then(res => {
        pageList.value = res.data.filter(item => {
            item.scope = item.userId == '0' ? 1 : 0
            return item
        })
    })
}
// 新增
const add = () => {
    push(`/admin/cockpit/popup?path=${String(getNextPagePath(pageList.value))}`)
}
// 修改
const edit = (row: any) => {
    push(`/admin/cockpit/popup?id=${row?.id}&&path=${row.pagePath}`)
}
// 激活
const beforeChange = (row: any): Promise<boolean> => {
    return new Promise(resolve => {
        // setTimeout(() => {
        //     loading1.value = false
        //     ElMessage.success('Switch success')
        //     return resolve(true)
        // }, 1000)
        ElMessageBox.confirm('此操作将激活该页面, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
            .then(() => {
                activatePage({ id: row.id, state: row.state == 0 ? 1 : 0 }).then(async (res: any) => {
                    if (res.code == 'A0000') {
                        ElMessage({
                            type: 'success',
                            message: '操作成功!'
                        })
                    }
                    init()
                    resolve(true)
                    await getMenu()
                    await setTimeout(() => {
                        navTabs.refresh()
                    }, 1000)
                })
            })
            .catch(() => {})
    })
}
// 全局
const beforeChange1 = (row: any): Promise<boolean> => {
    return new Promise(resolve => {
        // setTimeout(() => {
        //     loading1.value = false
        //     ElMessage.success('Switch success')
        //     return resolve(true)
        // }, 1000)
        ElMessageBox.confirm('此操作将页面配置成全局, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
            .then(() => {
                scopePage({ id: row.id, userId: row.scope == 0 ? '0' : adminInfo.id }).then(async (res: any) => {
                    if (res.code == 'A0000') {
                        ElMessage({
                            type: 'success',
                            message: '操作成功!'
                        })
                    }
                    init()
                    resolve(true)
                    await getMenu()
                    await setTimeout(() => {
                        navTabs.refresh()
                    }, 1000)
                })
            })
            .catch(() => {})
    })
}
// 删除
const deletes = (row: any) => {
    ElMessageBox.confirm('此操作将永久删除该菜单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(() => {
            deleteDashboard({ id: row.id }).then((res: any) => {
                if (res.code == 'A0000') {
                    ElMessage({
                        type: 'success',
                        message: '删除页面成功!'
                    })
                }
                init()
                getMenu()
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消删除'
            })
        })
}
function getNextPagePath(pages: any) {
    // 提取所有pagePath中的数字部分
    const numbers = pages.map((page: any) => {
        const match = page.pagePath.match(/dashboard\/index(\d*)$/)
        if (match && match[1]) {
            return parseInt(match[1], 10)
        }
        return 0 // 没有数字时视为0
    })

    // 找到最大数字并加1
    const maxNum = Math.max(...numbers)
    const nextNum = maxNum + 1

    // 生成下一个pagePath
    return `dashboard/index${nextNum}`
}

defineExpose({ open })
</script>
<style lang="scss" scoped></style>
