<template>
  <div class="user-list-container">
    <div class="header">
      <div class="header-left">
        <h2>用户管理</h2>
      </div>
      <div class="header-actions">
        <el-input 
            v-model="searchQuery" 
            placeholder="搜索手机/姓名/英文名" 
            style="width: 240px"
            clearable
            @clear="fetchUsers"
            @keyup.enter="handleSearch"
        >
            <template #append>
              <el-button :icon="Search" @click="handleSearch" />
            </template>
        </el-input>

        <el-select v-model="statusFilter" placeholder="状态筛选" clearable @change="handleSearch" style="width: 120px">
          <el-option label="待审核" value="PENDING" />
          <el-option label="正常" value="ACTIVE" />
          <el-option label="已禁用" value="DISABLED" />
        </el-select>
        <el-select v-model="roleFilter" placeholder="角色筛选" clearable @change="handleSearch" style="width: 140px">
          <el-option label="普通用户" value="ORDINARY_USER" />
          <el-option label="开发者" value="DEVELOPER" />
          <el-option label="管理员" value="SUPER_ADMIN" />
        </el-select>
        <el-select
          v-model="organizationFilter"
          placeholder="组织筛选"
          clearable
          @change="handleSearch"
          style="width: 180px"
        >
          <el-option label="未分配" :value="0" />
          <el-option v-for="o in orgList" :key="o.id" :label="o.name" :value="o.id" />
        </el-select>
        
        <el-divider direction="vertical" class="action-divider" />
        
        <el-button type="primary" @click="fetchUsers" circle>
          <el-icon><Refresh /></el-icon>
        </el-button>
        <el-button type="success" @click="handleCreateUser">
          <el-icon style="margin-right: 4px"><Plus /></el-icon> 新增用户
        </el-button>
        <el-button type="primary" plain @click="showImportDialog = true">
          <el-icon style="margin-right: 4px"><Upload /></el-icon> Excel导入
        </el-button>
        <el-button type="warning" plain @click="handleBatchResetClick" :disabled="selectedUsers.length === 0">
          <el-icon style="margin-right: 4px"><EditPen /></el-icon> 批量重置英文名
        </el-button>
        <el-button
          v-if="isSuperAdmin"
          type="primary"
          plain
          @click="openBatchOrgDialog"
          :disabled="selectedUsers.length === 0"
        >
          批量设置组织
        </el-button>
        <el-button v-if="isSuperAdmin" plain @click="openOrgManageDialog">组织管理</el-button>
        <el-button @click="openLogDrawer">
          <el-icon style="margin-right: 4px"><List /></el-icon> 操作日志
        </el-button>
      </div>
    </div>

    <el-table 
        :data="users" 
        v-loading="loading" 
        stripe 
        border 
        style="width: 100%"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="mobile" label="手机号" min-width="120" />
      <el-table-column prop="name" label="姓名" min-width="100" />
      <el-table-column prop="english_name" label="英文名" min-width="120" />
      <el-table-column prop="organization_name" label="所属组织" min-width="120">
        <template #default="scope">
          {{ scope.row.organization_name || '—' }}
        </template>
      </el-table-column>
      <el-table-column prop="role" label="角色" width="120" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.role === 'SUPER_ADMIN' ? 'danger' : (scope.row.role === 'DEVELOPER' ? 'warning' : 'info')">
            {{ getRoleLabel(scope.row.role) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="注册时间" min-width="180">
        <template #default="scope">
          {{ formatDate(scope.row.created_at) }}
        </template>
      </el-table-column>
      
      <el-table-column label="操作" fixed="right" width="220">
        <template #default="scope">
          <div class="action-buttons">
            <!-- Allow Edit for everyone, including Super Admin -->
            <el-button type="primary" link @click="handleEditUser(scope.row)">编辑</el-button>

            <!-- 非超管或 ID>1 超管：审核/禁用/更多；ID=1 超管仅「重置密码」 -->
            <template v-if="scope.row.role !== 'SUPER_ADMIN' || scope.row.id > 1">
                <el-divider direction="vertical" />
                
                <!-- PENDING Actions -->
                <template v-if="scope.row.status === 'PENDING'">
                  <el-button type="primary" link @click="handleStatus(scope.row, 'ACTIVE')">通过</el-button>
                  <el-divider direction="vertical" />
                  <el-button type="primary" link @click="handleStatus(scope.row, 'DISABLED')">拒绝</el-button>
                </template>
                
                <!-- ACTIVE Actions -->
                <template v-if="scope.row.status === 'ACTIVE'">
                  <el-button type="primary" link @click="handleStatus(scope.row, 'DISABLED')">禁用</el-button>
                </template>
                
                <!-- DISABLED Actions -->
                <template v-if="scope.row.status === 'DISABLED'">
                  <el-button type="primary" link @click="handleStatus(scope.row, 'ACTIVE')">启用</el-button>
                </template>

                <el-divider direction="vertical" />
                <el-dropdown trigger="click">
                    <span class="el-dropdown-link">
                      更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item 
                            @click="handleChangeRole(scope.row)"
                        >
                            变更角色
                        </el-dropdown-item>
                        <el-dropdown-item 
                            @click="handleResetPassword(scope.row)"
                        >
                            重置密码
                        </el-dropdown-item>
                        <el-dropdown-item
                            v-if="isSuperAdmin && scope.row.role === 'ORDINARY_USER'"
                            class="danger-dropdown-item"
                            @click="openDeleteUserDialog(scope.row)"
                        >
                            删除用户
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </template>
            <template v-else-if="isSuperAdmin && scope.row.role === 'SUPER_ADMIN' && scope.row.id <= 1">
                <el-divider direction="vertical" />
                <el-button type="primary" link @click="handleResetPassword(scope.row)">重置密码</el-button>
            </template>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- Change Role Dialog -->
    <el-dialog v-model="changeRoleDialogVisible" title="变更角色" width="400px">
        <p>变更用户 <strong>{{ roleTarget?.mobile }}</strong> 的角色。</p>
        
        <el-form :model="roleForm" label-position="top">
            <el-form-item label="选择角色">
                <el-select v-model="roleForm.role" style="width: 100%">
                    <el-option label="普通用户" value="ORDINARY_USER" />
                    <el-option label="开发者" value="DEVELOPER" />
                    <el-option label="超级管理员" value="SUPER_ADMIN" />
                </el-select>
            </el-form-item>
            <el-form-item label="管理员密码验证" required>
                <el-input 
                    v-model="roleForm.admin_password" 
                    type="password" 
                    show-password 
                    placeholder="请输入管理员密码" 
                    :name="dynamicPwdField"
                    autocomplete="new-password"
                />
            </el-form-item>
        </el-form>

        <template #footer>
            <el-button @click="changeRoleDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmChangeRole" :loading="changingRole">确认变更</el-button>
        </template>
    </el-dialog>

    <!-- Delete user (ordinary only): password + SMS -->
    <el-dialog v-model="deleteUserDialogVisible" title="删除用户" width="440px" @closed="resetDeleteUserForm">
        <p class="delete-hint">
            将软删除用户 <strong>{{ deleteTarget?.mobile }}</strong>（不可登录）。需验证您的登录密码与本人手机号短信验证码。
        </p>
        <p v-if="maskedAdminMobile" class="text-muted">验证码发送至：<strong>{{ maskedAdminMobile }}</strong></p>
        <el-form label-position="top" style="margin-top: 12px;">
            <el-form-item label="登录密码" required>
                <el-input
                    v-model="deleteUserForm.password"
                    type="password"
                    show-password
                    placeholder="请输入您的登录密码"
                    autocomplete="new-password"
                    :name="'del_pwd_' + dynamicPwdField"
                />
            </el-form-item>
            <el-form-item label="短信验证码" required>
                <div class="sms-row">
                    <el-input
                        v-model="deleteUserForm.sms_code"
                        placeholder="6 位验证码"
                        maxlength="6"
                        @keyup.enter="confirmDeleteUser"
                    />
                    <el-button
                        :disabled="deleteSmsCountdown > 0 || !adminMobile"
                        @click="sendDeleteUserSms"
                    >
                        {{ deleteSmsCountdown > 0 ? `${deleteSmsCountdown}s` : '获取验证码' }}
                    </el-button>
                </div>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="deleteUserDialogVisible = false">取消</el-button>
            <el-button type="danger" :loading="deletingUser" @click="confirmDeleteUser">确认删除</el-button>
        </template>
    </el-dialog>

    <!-- Admin Verify Dialog for Status/Reset -->
    <el-dialog v-model="verifyDialogVisible" title="安全验证" width="400px">
        <p>此操作需要验证管理员权限。</p>
        <p v-if="verifyTargetUser">操作对象: <strong>{{ verifyTargetUser.mobile }}</strong></p>
        
        <div style="margin-top: 20px;">
            <p style="margin-bottom: 10px;">管理员密码</p>
            <el-input 
                v-model="adminPasswordVerify" 
                type="password" 
                show-password 
                placeholder="请输入管理员密码"
                :name="dynamicPwdField"
                autocomplete="new-password"
                @keyup.enter="confirmVerify"
            />
        </div>

        <template #footer>
            <el-button @click="verifyDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmVerify" :loading="verifying">确认</el-button>
        </template>
    </el-dialog>

    <!-- Reset Password Dialog -->
    <el-dialog v-model="resetPasswordDialogVisible" title="重置密码成功" width="400px">
      <div style="text-align: center;">
        <p>用户 <b>{{ resetPasswordUserMobile }}</b> 的新密码为：</p>
        <div style="margin: 20px 0; font-size: 24px; font-weight: bold; color: #409EFF; background: #f4f4f5; padding: 10px; border-radius: 4px;">
          {{ newPassword }}
        </div>
        <p style="color: #f56c6c; font-size: 12px;">请立即复制并保存，此密码只显示一次！</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="copyPassword">复制密码</el-button>
          <el-button type="primary" @click="resetPasswordDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- Batch set organization -->
    <el-dialog v-model="batchOrgDialogVisible" title="批量设置组织" width="440px">
      <p style="margin-bottom: 12px; color: #606266">
        已选择 <strong>{{ selectedUsers.length }}</strong> 位用户；可选择组织或取消归属。
      </p>
      <el-form label-position="top">
        <el-form-item label="所属组织">
          <el-select v-model="batchOrgTargetId" clearable placeholder="不选择则表示取消归属" style="width: 100%">
            <el-option v-for="o in orgList" :key="o.id" :label="o.name" :value="o.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="管理员密码验证" required>
          <el-input
            v-model="batchOrgPassword"
            type="password"
            show-password
            placeholder="请输入管理员密码"
            autocomplete="new-password"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="batchOrgDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="batchOrgLoading" @click="confirmBatchOrg">确定</el-button>
      </template>
    </el-dialog>

    <!-- Organization CRUD (super admin) -->
    <el-dialog v-model="orgManageVisible" title="组织管理" width="640px" @open="loadOrgListForManage">
      <p class="text-muted" style="margin: 0 0 12px">组织创建后不可删除，仅可编辑；编辑时需验证图形验证码。</p>
      <div style="margin-bottom: 16px; display: flex; gap: 8px; flex-wrap: wrap; align-items: center">
        <el-input v-model="newOrgName" placeholder="新组织名称" style="width: 200px" clearable />
        <el-input v-model="newOrgDesc" placeholder="描述（可选）" style="width: 200px" clearable />
        <el-input-number v-model="newOrgSort" :min="0" placeholder="排序" style="width: 120px" />
        <el-button type="primary" :loading="orgCreating" @click="submitNewOrg">添加</el-button>
      </div>
      <el-table :data="orgList" v-loading="orgManageLoading" border stripe size="small" max-height="360">
        <el-table-column prop="id" label="ID" width="70" />
        <el-table-column prop="name" label="名称" min-width="120" />
        <el-table-column prop="description" label="描述" min-width="100" show-overflow-tooltip />
        <el-table-column prop="sort_order" label="排序" width="80" />
        <el-table-column label="操作" width="80" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="openEditOrg(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog v-model="editOrgVisible" title="编辑组织" width="480px" @opened="refreshEditOrgCaptcha">
      <p class="text-muted" style="margin-top: 0">请填写图形验证码以确认管理员身份。</p>
      <el-form label-width="88px">
        <el-form-item label="名称" required>
          <el-input v-model="editOrgForm.name" maxlength="100" show-word-limit />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="editOrgForm.description" type="textarea" rows="2" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="editOrgForm.sort_order" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="图形验证码" required class="captcha-item">
          <div class="captcha-row-edit">
            <el-input v-model="editOrgForm.captcha_code" placeholder="请输入右侧验证码" maxlength="10" />
            <div class="captcha-img" @click="refreshEditOrgCaptcha" v-if="editOrgCaptchaImage">
              <img :src="editOrgCaptchaImage" alt="captcha" />
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editOrgVisible = false">取消</el-button>
        <el-button type="primary" :loading="editOrgSubmitting" @click="submitEditOrg">保存</el-button>
      </template>
    </el-dialog>

    <!-- Batch Reset Dialog -->
    <el-dialog v-model="batchResetDialogVisible" title="批量重置英文名" width="400px">
        <div class="warning-text" style="margin-bottom: 20px; color: #e6a23c; display: flex; align-items: flex-start; gap: 8px;">
            <el-icon style="margin-top: 2px"><Warning /></el-icon>
            <span>
                将根据用户的姓名自动生成拼音英文名。如有重复将自动添加数字后缀。
                <br>
                已选择 <strong>{{ selectedUsers.length }}</strong> 位用户。
            </span>
        </div>
        
        <el-form label-position="top">
            <el-form-item label="管理员密码验证" required>
                <el-input 
                    v-model="batchAdminPassword" 
                    type="password" 
                    show-password 
                    placeholder="请输入管理员密码" 
                    :name="dynamicPwdField"
                    autocomplete="new-password"
                />
            </el-form-item>
        </el-form>

        <template #footer>
            <el-button @click="batchResetDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmBatchReset" :loading="batchResetting">确认重置</el-button>
        </template>
    </el-dialog>

    <!-- Create User Dialog -->
    <el-dialog v-model="createDialogVisible" title="新增用户" width="500px">
      <el-form :model="createForm" :rules="createRules" ref="createFormRef" label-width="100px">
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="createForm.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="createForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="英文名" prop="english_name">
          <el-input v-model="createForm.english_name" placeholder="请输入英文名（选填，自动生成拼音）" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="createForm.password" type="password" show-password placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="createForm.role" placeholder="请选择角色" style="width: 100%">
            <el-option label="普通用户" value="ORDINARY_USER" />
            <el-option label="开发者" value="DEVELOPER" />
            <el-option label="超级管理员" value="SUPER_ADMIN" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="isSuperAdmin" label="所属组织">
          <el-select v-model="createForm.organization_id" clearable placeholder="未分配" style="width: 100%">
            <el-option v-for="o in orgList" :key="o.id" :label="o.name" :value="o.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="管理员验证" prop="admin_password">
           <el-input 
                v-model="createForm.admin_password" 
                type="password" 
                show-password 
                placeholder="请输入管理员密码" 
                :name="dynamicPwdField"
                autocomplete="new-password"
            />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCreateUser" :loading="creating">确定</el-button>
      </template>
    </el-dialog>

    <!-- Edit User Dialog -->
    <el-dialog v-model="editDialogVisible" title="编辑用户信息" width="500px">
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px">
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="英文名" prop="english_name">
          <el-input v-model="editForm.english_name" placeholder="请输入英文名（选填，自动生成拼音）" />
        </el-form-item>
        <el-form-item v-if="isSuperAdmin" label="所属组织">
          <el-select v-model="editForm.organization_id" clearable placeholder="未分配" style="width: 100%">
            <el-option v-for="o in orgList" :key="o.id" :label="o.name" :value="o.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="管理员验证" prop="admin_password">
           <el-input 
                v-model="editForm.admin_password" 
                type="password" 
                show-password 
                placeholder="请输入管理员密码" 
                :name="dynamicPwdField"
                autocomplete="new-password"
            />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEditUser" :loading="editing">保存</el-button>
      </template>
    </el-dialog>

    <!-- Logs Drawer -->
    <el-drawer
        v-model="logDrawerVisible"
        title="操作日志"
        direction="rtl"
        size="60%"
    >
        <div class="log-filter" style="margin-bottom: 20px; display: flex; gap: 10px; flex-wrap: wrap;">
            <el-select v-model="logFilter.action_type" placeholder="操作类型" clearable style="width: 150px" @change="fetchLogsData">
                <el-option label="新增用户" value="MANUAL_ADD" />
                <el-option label="删除用户" value="DELETE" />
                <el-option label="更新信息" value="UPDATE" />
                <el-option label="禁用" value="DISABLE" />
                <el-option label="启用" value="ENABLE" />
                <el-option label="变更角色" value="CHANGE_ROLE" />
                <el-option label="重置密码" value="RESET_PASSWORD" />
                <el-option label="新建组织" value="ORG_CREATE" />
                <el-option label="编辑组织" value="ORG_UPDATE" />
            </el-select>
            <el-input 
                v-model="logFilter.keyword" 
                placeholder="搜索目标手机号" 
                style="width: 200px"
                clearable
                @clear="fetchLogsData"
                @keyup.enter="fetchLogsData"
            >
                <template #append>
                    <el-button :icon="Search" @click="fetchLogsData" />
                </template>
            </el-input>
             <el-date-picker
                v-model="logFilter.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                @change="fetchLogsData"
            />
            <el-button @click="fetchLogsData"><el-icon><Refresh /></el-icon></el-button>
        </div>

        <el-table :data="logList" v-loading="logLoading" stripe border style="width: 100%">
             <el-table-column prop="id" label="ID" width="80" />
             <el-table-column prop="operator_mobile" label="操作人" width="120" />
             <el-table-column prop="target_mobile" label="目标用户" width="120" />
             <el-table-column prop="action_type" label="操作类型" width="120">
                <template #default="scope">
                    {{ getActionLabel(scope.row.action_type) }}
                </template>
             </el-table-column>
             <el-table-column prop="ip_address" label="IP地址" width="130" />
             <el-table-column prop="created_at" label="时间" width="170">
                <template #default="scope">
                    {{ formatDate(scope.row.created_at) }}
                </template>
             </el-table-column>
             <el-table-column prop="details" label="详情" min-width="150">
                 <template #default="scope">
                     <el-tooltip effect="dark" placement="top">
                        <template #content>
                            <div style="max-width: 500px; max-height: 300px; overflow: auto; white-space: pre-wrap;">{{ JSON.stringify(scope.row.details, null, 2) }}</div>
                        </template>
                        <div style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-size: 12px; color: #666; cursor: pointer;">
                            {{ JSON.stringify(scope.row.details) }}
                        </div>
                     </el-tooltip>
                 </template>
             </el-table-column>
        </el-table>
        
        <div class="pagination" style="margin-top: 20px; display: flex; justify-content: flex-end;">
            <el-pagination
                v-model:current-page="logPage.current"
                v-model:page-size="logPage.size"
                :page-sizes="[10, 20, 50]"
                layout="total, sizes, prev, pager, next"
                :total="logPage.total"
                @size-change="handleLogSizeChange"
                @current-change="handleLogCurrentChange"
            />
        </div>
    </el-drawer>

    <UserImportDialog v-model="showImportDialog" @success="fetchUsers" />

  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, reactive, computed } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { Refresh, ArrowDown, Search, Plus, List, Upload, EditPen, Warning } from '@element-plus/icons-vue'
import api from '../utils/request'
import { getLogs, OperationLog } from '../api/logs'
import { sendSmsCode } from '../api/smsAuth'
import { deleteUserWithVerification, batchSetOrganization } from '../api/users'
import {
  getOrganizations,
  createOrganization,
  updateOrganization,
  type Organization,
} from '../api/organizations'
import { getCaptcha } from '../api/public'
import { useAuthStore } from '../store/auth'
import UserImportDialog from '../components/UserImportDialog.vue'

const authStore = useAuthStore()
const isSuperAdmin = computed(() => authStore.user?.role === 'SUPER_ADMIN')
const adminMobile = computed(() => (authStore.user?.mobile as string) || '')
const maskedAdminMobile = computed(() => {
    const m = adminMobile.value
    if (!m || m.length < 11) return ''
    return `${m.slice(0, 3)}****${m.slice(-4)}`
})

interface User {
  id: number
  mobile: string
  name?: string
  english_name?: string
  status: string
  role: string
  created_at: string
  organization_id?: number | null
  organization_name?: string | null
}

const users = ref<User[]>([])
const loading = ref(false)
const statusFilter = ref('')
const roleFilter = ref('')
const organizationFilter = ref<number | undefined>(undefined)
const searchQuery = ref('')

const orgList = ref<Organization[]>([])

const fetchOrganizations = async () => {
  try {
    const res = await getOrganizations()
    orgList.value = res.data || []
  } catch {
    orgList.value = []
  }
}

const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)


// Create User
const createDialogVisible = ref(false)
const showImportDialog = ref(false)
const creating = ref(false)
const createFormRef = ref<FormInstance>()
const createForm = reactive({
  mobile: '',
  name: '',
  english_name: '',
  password: '',
  role: 'ORDINARY_USER',
  admin_password: '',
  organization_id: null as number | null,
})

// Edit User Logic
const editDialogVisible = ref(false)
const editing = ref(false)
const editFormRef = ref<FormInstance>()
const editForm = reactive({
    id: 0,
    mobile: '',
    name: '',
    english_name: '',
    admin_password: '',
    organization_id: null as number | null,
})
const editRules = reactive<FormRules>({
    mobile: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
    ],
    name: [
        { required: true, message: '请输入姓名', trigger: 'blur' }
    ],
    admin_password: [
        { required: true, message: '请输入管理员密码验证', trigger: 'blur' }
    ]
})

const handleEditUser = (user: User) => {
    editForm.id = user.id
    editForm.mobile = user.mobile
    editForm.name = user.name || ''
    editForm.english_name = user.english_name || ''
    editForm.organization_id = user.organization_id ?? null
    editForm.admin_password = ''
    refreshDynamicField()
    editDialogVisible.value = true
}

const submitEditUser = async () => {
    if (!editFormRef.value) return
    await editFormRef.value.validate(async (valid) => {
        if (valid) {
            editing.value = true
            try {
                await api.put(`/users/${editForm.id}`, {
                    mobile: editForm.mobile,
                    name: editForm.name,
                    english_name: editForm.english_name,
                    organization_id: editForm.organization_id,
                    admin_password: editForm.admin_password
                })
                ElMessage.success('用户信息更新成功')
                editDialogVisible.value = false
                fetchUsers()
            } catch (e) {
                // handled
            } finally {
                editing.value = false
            }
        }
    })
}

// Dynamic Field Name logic
const dynamicPwdField = ref('admin_pwd_' + Date.now())
const refreshDynamicField = () => {
    dynamicPwdField.value = 'admin_pwd_' + Math.random().toString(36).slice(2)
}

const createRules = reactive<FormRules>({
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  admin_password: [
    { required: true, message: '请输入管理员密码验证', trigger: 'blur' }
  ]
})

const handleCreateUser = () => {
  createForm.mobile = ''
  createForm.name = ''
  createForm.english_name = ''
  createForm.password = ''
  createForm.role = 'ORDINARY_USER'
  createForm.admin_password = ''
  createForm.organization_id = null
  refreshDynamicField()
  createDialogVisible.value = true
}

const submitCreateUser = async () => {
  if (!createFormRef.value) return
  await createFormRef.value.validate(async (valid) => {
    if (valid) {
      creating.value = true
      try {
        await api.post('/users/', createForm)
        ElMessage.success('用户创建成功')
        createDialogVisible.value = false
        fetchUsers()
      } catch (e) {
        // handled
      } finally {
        creating.value = false
      }
    }
  })
}

const fetchUsers = async () => {
  loading.value = true
  try {
    const params: any = {
        skip: (currentPage.value - 1) * pageSize.value,
        limit: pageSize.value
    }
    if (statusFilter.value) params.status = statusFilter.value
    if (roleFilter.value) params.role = roleFilter.value
    if (searchQuery.value) params.keyword = searchQuery.value
    if (organizationFilter.value !== undefined) {
      params.organization_id = organizationFilter.value
    }
    
    const res = await api.get('/users/', { params })
    if (res.data && Array.isArray(res.data.items)) {
        users.value = res.data.items
        total.value = res.data.total
    } else if (Array.isArray(res.data)) {
        users.value = res.data
        total.value = res.data.length
    }
  } catch (e) {
    // handled
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
    currentPage.value = 1
    fetchUsers()
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchUsers()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchUsers()
}

const getStatusType = (status: string) => {
  switch(status) {
    case 'ACTIVE': return 'success'
    case 'PENDING': return 'warning'
    case 'DISABLED': return 'danger'
    default: return 'info'
  }
}

const getStatusLabel = (status: string) => {
    switch(status) {
        case 'ACTIVE': return '正常'
        case 'PENDING': return '待审核'
        case 'DISABLED': return '已禁用'
        default: return status
    }
}

const getRoleLabel = (role: string) => {
    switch(role) {
        case 'SUPER_ADMIN': return '超级管理员'
        case 'DEVELOPER': return '开发者'
        case 'ORDINARY_USER': return '普通用户'
        default: return role
    }
}

const formatDate = (dateStr: string) => {
    if (!dateStr) return ''
    return new Date(dateStr).toLocaleString()
}

const handleStatus = (user: User, newStatus: string) => {
    verifyTargetUser.value = user
    verifyNextStatus.value = newStatus
    verifyActionType.value = 'STATUS'
    adminPasswordVerify.value = ''
    refreshDynamicField()
    verifyDialogVisible.value = true
}

const doHandleStatus = async (user: User, newStatus: string, adminPwd: string) => {
  await api.put(`/users/${user.id}`, {
    status: newStatus,
    admin_password: adminPwd
  })
  ElMessage.success('状态已更新')
  fetchUsers()
}

// Verify Dialog Logic
const verifyDialogVisible = ref(false)
const adminPasswordVerify = ref('')
const verifyTargetUser = ref<User | null>(null)
const verifyActionType = ref('') // 'STATUS' | 'RESET'
const verifyNextStatus = ref('') 
const verifying = ref(false)

const confirmVerify = async () => {
    if (!adminPasswordVerify.value) {
        ElMessage.warning('请输入管理员密码')
        return
    }
    
    verifying.value = true
    try {
        if (verifyActionType.value === 'STATUS' && verifyTargetUser.value) {
            await doHandleStatus(verifyTargetUser.value, verifyNextStatus.value, adminPasswordVerify.value)
        } else if (verifyActionType.value === 'RESET' && verifyTargetUser.value) {
            await doHandleResetPassword(verifyTargetUser.value, adminPasswordVerify.value)
        }
        verifyDialogVisible.value = false
    } catch (e) {
        // handled
    } finally {
        verifying.value = false
    }
}

// Reset Password Logic
const resetPasswordDialogVisible = ref(false)
const newPassword = ref('')
const resetPasswordUserMobile = ref('')

const handleResetPassword = (user: User) => {
    verifyTargetUser.value = user
    verifyActionType.value = 'RESET'
    adminPasswordVerify.value = ''
    refreshDynamicField()
    verifyDialogVisible.value = true
}

const doHandleResetPassword = async (user: User, adminPwd: string) => {
  const res = await api.post('/simple/admin/reset-password', {
    user_id: user.id,
    admin_password: adminPwd
  })
  newPassword.value = res.data.new_password
  resetPasswordUserMobile.value = user.mobile
  resetPasswordDialogVisible.value = true
}

const copyPassword = async () => {
  try {
    await navigator.clipboard.writeText(newPassword.value)
    ElMessage.success('密码已复制到剪贴板')
  } catch (err) {
    ElMessage.error('复制失败，请手动复制')
  }
}

// Change Role Logic
const changeRoleDialogVisible = ref(false)
const roleTarget = ref<User | null>(null)
const changingRole = ref(false)
const roleForm = reactive({
    role: '',
    admin_password: ''
})

const handleChangeRole = (user: User) => {
    roleTarget.value = user
    roleForm.role = user.role
    roleForm.admin_password = ''
    refreshDynamicField()
    changeRoleDialogVisible.value = true
}

const confirmChangeRole = async () => {
    if (!roleTarget.value) return
    if (!roleForm.role) {
        ElMessage.warning('请选择角色')
        return
    }
    if (!roleForm.admin_password) {
        ElMessage.warning('请输入管理员密码')
        return
    }

    changingRole.value = true
    try {
        await api.put(`/users/${roleTarget.value.id}`, {
            role: roleForm.role,
            admin_password: roleForm.admin_password
        })
        ElMessage.success('角色变更成功')
        changeRoleDialogVisible.value = false
        fetchUsers()
    } catch (e) {
        // handled
    } finally {
        changingRole.value = false
    }
}

// Batch Reset Logic
const batchResetDialogVisible = ref(false)
const batchAdminPassword = ref('')
const batchResetting = ref(false)
const selectedUsers = ref<User[]>([])

const handleSelectionChange = (val: User[]) => {
    selectedUsers.value = val
}

const handleBatchResetClick = () => {
    if (selectedUsers.value.length === 0) {
        ElMessage.warning('请先选择用户')
        return
    }
    batchAdminPassword.value = ''
    refreshDynamicField()
    batchResetDialogVisible.value = true
}

const deleteUserDialogVisible = ref(false)
const deleteTarget = ref<User | null>(null)
const deletingUser = ref(false)
const deleteUserForm = reactive({
    password: '',
    sms_code: ''
})
const deleteSmsCountdown = ref(0)
let deleteSmsTimer: ReturnType<typeof setInterval> | null = null

const resetDeleteUserForm = () => {
    deleteTarget.value = null
    deleteUserForm.password = ''
    deleteUserForm.sms_code = ''
}

const openDeleteUserDialog = async (user: User) => {
    if (user.role !== 'ORDINARY_USER') return
    if (!authStore.user?.mobile) {
        try {
            await authStore.fetchUser()
        } catch {
            ElMessage.error('无法获取当前账号信息，请重新登录')
            return
        }
    }
    if (!adminMobile.value) {
        ElMessage.error('当前账号无手机号，无法发送验证码')
        return
    }
    deleteTarget.value = user
    deleteUserForm.password = ''
    deleteUserForm.sms_code = ''
    refreshDynamicField()
    deleteUserDialogVisible.value = true
}

const sendDeleteUserSms = async () => {
    if (!adminMobile.value) {
        ElMessage.warning('无法获取手机号')
        return
    }
    try {
        await sendSmsCode(adminMobile.value, 'pc')
        ElMessage.success('验证码已发送')
        deleteSmsCountdown.value = 60
        if (deleteSmsTimer) clearInterval(deleteSmsTimer)
        deleteSmsTimer = setInterval(() => {
            deleteSmsCountdown.value--
            if (deleteSmsCountdown.value <= 0 && deleteSmsTimer) {
                clearInterval(deleteSmsTimer)
                deleteSmsTimer = null
            }
        }, 1000)
    } catch {
        // interceptor
    }
}

const confirmDeleteUser = async () => {
    if (!deleteTarget.value) return
    if (!deleteUserForm.password) {
        ElMessage.warning('请输入登录密码')
        return
    }
    if (!deleteUserForm.sms_code) {
        ElMessage.warning('请输入短信验证码')
        return
    }
    deletingUser.value = true
    try {
        await deleteUserWithVerification(deleteTarget.value.id, {
            password: deleteUserForm.password,
            sms_code: deleteUserForm.sms_code
        })
        ElMessage.success('用户已删除')
        deleteUserDialogVisible.value = false
        fetchUsers()
    } catch {
        // interceptor
    } finally {
        deletingUser.value = false
    }
}

const confirmBatchReset = async () => {
    if (!batchAdminPassword.value) {
        ElMessage.warning('请输入管理员密码')
        return
    }
    
    batchResetting.value = true
    try {
        const res = await api.post('/users/batch/reset-english-name', {
            user_ids: selectedUsers.value.map(u => u.id),
            admin_password: batchAdminPassword.value
        })
        ElMessage.success(`操作成功，已重置 ${res.data.count} 位用户的英文名`)
        batchResetDialogVisible.value = false
        fetchUsers()
        selectedUsers.value = [] 
    } catch (e) {
        // handled
    } finally {
        batchResetting.value = false
    }
}


// Log Logic
const logDrawerVisible = ref(false)
const logLoading = ref(false)
const logList = ref<OperationLog[]>([])
const logFilter = reactive({
    action_type: '',
    keyword: '',
    dateRange: [] as string[]
})
const logPage = reactive({
    current: 1,
    size: 20,
    total: 0
})

const openLogDrawer = () => {
    logDrawerVisible.value = true
    fetchLogsData()
}

const fetchLogsData = async () => {
    logLoading.value = true
    try {
        const params: any = {
            skip: (logPage.current - 1) * logPage.size,
            limit: logPage.size,
            action_type: logFilter.action_type || undefined,
            keyword: logFilter.keyword || undefined,
        }
        if (logFilter.dateRange && logFilter.dateRange.length === 2) {
            params.start_date = logFilter.dateRange[0]
            params.end_date = logFilter.dateRange[1] + ' 23:59:59'
        }

        const res = await getLogs(params)
        logList.value = res.data.items
        logPage.total = res.data.total
    } catch (e) {
        // handled
    } finally {
        logLoading.value = false
    }
}

const handleLogSizeChange = (val: number) => {
    logPage.size = val
    fetchLogsData()
}

const handleLogCurrentChange = (val: number) => {
    logPage.current = val
    fetchLogsData()
}

const getActionLabel = (type: string) => {
    const map: Record<string, string> = {
        'MANUAL_ADD': '新增用户',
        'DELETE': '删除用户',
        'UPDATE': '更新信息',
        'IMPORT': '批量导入',
        'DISABLE': '禁用',
        'ENABLE': '启用',
        'RESET_PASSWORD': '重置密码',
        'CHANGE_ROLE': '变更角色',
        'SYNC_M2M': 'M2M 同步',
        'ORG_CREATE': '新建组织',
        'ORG_UPDATE': '编辑组织',
    }
    return map[type] || type
}

const batchOrgDialogVisible = ref(false)
const batchOrgTargetId = ref<number | undefined>(undefined)
const batchOrgPassword = ref('')
const batchOrgLoading = ref(false)

const orgManageVisible = ref(false)
const orgManageLoading = ref(false)
const newOrgName = ref('')
const newOrgDesc = ref('')
const newOrgSort = ref(0)
const orgCreating = ref(false)

const editOrgVisible = ref(false)
const editOrgSubmitting = ref(false)
const editOrgCaptchaImage = ref('')
const editOrgForm = reactive({
  id: 0,
  name: '',
  description: '',
  sort_order: 0,
  captcha_id: '',
  captcha_code: '',
})

const refreshEditOrgCaptcha = async () => {
  try {
    const res = await getCaptcha()
    editOrgCaptchaImage.value = res.data.image
    editOrgForm.captcha_id = res.data.captcha_id
    editOrgForm.captcha_code = ''
  } catch {
    editOrgCaptchaImage.value = ''
  }
}

const openEditOrg = (row: Organization) => {
  editOrgForm.id = row.id
  editOrgForm.name = row.name
  editOrgForm.description = row.description ?? ''
  editOrgForm.sort_order = row.sort_order
  editOrgForm.captcha_code = ''
  editOrgVisible.value = true
}

const submitEditOrg = async () => {
  const name = editOrgForm.name.trim()
  if (!name) {
    ElMessage.warning('请输入组织名称')
    return
  }
  if (!editOrgForm.captcha_code) {
    ElMessage.warning('请输入图形验证码')
    return
  }
  editOrgSubmitting.value = true
  try {
    const desc = editOrgForm.description.trim()
    await updateOrganization(editOrgForm.id, {
      name,
      description: desc || undefined,
      sort_order: editOrgForm.sort_order,
      captcha_id: editOrgForm.captcha_id,
      captcha_code: editOrgForm.captcha_code,
    })
    ElMessage.success('已保存')
    editOrgVisible.value = false
    await fetchOrganizations()
  } catch {
    refreshEditOrgCaptcha()
  } finally {
    editOrgSubmitting.value = false
  }
}

const loadOrgListForManage = async () => {
  orgManageLoading.value = true
  try {
    await fetchOrganizations()
  } finally {
    orgManageLoading.value = false
  }
}

const openOrgManageDialog = () => {
  orgManageVisible.value = true
}

const submitNewOrg = async () => {
  const name = newOrgName.value.trim()
  if (!name) {
    ElMessage.warning('请输入组织名称')
    return
  }
  orgCreating.value = true
  try {
    await createOrganization({
      name,
      description: newOrgDesc.value.trim() || undefined,
      sort_order: newOrgSort.value ?? 0,
    })
    ElMessage.success('已添加')
    newOrgName.value = ''
    newOrgDesc.value = ''
    newOrgSort.value = 0
    await fetchOrganizations()
  } catch {
    //
  } finally {
    orgCreating.value = false
  }
}

const openBatchOrgDialog = () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请先选择用户')
    return
  }
  batchOrgTargetId.value = undefined
  batchOrgPassword.value = ''
  batchOrgDialogVisible.value = true
}

const confirmBatchOrg = async () => {
  if (!batchOrgPassword.value) {
    ElMessage.warning('请输入管理员密码')
    return
  }
  batchOrgLoading.value = true
  try {
    const res = await batchSetOrganization({
      user_ids: selectedUsers.value.map((u) => u.id),
      organization_id: batchOrgTargetId.value ?? null,
      admin_password: batchOrgPassword.value,
    })
    ElMessage.success(`已更新 ${res.data.count} 位用户的组织`)
    batchOrgDialogVisible.value = false
    fetchUsers()
    selectedUsers.value = []
  } catch {
    //
  } finally {
    batchOrgLoading.value = false
  }
}

onMounted(() => {
  fetchUsers()
  fetchOrganizations()
  if (authStore.token && !authStore.user) {
    authStore.fetchUser().catch(() => {})
  }
})

onUnmounted(() => {
  if (deleteSmsTimer) {
    clearInterval(deleteSmsTimer)
    deleteSmsTimer = null
  }
})
</script>

<style scoped>
.user-list-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  flex-wrap: wrap;
  gap: 16px;
}
.header-left h2 {
    margin: 0;
    font-size: 24px;
    color: #303133;
}
.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}
.action-divider {
    height: 24px;
    margin: 0 4px;
}
.action-buttons {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
  display: flex;
  align-items: center;
  font-size: 14px;
  margin-left: 10px;
}
.text-gray {
    color: #909399;
    font-size: 12px;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.captcha-item {
    margin-bottom: 0;
}
.delete-hint {
    margin: 0 0 8px;
    line-height: 1.5;
    color: #606266;
}
.text-muted {
    margin: 0 0 8px;
    font-size: 13px;
    color: #909399;
}
.sms-row {
    display: flex;
    gap: 8px;
    width: 100%;
}
.sms-row .el-input {
    flex: 1;
}
.captcha-row-edit {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
}
.captcha-row-edit .el-input {
  flex: 1;
}
.captcha-img {
  cursor: pointer;
  flex-shrink: 0;
  height: 40px;
  line-height: 0;
}
.captcha-img img {
  height: 40px;
  display: block;
  border-radius: 4px;
}
:deep(.danger-dropdown-item) {
    color: #f56c6c;
}
</style>
