<template>
  <div class="user-management-container">
    <el-row :gutter="20" class="full-height-row">
      <!-- 左侧部门树 -->
      <el-col :xl="7" :lg="8" :md="10" :sm="24" :xs="24" class="full-height-col">
        <el-card shadow="hover" class="full-height-card">
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <span>部门</span>
                <el-checkbox v-model="showDeptCode" size="small" class="dept-code-checkbox">显示编号</el-checkbox>
              </div>
              <div class="header-actions">
                <el-tooltip content="展开全部" placement="top">
                  <el-button icon="ArrowDown" circle size="small" @click="expandAll"></el-button>
                </el-tooltip>
                <el-tooltip content="收缩全部" placement="top">
                  <el-button icon="ArrowUp" circle size="small" @click="collapseAll"></el-button>
                </el-tooltip>
                <el-tooltip content="重置为默认展开（前两层）" placement="top">
                  <el-button icon="RefreshLeft" circle size="small" @click="resetToDefaultExpanded"></el-button>
                </el-tooltip>
                <el-tooltip content="刷新数据" placement="top">
                  <el-button icon="Refresh" circle size="small" @click="getDeptTree"></el-button>
                </el-tooltip>
              </div>
            </div>
          </template>

          <div class="search-container">
            <el-input v-model="deptName" placeholder="请输入部门名称" prefix-icon="Search" clearable />
          </div>

          <div class="tree-scroll-container">
            <el-tree
              ref="deptTreeRef"
              node-key="id"
              :data="deptOptions"
              :props="DEPT_TREE_PROPS"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              :default-expanded-keys="defaultExpandedKeys"
              highlight-current
              @node-click="handleNodeClick"
            >
              <template #default="{ node, data }">
                <span>
                  {{ node.label }}
                  <span v-if="showDeptCode && data.manageCom" style="color: #999; margin-left: 8px; font-size: 12px"> [{{ data.manageCom }}] </span>
                </span>
              </template>
            </el-tree>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧用户列表 -->
      <el-col :xl="17" :lg="16" :md="14" :sm="24" :xs="24" class="full-height-col">
        <div class="right-content" :class="{ 'search-visible': showSearch }">
          <!-- 搜索区域 -->
          <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
            <div v-show="showSearch" class="search-card">
              <el-card shadow="hover">
                <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                  <el-form-item label="用户名称" prop="userName">
                    <el-input v-model="queryParams.userName" placeholder="请输入用户名称" clearable @keyup.enter="handleQuery" />
                  </el-form-item>
                  <el-form-item label="手机号码" prop="phonenumber">
                    <el-input v-model="queryParams.phonenumber" placeholder="请输入手机号码" clearable @keyup.enter="handleQuery" />
                  </el-form-item>
                  <el-form-item label="状态" prop="status">
                    <el-select v-model="queryParams.status" placeholder="用户状态" clearable>
                      <el-option v-for="dict in sys_user_status" :key="dict.value" :label="dict.label" :value="dict.value" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="角色类型" prop="roleType">
                    <el-select v-model="queryParams.roleType" placeholder="角色类型" clearable>
                      <el-option v-for="dict in sys_user_role_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="创建时间" style="width: 308px">
                    <el-date-picker
                      v-model="dateRange"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      type="daterange"
                      range-separator="-"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      :default-time="DEFAULT_TIME_RANGE"
                    />
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                    <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                  </el-form-item>
                </el-form>
              </el-card>
            </div>
          </transition>

          <!-- 用户列表卡片 -->
          <el-card shadow="hover" class="table-card">
            <template #header>
              <div class="table-header">
                <div class="header-title">
                  <span>用户列表</span>
                </div>
                <div class="header-actions">
                  <el-button v-has-permi="['system:user:add']" type="primary" plain icon="Plus" @click="handleAdd"> 新增 </el-button>
                  <el-button v-has-permi="['system:user:edit']" type="success" plain :disabled="single" icon="Edit" @click="handleUpdate()">
                    修改
                  </el-button>
                  <el-button
                    v-has-permi="['system:user:remove']"
                    type="danger"
                    plain
                    :disabled="multiple || hasBuiltInUserSelected"
                    icon="Delete"
                    @click="handleDelete()"
                  >
                    申请注销
                  </el-button>
                  <!-- <el-dropdown class="mt-[1px]">
                    <el-button plain type="info">
                      更多
                      <el-icon class="el-icon--right"><ArrowDown /></el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item icon="Download" @click="handleImportTemplate"> 下载模板 </el-dropdown-item>
                        <el-dropdown-item icon="Top" @click="handleImport"> 导入数据 </el-dropdown-item>
                        <el-dropdown-item icon="Download" @click="handleExport"> 导出数据 </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown> -->
                  <el-button icon="Search" plain @click="showSearch = !showSearch"> {{ showSearch ? '隐藏' : '显示' }}搜索 </el-button>
                  <RightToolbar v-model:show-search="showSearch" :columns="columns" :search="true" @query-table="getList" />
                </div>
              </div>
            </template>

            <div class="table-container">
              <el-table
                ref="tableRef"
                v-loading="loading"
                :height="tableHeight"
                :data="userList"
                row-key="userId"
                stripe
                border
                highlight-current-row
                @selection-change="handleSelectionChange"
              >
                <el-table-column type="selection" width="50" align="center" />
                <el-table-column v-if="columns[0].visible" key="userId" label="用户编号" align="center" prop="userId" width="100" />
                <el-table-column
                  v-if="columns[1].visible"
                  key="userName"
                  label="用户名称"
                  align="center"
                  prop="userName"
                  :show-overflow-tooltip="true"
                  width="150"
                />
                <el-table-column
                  v-if="columns[2].visible"
                  key="nickName"
                  label="用户昵称"
                  align="center"
                  prop="nickName"
                  :show-overflow-tooltip="true"
                  width="150"
                />
                <el-table-column
                  v-if="columns[3].visible"
                  key="deptName"
                  label="部门"
                  align="center"
                  prop="deptName"
                  :show-overflow-tooltip="true"
                  width="200"
                />
                <el-table-column v-if="columns[5].visible" key="status" label="状态" align="center" width="100">
                  <template #default="scope">
                    <el-tag :type="getStatusTagType(scope.row.status)" :effect="scope.row.status === USER_STATUS.ACTIVE ? 'dark' : 'plain'">
                      {{ getStatusLabel(scope.row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column v-if="columns[6].visible" key="roleType" label="角色类型" align="center" width="120">
                  <template #default="scope">
                    <template v-if="scope.row.roleType !== null && scope.row.roleType !== undefined && scope.row.roleType !== ''">
                      <DictTag :options="sys_user_role_type" :value="scope.row.roleType" />
                    </template>
                    <template v-else>
                      <el-tag type="info" effect="plain" size="small">未设置</el-tag>
                    </template>
                  </template>
                </el-table-column>
                <!-- <el-table-column v-if="columns[7].visible" key="branchType" label="渠道" align="center" width="100">
                  <template #default="scope">
                    <template v-if="scope.row.branchType">
                      <DictTag :options="branchtype" :value="scope.row.branchType" />
                    </template>
                    <template v-else>
                      <el-tag type="info" effect="plain" size="small">未设置</el-tag>
                    </template>
                  </template>
                </el-table-column> -->
                <el-table-column v-if="columns[8].visible" label="创建时间" align="center" prop="createTime" width="160">
                  <template #default="scope">
                    <span>{{ scope.row.createTime }}</span>
                  </template>
                </el-table-column>

                <!-- 操作列 - 修改后的版本 -->
                <el-table-column label="操作" fixed="right" width="180" class-name="small-padding fixed-width">
                  <template #default="scope">
                    <!-- 注销用户只显示修改操作 -->
                    <template v-if="isCancelledUser(scope.row)">
                      <el-tooltip content="修改" placement="top">
                        <el-button v-hasPermi="['system:user:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)" />
                      </el-tooltip>
                    </template>

                    <!-- 系统管理员不显示任何操作按钮 -->
                    <template v-else-if="isSystemAdmin(scope.row.userId)">
                      <!-- 系统管理员不显示任何操作 -->
                    </template>

                    <!-- 内置用户(非系统管理员)显示修改和重置密码 -->
                    <template v-else-if="isBuiltInUser(scope.row)">
                      <el-tooltip content="修改" placement="top">
                        <el-button v-hasPermi="['system:user:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)" />
                      </el-tooltip>
                      <el-tooltip content="重置密码" placement="top">
                        <el-button v-hasPermi="['system:user:resetPwd']" link type="primary" icon="Key" @click="handleResetPwd(scope.row)" />
                      </el-tooltip>
                    </template>

                    <!-- 普通用户显示所有操作 -->
                    <template v-else>
                      <el-tooltip content="修改" placement="top">
                        <el-button v-hasPermi="['system:user:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)" />
                      </el-tooltip>
                      <el-tooltip content="申请注销" placement="top">
                        <el-button v-hasPermi="['system:user:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)" />
                      </el-tooltip>
                      <el-tooltip content="重置密码" placement="top">
                        <el-button v-hasPermi="['system:user:resetPwd']" link type="primary" icon="Key" @click="handleResetPwd(scope.row)" />
                      </el-tooltip>
                      <!-- <el-tooltip content="分配角色" placement="top">
                        <el-button v-hasPermi="['system:user:edit']" link type="primary" icon="CircleCheck" @click="handleAuthRole(scope.row)" />
                      </el-tooltip> -->
                    </template>
                  </template>
                </el-table-column>

                <template #empty>
                  <div class="empty-data">
                    <el-empty description="暂无数据" />
                  </div>
                </template>
              </el-table>
            </div>

            <div class="pagination-container">
              <Pagination
                v-show="total > 0"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                :enabled-dept-tree="enabledDeptOptions"
                :total="total"
                @pagination="getList"
              />
            </div>
          </el-card>
        </div>
      </el-col>
    </el-row>

    <!-- 用户表单组件 -->
    <UserForm
      v-model:visible="userFormVisible"
      :edit-type="editType"
      :row-data="currentRow"
      :enabled-dept-tree="enabledDeptOptions"
      @save="handleSave"
    />

    <!-- 导入数据组件 -->
    <ImportData
      v-model:visible="importVisible"
      :upload-url="IMPORT_URL"
      :title="'用户导入'"
      @save="handleSave"
      @template-download="handleImportTemplateDownloaded"
    />

    <!-- 二次验证组件 -->
    <SecondVerify
      v-model:visible="secondVerifyVisible"
      :user-info="currentVerifyUser"
      :title="'安全验证'"
      :operation-type="pendingOperation.type"
      @verify-success="handleVerifySuccess"
      @verify-cancel="handleVerifyCancel"
    />

    <!-- 密码重置组件 -->
    <ForceChangePassword
      v-model:visible="forceChangePasswordVisible"
      :is-admin-reset="true"
      :target-user-id="resetPasswordData.userId"
      :target-user-name="resetPasswordData.userName"
      @success="handlePasswordResetSuccess"
      @cancel="handlePasswordResetCancel"
    />
  </div>
</template>

<script setup name="User" lang="ts">
import { computed, getCurrentInstance, onMounted, reactive, ref, toRefs, watch, watchEffect } from 'vue';
import { useRouter } from 'vue-router';
import { ArrowDown } from '@element-plus/icons-vue';
import api from '@/api/system/user';
import { isBuiltInUser, UserQuery, UserVO, VerifyResult } from '@/api/system/user/types';
import { DeptTreeVO, DeptVO } from '@/api/system/dept/types';
import { to } from 'await-to-js';
import UserForm from './userForm.vue';
import ImportData from './components/importData.vue';
import SecondVerify from './secondVerify.vue';
import Pagination from '@/components/Pagination/index.vue';
import RightToolbar from '@/components/RightToolbar/index.vue';
import DictTag from '@/components/DictTag/index.vue';
import ForceChangePassword from '@/components/User/ForceChangePassword.vue';
import { useUserStore } from '@/store/modules/user';
import { applyLogout } from '@/api/system/approval/logoutRequest';
import { LogoutRequestForm } from '@/api/system/approval/types';

// ===== 常量定义 =====
const USER_STATUS = {
  ACTIVE: '0',
  LOCKED: '1',
  PENDING: '2',
  DORMANT: '3',
  CANCELLED: '4'
} as const;

const ROLE_TYPE = {
  SYSTEM_ADMIN: '1',
  AUDIT_ADMIN: '3',
  APPROVAL_ADMIN: '4',
  BUSINESS_CONFIGURATOR: '5',
  BUSINESS_OPERATOR: '6'
} as const;

const SYSTEM_ADMIN_ID = 1;
const IMPORT_URL = '/system/user/importData';

const DEPT_TREE_PROPS = {
  label: 'label',
  children: 'children'
} as const;

const DEFAULT_TIME_RANGE = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)] as const;

const STATUS_TAG_MAP = {
  [USER_STATUS.ACTIVE]: 'success',
  [USER_STATUS.LOCKED]: 'danger',
  [USER_STATUS.PENDING]: 'warning',
  [USER_STATUS.DORMANT]: 'info',
  [USER_STATUS.CANCELLED]: 'danger'
} as const;

// ===== 基础设置 =====
const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const userStore = useUserStore();

// 字典数据
const { sys_user_role_type, sys_user_status, branchtype } = toRefs<any>(proxy?.useDict('sys_user_role_type', 'sys_user_status', 'branchtype'));

// ===== 权限相关计算属性 =====
// 当前用户信息
const currentUser = computed(() => userStore.userInfo?.user);

// 检查当前用户是否有渠道权限控制
const currentUserHasBranch = computed(() => {
  return currentUser.value?.branchType;
});

// 当前用户的渠道
const currentUserBranchType = computed(() => {
  return currentUser.value?.branchType || '';
});

// ===== 响应式数据 =====
const userList = ref<UserVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const showDeptCode = ref(true);
const ids = ref<Array<number | string>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const deptName = ref('');
const deptOptions = ref<DeptTreeVO[]>([]);
const enabledDeptOptions = ref<DeptTreeVO[]>([]);
const defaultExpandedKeys = ref<Array<string | number>>([]);
const tableHeight = ref();

// 表单控制状态
const userFormVisible = ref(false);
const editType = ref<'add' | 'edit'>('add');
const currentRow = ref<UserVO | null>(null);

// 密码重置控制状态
const forceChangePasswordVisible = ref(false);
const resetPasswordData = ref({
  userId: '',
  userName: ''
});

// 导入控制状态
const importVisible = ref(false);

// 二次验证状态
const secondVerifyVisible = ref(false);
const currentVerifyUser = ref<Partial<UserVO>>({});

// 待执行操作状态
const pendingOperation = ref<{
  type: 'resetPwd' | 'updateUser' | 'deleteUser';
  data: any;
}>({
  type: 'resetPwd',
  data: null
});

// 查询参数
const queryParams = reactive<UserQuery>({
  pageNum: 1,
  pageSize: 10,
  userName: '',
  phonenumber: '',
  status: '',
  roleType: '',
  deptId: '',
  roleId: ''
});

// 列显隐配置
const columns = ref<FieldOption[]>([
  { key: 0, label: '用户编号', visible: false, children: [] },
  { key: 1, label: '用户名称', visible: true, children: [] },
  { key: 2, label: '用户昵称', visible: true, children: [] },
  { key: 3, label: '部门', visible: true, children: [] },
  { key: 4, label: '手机号码', visible: true, children: [] },
  { key: 5, label: '状态', visible: true, children: [] },
  { key: 6, label: '角色类型', visible: true, children: [] },
  { key: 7, label: '渠道', visible: true, children: [] },
  { key: 8, label: '创建时间', visible: true, children: [] }
]);

// 引用
const deptTreeRef = ref<ElTreeInstance>();
const queryFormRef = ref<ElFormInstance>();
const tableRef = ref<ElTableInstance>();

// ===== 新增：内置用户相关计算属性 =====
// 检查选中的用户中是否有内置用户
const hasBuiltInUserSelected = computed(() => {
  if (ids.value.length === 0) return false;
  const selectedUsers = userList.value.filter((user) => ids.value.includes(user.userId));
  return selectedUsers.some((user) => isBuiltInUser(user));
});

// ===== 工具函数 =====
const isSystemAdmin = (userId: number): boolean => userId === SYSTEM_ADMIN_ID;

// 新增：判断用户是否已注销
const isCancelledUser = (user: UserVO): boolean => {
  return user.status === USER_STATUS.CANCELLED;
};

// 优化过滤函数，支持按编号和名称搜索
const filterNode = (value: string, data: any): boolean => {
  if (!value) return true;
  const searchValue = value.toLowerCase();
  const labelMatch = data.label.toLowerCase().indexOf(searchValue) !== -1;
  const codeMatch = data.manageCom && data.manageCom.toLowerCase().indexOf(searchValue) !== -1;
  return labelMatch || codeMatch;
};

const filterDisabledDept = (deptList: DeptTreeVO[]): DeptTreeVO[] => {
  return deptList.filter((dept) => {
    if (dept.disabled) return false;
    if (dept.children?.length) {
      dept.children = filterDisabledDept(dept.children);
    }
    return true;
  });
};

const getStatusTagType = (status: string): string => {
  return STATUS_TAG_MAP[status as keyof typeof STATUS_TAG_MAP] || '';
};

const getStatusLabel = (status: string): string => {
  const statusDict = sys_user_status.value;
  const found = statusDict?.find((item: any) => item.value === status);
  return found?.label || '未知状态';
};

// 显示错误消息
const showErrorMessage = (message: string, error?: any): void => {
  proxy?.$modal.msgError(`${message}${error ? ': ' + error : ''}`);
};

// 检查用户操作权限 - 修改后的权限控制逻辑
const checkUserPermission = (user: UserVO, operation: string, showMessage: boolean = true): boolean => {
  // 如果当前用户没有渠道设置，拥有所有权限
  if (!currentUserHasBranch.value) {
    return true;
  }

  // 如果当前用户有渠道设置，只能操作同渠道或无渠道的用户
  const hasPermission = !user.branchType || user.branchType === currentUserBranchType.value;

  if (!hasPermission && showMessage) {
    showErrorMessage(`您只能${operation}自己渠道的用户`);
  }

  return hasPermission;
};

// 为部门树添加用户统计信息
const addDeptUserStatistics = (deptList: DeptTreeVO[]): DeptTreeVO[] => {
  return deptList.map((dept) => {
    // 统计该部门下的用户数量
    const deptUserCount = userList.value.filter((user) => user.deptId === dept.id).length;

    // 如果有子部门，递归处理
    if (dept.children && dept.children.length > 0) {
      dept.children = addDeptUserStatistics(dept.children);
    }

    return {
      ...dept,
      userCount: deptUserCount
    };
  });
};

// ===== 部门树展开收缩相关方法 =====

// 获取默认展开到指定层级的节点keys
const getDefaultExpandedKeys = (deptList: DeptTreeVO[], currentLevel: number = 1, maxLevel: number = 2): Array<string | number> => {
  const keys: Array<string | number> = [];

  deptList.forEach((dept) => {
    // 第一层总是展开
    if (currentLevel === 1) {
      keys.push(dept.id);
    }
    // 第二层也展开，但不包括第二层的子节点
    if (currentLevel <= maxLevel && dept.children && dept.children.length > 0) {
      if (currentLevel < maxLevel) {
        // 递归处理子节点
        keys.push(...getDefaultExpandedKeys(dept.children, currentLevel + 1, maxLevel));
      }
      // 如果当前是第二层，展开当前节点但不递归子节点
      if (currentLevel === maxLevel) {
        keys.push(dept.id);
      }
    }
  });

  return keys;
};

// 获取所有节点的keys（用于全部展开/收缩）
const getAllNodeKeys = (deptList: DeptTreeVO[]): Array<string | number> => {
  const keys: Array<string | number> = [];

  const collectKeys = (nodes: DeptTreeVO[]) => {
    nodes.forEach((node) => {
      keys.push(node.id);
      if (node.children && node.children.length > 0) {
        collectKeys(node.children);
      }
    });
  };

  collectKeys(deptList);
  return keys;
};

// 展开所有节点
const expandAll = (): void => {
  if (!deptTreeRef.value || !deptOptions.value.length) return;

  proxy?.$nextTick(() => {
    try {
      const allKeys = getAllNodeKeys(deptOptions.value);
      defaultExpandedKeys.value = allKeys;

      // 同时使用tree组件的方法确保展开
      allKeys.forEach((key) => {
        const node = (deptTreeRef.value as any).getNode?.(key);
        if (node && !node.expanded) {
          node.expand?.();
        }
      });
    } catch (error) {}
  });
};

// 收缩所有节点
const collapseAll = (): void => {
  if (!deptTreeRef.value) return;

  proxy?.$nextTick(() => {
    try {
      // 清空展开的keys
      defaultExpandedKeys.value = [];

      // 使用tree组件的方法收缩所有节点
      const allKeys = getAllNodeKeys(deptOptions.value);
      allKeys.forEach((key) => {
        const node = (deptTreeRef.value as any).getNode?.(key);
        if (node && node.expanded) {
          node.collapse?.();
        }
      });
    } catch (error) {}
  });
};

// 重置为默认展开状态（展开前两层）
const resetToDefaultExpanded = (): void => {
  if (!deptOptions.value.length) return;

  const keys = getDefaultExpandedKeys(deptOptions.value, 1, 2);
  defaultExpandedKeys.value = keys;

  proxy?.$nextTick(() => {
    try {
      // 确保tree组件同步展开状态
      if (deptTreeRef.value) {
        // 先收缩所有
        const allKeys = getAllNodeKeys(deptOptions.value);
        allKeys.forEach((key) => {
          const node = (deptTreeRef.value as any).getNode?.(key);
          if (node && node.expanded) {
            node.collapse?.();
          }
        });

        // 再展开指定层级
        keys.forEach((key) => {
          const node = (deptTreeRef.value as any).getNode?.(key);
          if (node && !node.expanded) {
            node.expand?.();
          }
        });
      }
    } catch (error) {}
  });
};

// ===== 二次验证相关方法 =====

// 第一步：触发密码重置（显示二次验证）
const handleResetPwd = async (row: UserVO): Promise<void> => {
  if (!checkUserPermission(row, '重置密码')) return;

  // 保存当前用户信息用于二次验证
  currentVerifyUser.value = {
    userId: row.userId,
    userName: row.userName,
    phonenumber: row.phonenumber,
    email: row.email
  };

  // 保存待重置的用户信息
  pendingOperation.value = {
    type: 'resetPwd',
    data: row
  };

  // 显示二次验证对话框
  secondVerifyVisible.value = true;
};

// 第一步：触发修改用户（显示二次验证）
const handleUpdate = (row?: UserVO): void => {
  let targetRow: UserVO | null = null;

  if (row) {
    if (!checkUserPermission(row, '修改')) return;
    targetRow = row;
  } else {
    const selectedUser = userList.value.find((item) => item.userId === ids.value[0]);
    if (selectedUser && !checkUserPermission(selectedUser, '修改')) return;
    targetRow = selectedUser || null;
  }

  if (!targetRow) return;

  // 直接打开编辑表单，不再进行二次验证
  currentRow.value = targetRow;
  editType.value = 'edit';
  userFormVisible.value = true;
};

// 第一步：触发注销用户（显示二次验证）
const handleDelete = async (row?: UserVO): Promise<void> => {
  try {
    // 权限检查（原有逻辑）
    if (row) {
      if (!checkUserPermission(row, '申请注销')) return;
      // 新增：检查是否是内置用户
      if (isBuiltInUser(row)) {
        showErrorMessage('内置用户不允许注销');
        return;
      }
    } else if (ids.value.length > 0) {
      const selectedUsers = userList.value.filter((u) => ids.value.includes(u.userId));
      const hasPermissionIssue = selectedUsers.some((u) => !checkUserPermission(u, '注销', false));
      if (hasPermissionIssue) {
        showErrorMessage('您只能注销自己渠道的用户');
        return;
      }
      // 新增：检查选中用户中是否有内置用户
      const hasBuiltInUser = selectedUsers.some((u) => isBuiltInUser(u));
      if (hasBuiltInUser) {
        showErrorMessage('选中的用户中包含内置用户，内置用户不允许注销');
        return;
      }
    }

    const userIds = row?.userId || ids.value;

    // 确认操作
    const [err] = await to(proxy?.$modal.confirm(`是否确认申请注销用户数据？提交后将进入审批流程!`, '注销申请确认') as any);
    if (err) return;

    // 设置二次验证信息
    if (row) {
      currentVerifyUser.value = {
        userId: row.userId,
        userName: row.userName,
        phonenumber: row.phonenumber,
        email: row.email
      };
    } else {
      currentVerifyUser.value = {
        userId: 'batch',
        userName: '批量操作'
      };
    }

    // 设置待执行操作
    pendingOperation.value = {
      type: 'deleteUser',
      data: { userIds, targetUser: row }
    };

    // 显示二次验证
    secondVerifyVisible.value = true;
  } catch (error) {
    showErrorMessage('注销失败', error);
  }
};

// 第二步：处理二次验证成功后的逻辑
const handleVerifySuccess = async (result: VerifyResult): Promise<void> => {
  if (!result.success) return;

  try {
    switch (pendingOperation.value.type) {
      case 'resetPwd':
        // 密码重置逻辑
        handlePasswordReset(pendingOperation.value.data);
        break;

      case 'updateUser':
        // 修改用户逻辑
        currentRow.value = pendingOperation.value.data;
        editType.value = 'edit';
        userFormVisible.value = true;
        break;

      case 'deleteUser':
        // 注销用户逻辑
        await executeDeleteUser(pendingOperation.value.data);
        break;
    }
  } finally {
    // 清理状态
    handleVerifyCancel();
  }
};

// 第三步：显示密码重置组件
const handlePasswordReset = (row: UserVO): void => {
  // 设置重置密码的用户信息
  resetPasswordData.value = {
    userId: row.userId.toString(),
    userName: row.userName
  };
  // 显示密码重置对话框
  forceChangePasswordVisible.value = true;
};

// 执行注销用户
// 执行注销用户（精简版）
const executeDeleteUser = async (operationData: any) => {
  try {
    const { userIds, targetUser } = operationData;
    // 处理单个用户注销
    if (targetUser) {
      const logoutRequest: LogoutRequestForm = {
        userId: targetUser.userId,
        applyReason: '管理员申请注销用户账号',
        remark: `由管理员${userStore.userInfo?.user?.nickName || ''}申请注销用户${targetUser.userName}`
      };
      await applyLogout(logoutRequest);
      proxy?.$modal.msgSuccess('用户注销申请提交成功，等待审批');
    }
    // 处理批量用户注销
    else {
      const userIdArray = Array.isArray(userIds) ? userIds : [userIds];
      const successCount = userIdArray.length;
      // 批量处理：为每个用户创建注销申请
      const promises = userIdArray.map(async (userId) => {
        // 从用户列表中找到对应的用户信息
        const user = userList.value.find((u) => u.userId === userId);
        const userName = user?.userName || `用户${userId}`;
        const logoutRequest: LogoutRequestForm = {
          userId: String(userId),
          applyReason: '管理员批量申请注销用户账号',
          remark: `由管理员${userStore.userInfo?.user?.nickName || ''}批量申请注销用户${userName}`
        };
        return applyLogout(logoutRequest);
      });
      // 等待所有请求完成
      await Promise.all(promises);
      proxy?.$modal.msgSuccess(`批量注销申请提交成功，共处理 ${successCount} 个用户，等待审批`);
    }
    // 刷新用户列表
    await getList();
  } catch (error: any) {
    // 根据错误类型显示不同的错误信息
    if (error?.response?.data?.msg) {
      proxy?.$modal.msgError(`注销申请失败：${error.response.data.msg}`);
    } else {
      proxy?.$modal.msgError('注销申请提交失败，请重试');
    }
  }
};

// 密码重置成功回调
const handlePasswordResetSuccess = (): void => {
  // 关闭二次验证对话框
  secondVerifyVisible.value = false;
  // 清理状态
  handleVerifyCancel();
};

// 密码重置取消回调
const handlePasswordResetCancel = (): void => {
  // 重置状态
  resetPasswordData.value = {
    userId: '',
    userName: ''
  };
};

// 二次验证取消处理
const handleVerifyCancel = (): void => {
  pendingOperation.value = { type: 'resetPwd', data: null };
  currentVerifyUser.value = {};
};

// ===== 监听器 =====
watchEffect(
  () => {
    deptTreeRef.value?.filter(deptName.value);
  },
  { flush: 'post' }
);

// 监听部门数据变化，确保展开状态
watch(
  () => deptOptions.value,
  (newData) => {
    if (newData && newData.length > 0 && defaultExpandedKeys.value.length === 0) {
      const keys = getDefaultExpandedKeys(newData, 1, 2);
      defaultExpandedKeys.value = keys;
    }
  },
  { immediate: true }
);

// ===== 数据获取 =====
const getList = async (): Promise<void> => {
  try {
    loading.value = true;
    const res = await api.listUser(proxy?.addDateRange(queryParams, dateRange.value));
    userList.value = res.rows;
    total.value = res.total;

    // 更新部门树的用户统计信息
    if (deptOptions.value.length > 0) {
      deptOptions.value = addDeptUserStatistics(deptOptions.value);
    }
  } catch (error) {
    showErrorMessage('获取用户列表失败', error);
  } finally {
    loading.value = false;
  }
};

const getDeptTree = async (): Promise<void> => {
  try {
    const res = await api.deptTreeSelect();
    let treeData = res.data;
    if (currentUser.value?.sysType != 'Y' && !currentUser.value.admin && currentUser.value?.deptId) {
      const targetDeptId = currentUser.value.deptId;
      treeData = filterDeptTreeById(treeData, targetDeptId);
    }
    deptOptions.value = addDeptUserStatistics(treeData);
    enabledDeptOptions.value = filterDisabledDept(treeData);

    // 设置默认展开前两层
    const keys = getDefaultExpandedKeys(deptOptions.value, 1, 2);
    defaultExpandedKeys.value = keys;

    // 确保tree组件渲染完成后应用展开状态
    proxy?.$nextTick(() => {
      resetToDefaultExpanded();
    });
  } catch (error) {
    showErrorMessage('获取部门树失败', error);
  }
};
//过滤，只留下当前用户部门及子部门
const filterDeptTreeById = (tree: DeptTreeVO[], targetId: number | string): DeptTreeVO[] => {
  const result: DeptTreeVO[] = [];
  const dfs = (nodes: DeptTreeVO[]): DeptTreeVO | null => {
    for (const node of nodes) {
      if (node.id === targetId) {
        return { ...node };
      }
      if (node.children && node.children.length > 0) {
        const foundNode = dfs(node.children);
        if (foundNode) {
          return { ...node, children: [foundNode] };
        }
      }
    }
    return null;
  };
  const matched = dfs(tree);
  return matched ? [matched] : [];
};

// ===== 事件处理 =====
const handleNodeClick = (data: DeptVO): void => {
  const label = (data as any).label ?? data.deptName ?? '';
  if (typeof label === 'string' && label.endsWith('公司')) {
    showErrorMessage('公司节点不可查看用户列表');
    return;
  }
  queryParams.deptId = data.id;
  handleQuery();
};

const handleQuery = (): void => {
  queryParams.pageNum = 1;
  getList();
};

const resetQuery = (): void => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  queryParams.pageNum = 1;
  queryParams.deptId = undefined;
  deptTreeRef.value?.setCurrentKey(undefined);
  handleQuery();
};

const handleSelectionChange = (selection: UserVO[]): void => {
  ids.value = selection.map((item) => item.userId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

// ===== CRUD 操作 =====
const handleAdd = (): void => {
  editType.value = 'add';
  currentRow.value = null;
  userFormVisible.value = true;
};

const handleAuthRole = (row: UserVO): void => {
  if (!checkUserPermission(row, '分配角色')) return;

  // 新增：检查是否是内置用户
  if (isBuiltInUser(row)) {
    showErrorMessage('内置用户不允许分配角色');
    return;
  }

  router.push(`/system/user-auth/role/${row.userId}`);
};

// ===== 导入导出操作 =====
const handleImport = (): void => {
  importVisible.value = true;
};

const handleExport = (): void => {
  proxy?.download('system/user/export', { ...queryParams }, `用户导出_${new Date().getTime()}.xlsx`);
};

const handleImportTemplate = (): void => {
  proxy?.download('system/user/importTemplate', {}, `用户导入模板_${new Date().getTime()}.xlsx`);
};

const handleImportTemplateDownloaded = (): void => {
  // 模板下载完成后的处理逻辑
};

const handleSave = (): void => {
  getList();
};

// ===== 生命周期 =====
onMounted(async () => {
  try {
    // 确保用户信息已加载
    if (!userStore.userInfo) {
      await userStore.getInfo();
    }
    if (currentUser.value?.sysType != 'Y' && currentUser.value?.deptId) {
      queryParams.deptId = currentUser.value.deptId;
    }
    // 并行初始化数据
    await Promise.all([getDeptTree(), getList()]);
    tableHeight.value = window.innerHeight - (tableRef.value as any).$el.offsetTop - 200;
  } catch (error) {
    showErrorMessage('页面初始化失败', error);
  }
});
</script>

<style lang="scss" scoped>
// 导入样式文件
@use '@/assets/styles/components/user-management.scss';
</style>
