<template>
  <AdminLayout title="任务管理" subtitle="任务管理">
    <div class="task-management">
      <!-- 任务列表视图 -->
      <div v-if="currentView === 'list'" class="task-manage-view">
        <!-- 头部 -->
        <div class="header">
          <h2 class="title">学习任务列表</h2>
          <button class="btn-create" @click="handleAdd">
            <span class="icon">+</span>
            新建任务
          </button>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
          <div class="loading-spinner"></div>
          <span>加载中...</span>
        </div>

        <!-- 空状态 -->
        <div v-else-if="taskList.length === 0" class="empty-container">
          <div class="empty-icon">📋</div>
          <p>暂无任务数据</p>
        </div>

        <!-- 任务卡片列表 -->
        <div v-else class="task-cards">
          <TaskCard
            v-for="task in taskList"
            :key="task.learningTask.taskID"
            :task="task"
            @view="handleView"
            @edit="handleEdit"
            @publish="handlePublish"
            @unpublish="handleUnpublish"
            @statistics="handleStatistics"
            @update-user="handleUpdateUser"
            @delete="handleDelete"
          />
        </div>

        <!-- 分页 -->
        <div v-if="!loading && taskList.length > 0" class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[9, 18, 27, 36]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- 新增/编辑任务视图 -->
      <LearningTaskAdd
        v-else-if="currentView === 'add' || currentView === 'edit'"
        :taskId="currentTaskId"
        @success="handleFormSuccess"
        @cancel="handleFormCancel"
      />

      <!-- 统计数据视图 -->
      <div v-else-if="currentView === 'statistics'" class="task-statistics-view">
        <div class="statistics-header">
          <button class="btn-back" @click="handleStatisticsBack">
            <span class="arrow-left">←</span> 返回
          </button>
          <h2 class="page-title">任务统计 - {{ currentTaskName }}</h2>
        </div>
        <TaskStatics v-if="currentTaskId" :task-id="currentTaskId" />
      </div>
    </div>

    <!-- 任务详情弹窗 -->
    <div v-if="showTaskDetail" class="modal-overlay" @click.self="showTaskDetail = false">
      <div class="modal-content">
        <div class="modal-header">
          <h3 class="modal-title">任务详情</h3>
          <button class="modal-close" @click="showTaskDetail = false">✕</button>
        </div>
        
        <div class="modal-body">
          <div v-if="viewingTask" class="task-detail">
            <!-- 基本信息 -->
            <div class="detail-section">
              <h4 class="detail-title">基本信息</h4>
              <div class="detail-content">
                <div class="detail-row">
                  <span class="detail-label">任务名称:</span>
                  <span class="detail-value">{{ viewingTask.learningTask.name }}</span>
                </div>
                <div class="detail-row">
                  <span class="detail-label">任务描述:</span>
                  <span class="detail-value">{{ viewingTask.learningTask.description || '暂无描述' }}</span>
                </div>
                <div class="detail-row">
                  <span class="detail-label">任务状态:</span>
                  <span class="detail-value">
                    <span class="status-badge" :class="getStatusClass(viewingTask.learningTask.status)">
                      {{ getStatusText(viewingTask.learningTask.status, viewingTask.learningTask.startTime, viewingTask.learningTask.endTime) }}
                    </span>
                  </span>
                </div>
                <div class="detail-row">
                  <span class="detail-label">开始时间:</span>
                  <span class="detail-value">{{ formatDate(viewingTask.learningTask.startTime) }}</span>
                </div>
                <div class="detail-row">
                  <span class="detail-label">结束时间:</span>
                  <span class="detail-value">{{ formatDate(viewingTask.learningTask.endTime) }}</span>
                </div>
                <div class="detail-row">
                  <span class="detail-label">创建时间:</span>
                  <span class="detail-value">{{ formatDate(viewingTask.learningTask.createTime) }}</span>
                </div>
              </div>
            </div>

            <!-- 关联课程 -->
            <div class="detail-section" v-if="viewingTask.taskCourses && viewingTask.taskCourses.length > 0">
              <h4 class="detail-title">关联课程 ({{ viewingTask.taskCourses.length }})</h4>
              <div class="detail-list">
                <div v-for="(course, index) in viewingTask.taskCourses" :key="course.id" class="list-item">
                  <span class="item-index">{{ index + 1 }}.</span>
                  <span class="item-name">{{ course.courseName }}</span>
                </div>
              </div>
            </div>

            <!-- 关联资源 -->
            <div class="detail-section" v-if="viewingTask.taskResources && viewingTask.taskResources.length > 0">
              <h4 class="detail-title">关联资源 ({{ viewingTask.taskResources.length }})</h4>
              <div class="detail-list">
                <div v-for="(resource, index) in viewingTask.taskResources" :key="resource.id" class="list-item">
                  <span class="item-index">{{ index + 1 }}.</span>
                  <span class="item-name">{{ resource.resourceName }}</span>
                </div>
              </div>
            </div>

            <!-- 关联用户 -->
            <div class="detail-section" v-if="viewingTask.taskUsers && viewingTask.taskUsers.length > 0">
              <h4 class="detail-title">关联用户 ({{ viewingTask.taskUsers.length }})</h4>
              <div class="detail-list">
                <div v-for="(user, index) in viewingTask.taskUsers" :key="user.id" class="list-item">
                  <span class="item-index">{{ index + 1 }}.</span>
                  <span class="item-name">{{ user.username }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="modal-footer">
          <button class="btn-default" @click="showTaskDetail = false">关闭</button>
        </div>
      </div>
    </div>

    <!-- 确认删除弹窗 -->
    <div v-if="showDeleteConfirm" class="modal-overlay" @click.self="showDeleteConfirm = false">
      <div class="modal-content small">
        <div class="modal-header">
          <h3 class="modal-title">确认删除</h3>
          <button class="modal-close" @click="showDeleteConfirm = false">✕</button>
        </div>
        
        <div class="modal-body">
          <p class="confirm-text">确定要删除任务 "{{ deletingTask?.learningTask.name }}" 吗？此操作不可恢复。</p>
        </div>

        <div class="modal-footer">
          <button class="btn-danger" @click="confirmDelete" :disabled="deleting">
            {{ deleting ? '删除中...' : '确定删除' }}
          </button>
          <button class="btn-default" @click="showDeleteConfirm = false">取消</button>
        </div>
      </div>
    </div>

    <!-- 人员列表弹窗 -->
    <div v-if="showUserList" class="modal-overlay" @click.self="closeUserList">
      <div class="modal-content">
        <div class="modal-header">
          <h3 class="modal-title">人员管理 - {{ managingTask?.learningTask.name }}</h3>
          <button class="modal-close" @click="closeUserList">✕</button>
        </div>
        
        <div class="modal-body">
          <div class="user-list-actions">
            <button class="btn-success" @click="showAddUserSelector">
              <span class="icon">+</span> 添加人员
            </button>
            <button class="btn-danger" @click="showRemoveUserSelector" :disabled="currentUsers.length === 0">
              <span class="icon">-</span> 删除人员
            </button>
          </div>

          <div class="current-user-list">
            <div class="list-header">
              <h4>当前人员列表</h4>
              <span class="count-badge">{{ currentUsers.length }} 人</span>
            </div>
            <div v-if="currentUsers.length === 0" class="empty-list">
              <div class="empty-icon">👥</div>
              <p>暂无人员</p>
            </div>
            <div v-else class="user-grid">
              <div v-for="user in currentUsers" :key="user.id" class="user-card">
                <div class="user-avatar">{{ user.username?.charAt(0) }}</div>
                <div class="user-info">
                  <div class="user-name">{{ user.username }}</div>
                  <div class="user-dept" v-if="user.deptName">{{ user.deptName }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="modal-footer">
          <button class="btn-default" @click="closeUserList">关闭</button>
        </div>
      </div>
    </div>

    <!-- 人员选择器组件 -->
    <GenericSelector
      v-model:visible="showUserSelector"
      :mode="selectorMode"
      :title="selectorMode === 'add' ? '添加人员' : '删除人员'"
      :left-title="selectorMode === 'add' ? '可添加人员' : '当前人员'"
      :right-title="selectorMode === 'add' ? '待添加人员' : '待删除人员'"
      :fetch-available-api="selectorMode === 'add' ? fetchAllUsers : fetchCurrentUsers"
      :fetch-selected-api="selectorMode === 'add' ? fetchTaskUsers : undefined"
      :filter-selected="filterUsers"
      :loading="saving"
      :item-config="{ id: 'id', label: 'username', sublabel: 'deptName' }"
      :use-tree="true"
      :tree-transform="transformUsersToTree"
      :tree-props="{ children: 'children', label: 'displayName', id: 'id' }"
      :only-leaf-selectable="true"
      unit-name="人"
      search-placeholder="搜索人员..."
      @confirm="handleUserSelectConfirm"
      @cancel="closeSelectorModal"
    />
  </AdminLayout>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElPagination, ElMessage, ElMessageBox } from 'element-plus';
import { AdminLayout } from '@/views/admin';
import { TaskCard, TaskStatics } from './components';
import { GenericSelector } from '@/components/base';
import { LearningTaskAdd } from '@/views/public/task';
import type { TaskVO, UserVO } from '@/types';
import { learningTaskApi } from '@/apis/study';
import { userApi } from '@/apis/system';

defineOptions({
  name: 'TaskManageView'
});

// 视图控制
const currentView = ref<'list' | 'add' | 'edit' | 'statistics'>('list');
const currentTaskId = ref<string | undefined>(undefined);
const currentTaskName = ref<string>('');

const loading = ref(false);
const taskList = ref<TaskVO[]>([]);

const pagination = ref({
  current: 1,
  pageSize: 9,
  total: 0
});

// 弹窗控制
const showTaskDetail = ref(false);
const showDeleteConfirm = ref(false);
const showUserList = ref(false);
const showUserSelector = ref(false);

// 查看和删除的任务
const viewingTask = ref<TaskVO | null>(null);
const deletingTask = ref<TaskVO | null>(null);
const deleting = ref(false);

// 人员管理相关
const managingTask = ref<TaskVO | null>(null);
const selectorMode = ref<'add' | 'remove'>('add');
const currentUsers = ref<UserVO[]>([]);
const saving = ref(false);

onMounted(() => {
  loadTaskList();
});

/**
 * 加载任务列表
 */
async function loadTaskList() {
  try {
    loading.value = true;
    const response = await learningTaskApi.getTaskPage(
      { pageNumber: pagination.value.current, pageSize: pagination.value.pageSize },
      {}
    );
    
    if (response.success && response.pageDomain) {
      taskList.value = response.pageDomain.dataList || [];
      pagination.value.total = response.pageDomain.pageParam.totalElements || 0;
    }
  } catch (error) {
    console.error('加载任务列表失败:', error);
    ElMessage.error('加载任务列表失败');
  } finally {
    loading.value = false;
  }
}

/**
 * 新增任务
 */
function handleAdd() {
  currentView.value = 'add';
  currentTaskId.value = undefined;
}

/**
 * 查看任务
 */
async function handleView(task: TaskVO) {
  try {
    const res = await learningTaskApi.getTaskById(task.learningTask.taskID!);
    if (res.success && res.data) {
      viewingTask.value = res.data;
      showTaskDetail.value = true;
    }
  } catch (error) {
    console.error('加载任务详情失败:', error);
    ElMessage.error('加载任务详情失败');
  }
}

/**
 * 编辑任务
 */
function handleEdit(task: TaskVO) {
  currentView.value = 'edit';
  currentTaskId.value = task.learningTask.taskID;
}

/**
 * 发布任务
 */
async function handlePublish(task: TaskVO) {
  try {
    await ElMessageBox.confirm(
      `确定要发布任务 "${task.learningTask.name}" 吗？`,
      '确认发布',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    const response = await learningTaskApi.changeTaskStatus({
      ...task.learningTask,
      status: 1
    });
    if (response.success) {
      ElMessage.success('任务发布成功');
      loadTaskList();
    } else {
      ElMessage.error(response.message || '发布失败');
    }
  } catch (error) {
    if (error === 'cancel') return;
    console.error('发布任务失败:', error);
    ElMessage.error('发布任务失败');
  }
}

/**
 * 下架任务
 */
async function handleUnpublish(task: TaskVO) {
  try {
    await ElMessageBox.confirm(
      `确定要下架任务 "${task.learningTask.name}" 吗？`,
      '确认下架',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    const response = await learningTaskApi.changeTaskStatus({
      ...task.learningTask,
      status: 2
    });
    if (response.success) {
      ElMessage.success('任务已下架');
      loadTaskList();
    } else {
      ElMessage.error(response.message || '下架失败');
    }
  } catch (error) {
    if (error === 'cancel') return;
    console.error('下架任务失败:', error);
    ElMessage.error('下架任务失败');
  }
}

/**
 * 统计
 */
function handleStatistics(task: TaskVO) {
  currentView.value = 'statistics';
  currentTaskId.value = task.learningTask.taskID;
  currentTaskName.value = task.learningTask.name || '';
}

/**
 * 修改人员 - 显示当前人员列表
 */
async function handleUpdateUser(task: TaskVO) {
  managingTask.value = task;
  
  try {
    // 加载任务详情（包含已分配的用户）
    const taskRes = await learningTaskApi.getTaskById(task.learningTask.taskID!);
    if (taskRes.success && taskRes.data) {
      const taskUsers = taskRes.data.taskUsers || [];
      const assignedUserIds = taskUsers.map(tu => tu.userID!);
      
      // 加载用户详情（批量查询）
      if (assignedUserIds.length > 0) {
        const usersRes = await userApi.getUserList({});
        if (usersRes.success && usersRes.dataList) {
          currentUsers.value = usersRes.dataList.filter(user => 
            assignedUserIds.includes(user.id!)
          );
        }
      } else {
        currentUsers.value = [];
      }
    }
    
    showUserList.value = true;
  } catch (error) {
    console.error('加载用户数据失败:', error);
    ElMessage.error('加载用户数据失败');
  }
}

/**
 * 删除任务
 */
function handleDelete(task: TaskVO) {
  deletingTask.value = task;
  showDeleteConfirm.value = true;
}

/**
 * 确认删除
 */
async function confirmDelete() {
  if (!deletingTask.value) return;
  
  deleting.value = true;
  
  try {
    const res = await learningTaskApi.deleteTask(deletingTask.value.learningTask.taskID!);
    if (res.success) {
      ElMessage.success('删除成功');
      showDeleteConfirm.value = false;
      deletingTask.value = null;
      loadTaskList();
    } else {
      ElMessage.error(res.message || '删除失败');
    }
  } catch (error) {
    console.error('删除任务失败:', error);
    ElMessage.error('删除任务失败');
  } finally {
    deleting.value = false;
  }
}

/**
 * 关闭人员列表弹窗
 */
function closeUserList() {
  showUserList.value = false;
  managingTask.value = null;
  currentUsers.value = [];
}

/**
 * 获取所有用户的API函数
 */
async function fetchAllUsers() {
  const filter: any = { username: undefined };
  return await userApi.getUserList(filter);
}

/**
 * 获取当前任务用户的API函数（用于删除模式）
 */
async function fetchCurrentUsers() {
  // 删除模式时，左侧显示当前任务的用户列表
  return {
    success: true,
    dataList: currentUsers.value,
    code: 200,
    message: '',
    login: true,
    auth: true
  };
}

/**
 * 获取任务已分配用户的API函数
 */
async function fetchTaskUsers() {
  if (!managingTask.value || !managingTask.value.learningTask.taskID) {
    return {
      success: true,
      dataList: [],
      code: 200,
      message: '',
      login: true,
      auth: true
    };
  }
  
  // 从任务详情中获取用户列表
  const result = await learningTaskApi.getTaskUsers(managingTask.value.learningTask.taskID);
  if (result.success && result.dataList) {
    // 将返回的用户列表转换为UserVO格式
    const users = (result.dataList || []).map((item: any) => ({
      id: item.userID,
      username: item.username,
      deptID: item.deptID,
      deptName: item.deptName,
      parentID: item.parentID
    }));
    return {
      success: true,
      dataList: users,
      code: 200,
      message: '',
      login: true,
      auth: true
    };
  }
  
  return {
    success: false,
    dataList: [],
    code: result.code || 500,
    message: result.message || '获取任务用户失败',
    login: true,
    auth: true
  };
}

/**
 * 过滤已选用户
 */
function filterUsers(available: any[], selected: any[]) {
  const selectedIds = new Set(selected.map(item => item.id));
  return available.filter(item => !selectedIds.has(item.id));
}

/**
 * 将用户扁平数据转换为树形结构（按部门分组）
 */
function transformUsersToTree(flatData: any[]): any[] {
  if (!flatData || flatData.length === 0) {
    return [];
  }
  
  // 按部门分组
  const deptMap = new Map<string, any>();
  const tree: any[] = [];
  
  flatData.forEach(item => {
    const deptID = item.deptID || 'unknown';
    const deptName = item.deptName || '未分配部门';
    
    if (!deptMap.has(deptID)) {
      // 创建部门节点
      deptMap.set(deptID, {
        id: `dept_${deptID}`, // 使用特殊前缀避免与用户ID冲突
        displayName: deptName,
        deptID: deptID,
        deptName: deptName,
        parentID: item.parentID,
        children: [],
        isDept: true // 标记这是部门节点
      });
    }
    
    // 添加用户到部门的children中
    const deptNode = deptMap.get(deptID);
    if (deptNode) {
      deptNode.children.push({
        ...item,
        displayName: item.username || item.id,
        isDept: false // 标记这是用户节点
      });
    }
  });
  
  // 构建部门层级关系
  const deptNodes = Array.from(deptMap.values());
  const deptTreeMap = new Map<string, any>();
  
  // 初始化所有部门节点
  deptNodes.forEach(dept => {
    deptTreeMap.set(dept.deptID, { ...dept });
  });
  
  // 构建部门树
  deptNodes.forEach(dept => {
    const node = deptTreeMap.get(dept.deptID);
    if (!node) return;
    
    if (!dept.parentID || dept.parentID === '0' || dept.parentID === '') {
      // 根部门
      tree.push(node);
    } else {
      // 子部门
      const parent = deptTreeMap.get(dept.parentID);
      if (parent) {
        // 将用户节点暂存
        const users = node.children || [];
        node.children = [];
        
        // 添加部门到父部门
        if (!parent.children) {
          parent.children = [];
        }
        parent.children.push(node);
        
        // 将用户添加回来（放在部门子节点之后）
        node.children = users;
      } else {
        // 找不到父节点，作为根节点
        tree.push(node);
      }
    }
  });
  
  return tree;
}

/**
 * 显示添加人员选择器
 */
function showAddUserSelector() {
  selectorMode.value = 'add';
  showUserSelector.value = true;
}

/**
 * 显示删除人员选择器
 */
function showRemoveUserSelector() {
  selectorMode.value = 'remove';
  showUserSelector.value = true;
}

/**
 * 关闭选择器弹窗
 */
function closeSelectorModal() {
  showUserSelector.value = false;
}

/**
 * 处理用户选择器确认事件
 */
async function handleUserSelectConfirm(selectedUsers: any[]) {
  if (!managingTask.value || selectedUsers.length === 0) {
    ElMessage.warning('请选择要操作的人员');
    return;
  }
  
  saving.value = true;
  
  try {
    const userIds = selectedUsers.map(u => u.id!);
    
    if (selectorMode.value === 'add') {
      // 执行添加操作
      for (const userID of userIds) {
        await learningTaskApi.assignTaskToUser(managingTask.value.learningTask.taskID!, userID);
      }
      ElMessage.success(`成功添加 ${userIds.length} 位人员`);
      
      // 更新当前用户列表
      currentUsers.value.push(...(selectedUsers as UserVO[]));
    } else {
      // 执行删除操作
      for (const userID of userIds) {
        await learningTaskApi.removeTaskFromUser(managingTask.value.learningTask.taskID!, userID);
      }
      ElMessage.success(`成功删除 ${userIds.length} 位人员`);
      
      // 更新当前用户列表
      currentUsers.value = currentUsers.value.filter(user => 
        !userIds.includes(user.id!)
      );
    }
    
    closeSelectorModal();
    loadTaskList();
  } catch (error) {
    console.error('人员操作失败:', error);
    ElMessage.error('人员操作失败');
  } finally {
    saving.value = false;
  }
}

/**
 * 获取状态样式类
 */
function getStatusClass(status?: number) {
  switch (status) {
    case 0:
      return 'status-draft';
    case 1:
      return 'status-ongoing';
    case 2:
      return 'status-ended';
    default:
      return '';
  }
}

/**
 * 获取状态文本
 */
function getStatusText(status?: number, startTime?: string, endTime?: string): string {
  if (status === 0) return '草稿';
  if (status === 1) {
    const now = new Date();
    const start = new Date(startTime!);
    const end = new Date(endTime!);
    if (now >= start && now <= end) {
      return '进行中';
    } else if (now < start) {
      return '未开始';
    } else {
      return '已结束';
    }
  }
  if (status === 2) return '下架';
  return '未知';
}

/**
 * 格式化日期
 */
function formatDate(dateStr?: string) {
  if (!dateStr) return '-';
  const date = new Date(dateStr);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
}

/**
 * 每页条数改变
 */
function handleSizeChange() {
  pagination.value.current = 1;
  loadTaskList();
}

/**
 * 当前页改变
 */
function handleCurrentChange() {
  loadTaskList();
}

/**
 * 表单保存成功
 */
function handleFormSuccess() {
  currentView.value = 'list';
  currentTaskId.value = undefined;
  loadTaskList();
}

/**
 * 取消表单
 */
function handleFormCancel() {
  currentView.value = 'list';
  currentTaskId.value = undefined;
}

/**
 * 从统计页面返回列表
 */
function handleStatisticsBack() {
  currentView.value = 'list';
  currentTaskId.value = undefined;
  currentTaskName.value = '';
}
</script>

<style lang="scss" scoped>
.task-management {
  height: 100%;
  background: #fff;
}

.task-manage-view {
  padding: 24px;
  background: #FFFFFF;
  min-height: calc(100vh - 100px);
}

// 头部
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 48px;
}

.title {
  font-size: 16px;
  font-weight: 400;
  line-height: 1.5em;
  letter-spacing: -1.953125%;
  color: #101828;
  margin: 0;
}

// 任务卡片列表
.task-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(480px, 1fr));
  gap: 16px;
  margin-bottom: 32px;
}

// 统计视图样式
.task-statistics-view {
  padding: 24px;
  background: #FFFFFF;
  min-height: calc(100vh - 100px);
}

.statistics-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e0e0e0;
}

.btn-back {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 8px 16px;
  border: 1px solid #dcdfe6;
  background: #fff;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  color: #606266;
  transition: all 0.3s;

  &:hover {
    color: #409eff;
    border-color: #409eff;
  }

  .arrow-left {
    font-size: 16px;
  }
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

// 弹窗样式
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.modal-content {
  background: #fff;
  border-radius: 8px;
  width: 90%;
  max-width: 700px;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);

  &.small {
    max-width: 500px;
  }

  &.large {
    max-width: 900px;
  }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;
}

.modal-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.modal-close {
  width: 32px;
  height: 32px;
  border: none;
  background: #f5f7fa;
  border-radius: 50%;
  cursor: pointer;
  font-size: 18px;
  color: #909399;
  transition: all 0.3s;

  &:hover {
    background: #ecf5ff;
    color: #409eff;
  }
}

.modal-body {
  flex: 1;
  overflow-y: auto;
  padding: 20px 24px;
}

.modal-footer {
  padding: 16px 24px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.confirm-text {
  font-size: 15px;
  color: #606266;
  line-height: 1.6;
  margin: 0;
}

// 任务详情样式
.task-detail {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.detail-section {
  background: #f5f7fa;
  padding: 16px;
  border-radius: 6px;
}

.detail-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 16px 0;
  padding-bottom: 12px;
  border-bottom: 2px solid #e0e0e0;
}

.detail-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.detail-row {
  display: flex;
  font-size: 14px;
}

.detail-label {
  color: #909399;
  min-width: 100px;
  font-weight: 500;
}

.detail-value {
  color: #606266;
  flex: 1;
}

.detail-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.list-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 12px;
  background: #fff;
  border-radius: 4px;
  transition: all 0.3s;

  &:hover {
    background: #ecf5ff;
  }
}

.item-index {
  color: #909399;
  font-weight: 600;
  min-width: 24px;
}

.item-name {
  color: #606266;
  flex: 1;
}

.status-badge {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;

  &.status-draft {
    background: #f4f4f5;
    color: #909399;
  }

  &.status-ongoing {
    background: #e1f3d8;
    color: #67c23a;
  }

  &.status-ended {
    background: #f0f9ff;
    color: #409eff;
  }
}

// 人员列表样式
.user-list-actions {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
}

// .btn-success,
// .btn-danger,
// .btn-default {
//   padding: 10px 24px;
//   border-radius: 4px;
//   font-size: 14px;
//   cursor: pointer;
//   transition: all 0.3s;
//   border: none;

//   .icon {
//     margin-right: 4px;
//   }

//   &:disabled {
//     opacity: 0.6;
//     cursor: not-allowed;
//   }
// }

// .btn-success {
//   background: #67c23a;
//   color: #fff;

//   &:hover:not(:disabled) {
//     background: #85ce61;
//   }
// }

// .btn-danger {
//   background: #f56c6c;
//   color: #fff;

//   &:hover:not(:disabled) {
//     background: #f78989;
//   }
// }

// .btn-default {
//   background: #fff;
//   color: #606266;
//   border: 1px solid #dcdfe6;

//   &:hover {
//     color: #409eff;
//     border-color: #409eff;
//   }
// }

.current-user-list {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 20px;
  background: #fafafa;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 2px solid #e0e0e0;

  h4 {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin: 0;
  }
}

.count-badge {
  background: #409eff;
  color: #fff;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 13px;
  font-weight: 500;
}

.empty-list {
  text-align: center;
  padding: 60px 20px;
  color: #909399;

  .empty-icon {
    font-size: 64px;
    margin-bottom: 16px;
  }

  p {
    margin: 0;
    font-size: 15px;
  }
}

.user-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 12px;
}

.user-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: #fff;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  transition: all 0.3s;

  &:hover {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    border-color: #409eff;
  }
}

.user-avatar {
  width: 40px;
  height: 40px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  font-weight: bold;
  text-transform: uppercase;
}

.user-info {
  flex: 1;
  min-width: 0;

  .user-name {
    font-size: 14px;
    font-weight: 500;
    color: #303133;
    margin-bottom: 4px;
  }

  .user-dept {
    font-size: 12px;
    color: #909399;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
</style>

