<template>
    <div class="settings-container">
        <el-card class="settings-card">
            <template #header>
                <div class="card-header">
                    <span>系统配置</span>
                    <div class="header-actions">
                        <el-button type="primary" @click="saveSettings">保存配置</el-button>
                        <el-button type="danger" @click="logout">注销退出</el-button>
                    </div>
                </div>
            </template>

            <el-tabs v-model="activeTab">
                <!-- 系统配置 -->
                <el-tab-pane label="系统配置" name="system">
                    <el-form label-width="120px">
                        <el-form-item label="系统标题">
                            <el-input v-model="settings.title" placeholder="请输入系统标题"></el-input>
                        </el-form-item>
                        <el-form-item label="API基础地址">
                            <el-input v-model="settings.apiBaseUrl" placeholder="请输入API基础地址"></el-input>
                        </el-form-item>
                        <el-form-item label="自动登出时间">
                            <el-input-number
                                v-model="settings.autoLogoutTime"
                                :min="300"
                                :max="7200"
                                :step="300"
                            ></el-input-number>
                            <span class="form-item-hint">秒</span>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>

                <!-- 界面配置 -->
                <el-tab-pane label="界面配置" name="ui">
                    <el-form label-width="120px">
                        <el-form-item label="Logo路径">
                            <el-input v-model="settings.logoPath" placeholder="请输入Logo路径"></el-input>
                        </el-form-item>
                        <el-form-item label="菜单收起宽度">
                            <el-input-number
                                v-model="settings.collapsedWidth"
                                :min="40"
                                :max="100"
                                :step="10"
                            ></el-input-number>
                            <span class="form-item-hint">像素</span>
                        </el-form-item>
                        <el-form-item label="菜单展开宽度">
                            <el-input-number
                                v-model="settings.expandedWidth"
                                :min="160"
                                :max="300"
                                :step="20"
                            ></el-input-number>
                            <span class="form-item-hint">像素</span>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>

                <!-- 工作组 -->
                <el-tab-pane label="工作组" name="group" v-if="userStore.userInfo.role <= 1">
                    <el-row v-for="(group, index) in userStore.user_groups" :key="index" class="mb-4">
                        <el-col :span="6">
                            <div class="w-full flex items-center justify-end px-4">
                                <span>{{ group.name }}</span>
                                <el-button type="danger" size="small" circle class="ml-2" @click="userStore.user_groups.splice(index,1)"><i class="fa fa-close"></i></el-button>
                            </div>
                        </el-col>
                        <el-col :span="18">
                            <el-select v-model="group.member" multiple placeholder="请选择工作组" @change="changeGroup(index,group.name,group.member)">
                                <el-option
                                    v-for="group in userGroups"
                                    :key="group.id"
                                    :label="group.name"
                                    :value="group.id"
                                ></el-option>
                            </el-select>
                        </el-col>
                    </el-row>
                    <el-form inline class="mt-6">
                        <el-form-item>
                            <el-input v-model="groupName" placeholder="请输入工作组名称"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="addGroup">新建工作组</el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>

                <!-- 其他配置 -->
                <el-tab-pane label="其他配置" name="other">
                    <el-form label-width="120px">
                        <el-form-item label="调试模式">
                            <el-switch v-model="settings.debug"></el-switch>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
            </el-tabs>
        </el-card>
    </div>
</template>

<script setup>
import { ref, onMounted,computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store'
import { updateAthority } from '@/api'
import { removeToken } from '@/utils'
import { ElMessage } from 'element-plus'
import * as envUtils from '@/utils/env'

// 当前激活的标签页
const activeTab = ref('system')
const router = useRouter()
const userStore = useUserStore()

// 配置数据
const settings = ref({
    title: '',
    apiBaseUrl: '',
    autoLogoutTime: 1800,
    logoPath: '',
    collapsedWidth: 60,
    expandedWidth: 200,
    debug: false
})

const groupName = ref('')
const addGroup = async () => {
    let name = groupName.value.trim()
    if (!name || name.length < 2) { // || userStore.user_groups.findIndex(name) >= 0
        ElMessage.warning('工作组名称至少两个字，且不能重复！')
        return
    }
    userStore.newUserGroup(name)
    await updateAthority(userStore.user_id,userStore.user_groups)
    groupName.value = ''
    ElMessage.success('工作组添加成功，请刷新页面查看')
}

const changeGroup = async (idx,name,member=[]) => {
    await updateAthority(userStore.user_id,userStore.user_groups)
    // userStore.editUserGroup(idx,name,member)
}

// 加载配置
const loadSettings = () => {
    settings.value = {
        title: envUtils.getRuntimeConfig('VITE_APP_TITLE', envUtils.getAppTitle()),
        apiBaseUrl: envUtils.getRuntimeConfig('VITE_APP_API_BASE_URL', envUtils.getApiBaseUrl()),
        autoLogoutTime: envUtils.getRuntimeConfig('VITE_APP_AUTO_LOGOUT_TIME', envUtils.getAutoLogoutTime()),
        logoPath: envUtils.getRuntimeConfig('VITE_APP_LOGO_PATH', envUtils.getLogoPath()),
        collapsedWidth: envUtils.getRuntimeConfig('VITE_APP_COLLAPSED_WIDTH', envUtils.getCollapsedWidth()),
        expandedWidth: envUtils.getRuntimeConfig('VITE_APP_EXPANDED_WIDTH', envUtils.getExpandedWidth()),
        debug: envUtils.getRuntimeConfig('VITE_APP_DEBUG', envUtils.isDebug())
    }
}

// 保存配置
const saveSettings = () => {
    // 保存所有配置项
    envUtils.setRuntimeConfig('VITE_APP_TITLE', settings.value.title)
    envUtils.setRuntimeConfig('VITE_APP_API_BASE_URL', settings.value.apiBaseUrl)
    envUtils.setRuntimeConfig('VITE_APP_AUTO_LOGOUT_TIME', settings.value.autoLogoutTime)
    envUtils.setRuntimeConfig('VITE_APP_LOGO_PATH', settings.value.logoPath)
    envUtils.setRuntimeConfig('VITE_APP_COLLAPSED_WIDTH', settings.value.collapsedWidth)
    envUtils.setRuntimeConfig('VITE_APP_EXPANDED_WIDTH', settings.value.expandedWidth)
    envUtils.setRuntimeConfig('VITE_APP_DEBUG', settings.value.debug)

    ElMessage.success('配置保存成功')
}

const userGroups = computed(() => {
    return Object.values(userStore.teamInfo).filter(member => member.role > userStore.userInfo.role)
})
// 注销登出
const logout = () => {
    userStore.clearInfo()
    removeToken()
    router.push('/login')
}

// 组件挂载时加载配置
onMounted(() => {
    loadSettings()
})
</script>

<style lang="scss" scoped>
.settings-container {
    padding: 20px;

    .settings-card {
        max-width: 800px;
        margin: 0 auto;

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .header-actions {
                display: flex;
                gap: 10px;
            }
        }

        .form-item-hint {
            margin-left: 10px;
            color: #909399;
        }
    }
}
</style>