<script setup>
    import { ref, onMounted,computed } from 'vue'
    import { Menu, Lock, User, Grid, Setting } from '@element-plus/icons-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 systemParams = ref({
    name: '',
    version: '',
    apiBaseUrl: '',
    autoLogoutTime: 1800,
    cacheTime: 3600,
    debug: false
})

const accountSecurity = ref({
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
})

const teamMember = ref({
    name: '',
    role: 0,
    password: ''
})

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

    const appModules = {
        installedCount: 0,
        modules: [
            {
                name: 'Inquiry',
                title: '询价单',
                icon: 'el-icon-s-order',
                path: '/inquiry',
                children: [
                    {
                        name: 'InquiryList',
                        title: '询价单',
                        icon: 'el-icon-s-order',
                        path: '/inquiry/list'
                    },
                    {   name: 'InquiryCreate',
                        title: '新建询价单',
                        icon: 'el-icon-plus',             
                        path: '/inquiry/create'
                    },
                    {
                        name: 'InquiryDetail',
                        title: '询价单详情',
                        icon: 'el-icon-s-order',
                        path: '/inquiry/detail'
                    }
                ]
            },
            {
                name: 'Inquiry',
                title: '询价单',
                icon: 'el-icon-s-order',    
            }
        ]
    }

    const menuSettings = {
    menuTree: [],
    currentMenu: null,
    isEditing: false,
    menuOptions: []
}

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 handleAnchorClick = (e) => {
    e.preventDefault()
}
// 注销登出
const logout = () => {
    userStore.clearInfo()
    removeToken()
    router.push('/login')
}

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

</script>
<template>
  <div class="setup-container">
    <el-card class="setup-card">
      <template #header>
        <div class="card-header">
          <span>系统设置</span>
          <div class="header-actions">
            <el-button type="primary" @click="saveSettings">保存设置</el-button>
            <el-button @click="resetSettings">重置设置</el-button>
          </div>
        </div>
      </template>

      <el-row class="setup-content">
        <!-- 左侧锚点导航 -->
        <el-col :span="6" class="anchor-container">
          <el-anchor :bounds="100" :offset-top="100" @click="handleAnchorClick">
            <el-anchor-link href="#system-params" title="系统参数">
              <template #icon><el-icon><Setting /></el-icon></template>
            </el-anchor-link>
            <el-anchor-link href="#app-modules" title="应用模块">
              <template #icon><el-icon><Grid /></el-icon></template>
            </el-anchor-link>
            <el-anchor-link href="#menu-settings" title="菜单设置">
              <template #icon><el-icon><Menu /></el-icon></template>
            </el-anchor-link>
            <el-anchor-link href="#account-security" title="账号安全">
              <template #icon><el-icon><Lock /></el-icon></template>
            </el-anchor-link>
            <el-anchor-link href="#team-members" title="成员团队">
              <template #icon><el-icon><User /></el-icon></template>
            </el-anchor-link>
          </el-anchor>
        </el-col>

        <!-- 右侧设置内容 -->
        <el-col :span="18" class="settings-content">
          <!-- 系统参数 -->
          <div id="system-params" class="setting-section">
            <h2>系统参数</h2>
            <el-divider />
            <div class="h-320px">系统参数</div>
            <!-- <el-form label-width="180px">
              <el-form-item label="系统名称">
                <el-input v-model="systemParams.name" placeholder="请输入系统名称"></el-input>
              </el-form-item>
              <el-form-item label="系统版本">
                <el-input v-model="systemParams.version" placeholder="请输入系统版本"></el-input>
              </el-form-item>
              <el-form-item label="API基础地址">
                <el-input v-model="systemParams.apiBaseUrl" placeholder="请输入API基础地址"></el-input>
              </el-form-item>
              <el-form-item label="自动登出时间">
                <el-input-number
                  v-model="systemParams.autoLogoutTime"
                  :min="300"
                  :max="7200"
                  :step="300"
                ></el-input-number>
                <span class="form-item-hint">秒</span>
              </el-form-item>
              <el-form-item label="数据缓存时间">
                <el-input-number
                  v-model="systemParams.cacheTime"
                  :min="60"
                  :max="3600"
                  :step="60"
                ></el-input-number>
                <span class="form-item-hint">秒</span>
              </el-form-item>
              <el-form-item label="调试模式">
                <el-switch v-model="systemParams.debug"></el-switch>
              </el-form-item>
            </el-form> -->
          </div>

          <!-- 应用模块 -->
          <div id="app-modules" class="setting-section">
            <h2>应用模块</h2>
            <el-divider />
            <el-descriptions border>
              <el-descriptions-item label="已安装模块" :span="3">
                {{ 'appModules.installedCount' }} 个模块
              </el-descriptions-item>
            </el-descriptions>
            <div class="h-420px"></div>
            <!-- <el-table :data="appModules.modules" style="width: 100%; margin-top: 20px;">
              <el-table-column prop="name" label="模块名称" width="180" />
              <el-table-column prop="version" label="版本" width="120" />
              <el-table-column prop="description" label="描述" />
              <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                  <el-tag :type="scope.row.status === '启用' ? 'success' : 'info'">
                    {{ scope.row.status }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200">
                <template #default="scope">
                  <el-button
                    size="small"
                    :type="scope.row.status === '启用' ? 'danger' : 'success'"
                    @click="toggleModuleStatus(scope.row)"
                  >
                    {{ scope.row.status === '启用' ? '禁用' : '启用' }}
                  </el-button>
                  <el-button
                    size="small"
                    type="primary"
                    @click="updateModule(scope.row)"
                  >
                    更新
                  </el-button>
                </template>
              </el-table-column>
            </el-table> -->

            <div class="module-actions">
              <el-button type="primary" @click="installNewModule">安装新模块</el-button>
              <el-button @click="refreshModules">刷新模块列表</el-button>
            </div>
          </div>

          <!-- 菜单设置 -->
          <div id="menu-settings" class="setting-section">
            <h2>菜单设置</h2>
            <el-divider />
            <div class="menu-config">
              <div class="menu-tree">
                <h3>菜单结构</h3>
                <div class="h-240px"></div>
                <!-- <el-tree
                  :data="menuSettings.menuTree"
                  node-key="id"
                  default-expand-all
                  draggable
                  :allow-drop="allowDrop"
                  @node-drag-end="handleDragEnd"
                >
                  <template #default="{ node, data }">
                    <div class="custom-tree-node">
                      <span>
                        <el-icon v-if="data.icon"><component :is="data.icon" /></el-icon>
                        {{ data.label }}
                      </span>
                      <span>
                        <el-button
                          size="small"
                          @click="editMenu(data)"
                        >
                          编辑
                        </el-button>
                        <el-button
                          size="small"
                          type="danger"
                          @click="removeMenu(node, data)"
                        >
                          删除
                        </el-button>
                      </span>
                    </div>
                  </template>
                </el-tree> -->
                <div class="menu-actions">
                  <el-button type="primary" @click="addMenu">添加菜单项</el-button>
                </div>
              </div>
              <!-- <div class="menu-form" v-if="menuSettings.currentMenu">
                <h3>{{ menuSettings.isEditing ? '编辑菜单' : '添加菜单' }}</h3>
                <el-form label-width="100px">
                  <el-form-item label="菜单名称">
                    <el-input v-model="menuSettings.currentMenu.label"></el-input>
                  </el-form-item>
                  <el-form-item label="图标">
                    <el-select v-model="menuSettings.currentMenu.icon" placeholder="选择图标">
                      <el-option label="首页" value="HomeFilled" />
                      <el-option label="设置" value="Setting" />
                      <el-option label="用户" value="User" />
                      <el-option label="文档" value="Document" />
                      <el-option label="消息" value="ChatDotRound" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="路径">
                    <el-input v-model="menuSettings.currentMenu.path"></el-input>
                  </el-form-item>
                  <el-form-item label="父级菜单">
                    <el-cascader
                      v-model="menuSettings.currentMenu.parentId"
                      :options="menuSettings.menuOptions"
                      :props="{ checkStrictly: true }"
                      clearable
                    />
                  </el-form-item>
                  <el-form-item label="排序">
                    <el-input-number v-model="menuSettings.currentMenu.order" :min="0"></el-input-number>
                  </el-form-item>
                  <el-form-item label="是否显示">
                    <el-switch v-model="menuSettings.currentMenu.visible"></el-switch>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="saveMenu">保存</el-button>
                    <el-button @click="cancelMenu">取消</el-button>
                  </el-form-item>
                </el-form>
              </div> -->
            </div>
          </div>

          <!-- 账号安全 -->
          <div id="account-security" class="setting-section">
            <h2>账号安全</h2>
            <el-divider />
            <div class="h-320px">账号</div>
            <!-- <el-tabs v-model="securityActiveTab">
              <el-tab-pane label="密码设置" name="password">
                <el-form label-width="180px">
                  <el-form-item label="当前密码">
                    <el-input
                      v-model="accountSecurity.currentPassword"
                      type="password"
                      placeholder="请输入当前密码"
                      show-password
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="新密码">
                    <el-input
                      v-model="accountSecurity.newPassword"
                      type="password"
                      placeholder="请输入新密码"
                      show-password
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="确认新密码">
                    <el-input
                      v-model="accountSecurity.confirmPassword"
                      type="password"
                      placeholder="请再次输入新密码"
                      show-password
                    ></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="changePassword">修改密码</el-button>
                  </el-form-item>
                </el-form>
              </el-tab-pane>
              <el-tab-pane label="安全设置" name="security">
                <el-form label-width="180px">
                  <el-form-item label="双因素认证">
                    <el-switch v-model="accountSecurity.twoFactorAuth"></el-switch>
                    <span class="form-item-hint">启用后，登录时需要输入手机验证码</span>
                  </el-form-item>
                  <el-form-item label="登录通知">
                    <el-switch v-model="accountSecurity.loginNotification"></el-switch>
                    <span class="form-item-hint">启用后，每次登录都会发送通知</span>
                  </el-form-item>
                  <el-form-item label="异地登录保护">
                    <el-switch v-model="accountSecurity.locationProtection"></el-switch>
                    <span class="form-item-hint">启用后，异地登录需要额外验证</span>
                  </el-form-item>
                  <el-form-item label="密码过期时间">
                    <el-select v-model="accountSecurity.passwordExpiration">
                      <el-option label="永不过期" value="never" />
                      <el-option label="30天" value="30days" />
                      <el-option label="60天" value="60days" />
                      <el-option label="90天" value="90days" />
                    </el-select>
                  </el-form-item>
                </el-form>
              </el-tab-pane>
              <el-tab-pane label="登录历史" name="history">
                <el-table :data="accountSecurity.loginHistory" style="width: 100%">
                  <el-table-column prop="time" label="登录时间" width="180" />
                  <el-table-column prop="ip" label="IP地址" width="180" />
                  <el-table-column prop="location" label="登录地点" />
                  <el-table-column prop="device" label="设备" />
                  <el-table-column prop="status" label="状态" width="100">
                    <template #default="scope">
                      <el-tag :type="scope.row.status === '成功' ? 'success' : 'danger'">
                        {{ scope.row.status }}
                      </el-tag>
                    </template>
                  </el-table-column>
                </el-table>
              </el-tab-pane>
            </el-tabs> -->
          </div>

          <!-- 成员团队 -->
          <div id="team-members" class="setting-section">
            <h2>成员团队</h2>
            <el-divider />
            <div class="h-320px">团队</div>
            <!-- <el-tabs v-model="teamActiveTab">
              <el-tab-pane label="团队成员" name="members">
                <div class="search-bar">
                  <el-input
                    v-model="teamMembers.searchKeyword"
                    placeholder="搜索成员"
                    prefix-icon="Search"
                    clearable
                    @input="searchMembers"
                  ></el-input>
                  <el-button type="primary" @click="addMember">添加成员</el-button>
                </div>
                <el-table :data="teamMembers.filteredMembers" style="width: 100%">
                  <el-table-column prop="name" label="姓名" width="120" />
                  <el-table-column prop="email" label="邮箱" width="200" />
                  <el-table-column prop="role" label="角色" width="120">
                    <template #default="scope">
                      <el-tag :type="getRoleTagType(scope.row.role)">
                        {{ scope.row.role }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="department" label="部门" />
                  <el-table-column prop="status" label="状态" width="100">
                    <template #default="scope">
                      <el-tag :type="scope.row.status === '活跃' ? 'success' : 'info'">
                        {{ scope.row.status }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="200">
                    <template #default="scope">
                      <el-button
                        size="small"
                        @click="editMember(scope.row)"
                      >
                        编辑
                      </el-button>
                      <el-button
                        size="small"
                        type="danger"
                        @click="removeMember(scope.row)"
                      >
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-tab-pane>
              <el-tab-pane label="团队管理" name="teams">
                <div class="team-list">
                  <div class="team-header">
                    <h3>团队列表</h3>
                    <el-button type="primary" size="small" @click="addTeam">新建团队</el-button>
                  </div>
                  <el-collapse v-model="teamMembers.activeTeams">
                    <el-collapse-item
                      v-for="team in teamMembers.teams"
                      :key="team.id"
                      :title="team.name"
                      :name="team.id"
                    >
                      <div class="team-info">
                        <p><strong>创建时间：</strong>{{ team.createdAt }}</p>
                        <p><strong>团队描述：</strong>{{ team.description }}</p>
                        <p><strong>成员数量：</strong>{{ team.members.length }}</p>
                      </div>
                      <div class="team-members-list">
                        <el-tag
                          v-for="member in team.members"
                          :key="member.id"
                          closable
                          @close="removeTeamMember(team, member)"
                        >
                          {{ member.name }}
                        </el-tag>
                        <el-button size="small" @click="addTeamMember(team)">添加成员</el-button>
                      </div>
                      <div class="team-actions">
                        <el-button size="small" @click="editTeam(team)">编辑团队</el-button>
                        <el-button size="small" type="danger" @click="removeTeam(team)">删除团队</el-button>
                      </div>
                    </el-collapse-item>
                  </el-collapse>
                </div>
              </el-tab-pane>
              <el-tab-pane label="权限设置" name="permissions">
                <el-table :data="teamMembers.roles" style="width: 100%">
                  <el-table-column prop="name" label="角色名称" width="150" />
                  <el-table-column prop="description" label="描述" />
                  <el-table-column label="权限" width="400">
                    <template #default="scope">
                      <el-checkbox-group v-model="scope.row.permissions">
                        <el-checkbox label="read">查看</el-checkbox>
                        <el-checkbox label="create">创建</el-checkbox>
                        <el-checkbox label="update">编辑</el-checkbox>
                        <el-checkbox label="delete">删除</el-checkbox>
                        <el-checkbox label="export">导出</el-checkbox>
                        <el-checkbox label="import">导入</el-checkbox>
                        <el-checkbox label="admin">管理</el-checkbox>
                      </el-checkbox-group>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="150">
                    <template #default="scope">
                      <el-button
                        size="small"
                        @click="editRole(scope.row)"
                      >
                        编辑
                      </el-button>
                      <el-button
                        size="small"
                        type="danger"
                        @click="removeRole(scope.row)"
                        :disabled="scope.row.isDefault"
                      >
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <div class="role-actions">
                  <el-button type="primary" @click="addRole">添加角色</el-button>
                </div>
              </el-tab-pane>
            </el-tabs> -->
          </div>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>