<template>
  <!-- 密码验证界面 -->
  <div v-if="!isAuthenticated" class="auth-container">
    <div class="auth-card">
      <div class="auth-header">
        <h2>🔒 工作时间管理</h2>
        <p>请输入访问密码</p>
      </div>
      <div class="pin-input-container">
        <div class="pin-input">
          <input 
            v-for="(digit, index) in 6" 
            :key="index"
            :ref="`pinInput${index}`"
            v-model="pinDigits[index]"
            type="text"
            maxlength="1"
            class="pin-digit"
            readonly
            @click="focusHiddenInput"
          />
        </div>
        <!-- 隐藏的输入框用于连续输入 -->
        <input
          ref="hiddenInput"
          type="text"
          class="hidden-input"
          @input="onHiddenInput"
          @keydown="onHiddenKeydown"
          @paste="onPinPaste"
          autocomplete="off"
          maxlength="6"
        />
        <div class="pin-error" v-if="pinError">
          {{ pinError }}
        </div>
        <div class="pin-hint">
          默认密码：961031
        </div>
      </div>
    </div>
  </div>

  <!-- 主应用界面 -->
  <div v-else class="app-container">
    <div :class="['container', { 'fullscreen': isFullscreen }]">
      <!-- 头部 -->
      <div class="header">
        <div class="header-content">
          <div class="header-left">
            <h1>📝 滴答清单</h1>
            <p>高效管理您的任务，提升工作效率</p>
          </div>
          <div class="header-right">
            <button @click="toggleFullscreen" class="btn btn-secondary fullscreen-btn">
              {{ isFullscreen ? '🔄 退出全屏' : '⛶ 全屏' }}
            </button>
          </div>
        </div>
      </div>

      <!-- 通知组件 -->
      <div v-if="notification" class="notification" :class="notification.type">
        <div class="notification-content">
          <span class="notification-icon">
            {{ notification.type === 'success' ? '✅' : notification.type === 'error' ? '❌' : 'ℹ️' }}
          </span>
          <span class="notification-message">{{ notification.message }}</span>
        </div>
      </div>

      <!-- 统计信息 -->
      <div class="stats">
        <div class="stat-item">
          <div class="stat-number">{{ totalTasks }}</div>
          <div class="stat-label">总任务</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ completedTasks }}</div>
          <div class="stat-label">已完成</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ pendingTasks }}</div>
          <div class="stat-label">待完成</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ todayTasks }}</div>
          <div class="stat-label">今日任务</div>
        </div>
      </div>

      <!-- 菜单导航 -->
      <div class="menu-nav">
        <button 
          @click="currentMenu = 'tasks'" 
          :class="['menu-btn', { active: currentMenu === 'tasks' }]"
        >
          📝 任务管理
        </button>
        <button 
          @click="currentMenu = 'quadrant'" 
          :class="['menu-btn', { active: currentMenu === 'quadrant' }]"
        >
          🎯 四象限
        </button>
        <button 
          @click="currentMenu = 'calendar'" 
          :class="['menu-btn', { active: currentMenu === 'calendar' }]"
        >
          📅 日历看板
        </button>
        <button 
          @click="currentMenu = 'analysis'" 
          :class="['menu-btn', { active: currentMenu === 'analysis' }]"
        >
          📊 工作分析
        </button>
        <button 
          @click="currentMenu = 'data'" 
          :class="['menu-btn', { active: currentMenu === 'data' }]"
        >
          💾 数据管理
        </button>
      </div>

      <!-- 任务管理页面 -->
      <div v-if="currentMenu === 'tasks'" class="menu-content">
        <!-- 项目管理 -->
        <div class="project-section">
          <div class="project-header">
            <h3>📁 项目管理</h3>
            <button @click="showAddProject = true" class="btn btn-secondary">
              <span>➕</span>
              新建项目
            </button>
          </div>
          
          <!-- 项目列表 -->
          <div class="project-list">
            <button
              v-for="project in projects"
              :key="project.id"
              @click="currentProject = project.id"
              :class="['project-item', { active: currentProject === project.id }]"
            >
              <span class="project-name">{{ project.name }}</span>
              <span class="project-count">({{ getProjectTaskCount(project.id) }})</span>
            </button>
          </div>
        </div>

        <!-- 添加项目弹窗 -->
        <div v-if="showAddProject" class="modal-overlay" @click="showAddProject = false">
          <div class="modal" @click.stop>
            <h3>新建项目</h3>
            <input
              v-model="newProjectName"
              @keyup.enter="addProject"
              placeholder="输入项目名称..."
              class="modal-input"
            />
            <div class="modal-actions">
              <button @click="showAddProject = false" class="btn btn-secondary">取消</button>
              <button @click="addProject" class="btn btn-primary">创建</button>
            </div>
          </div>
        </div>

        <!-- 添加任务 -->
        <div class="input-group">
          <input
            v-model="newTask"
            @keyup.enter="addTask"
            placeholder="输入新任务..."
            type="text"
          />
          <select v-model="newTaskProject" class="btn btn-secondary">
            <option value="">📁 选择项目</option>
            <option v-for="project in projects" :key="project.id" :value="project.id">
              📁 {{ project.name }}
            </option>
          </select>
          <select v-model="newTaskType" class="btn btn-secondary">
            <option value="requirement">需求分析</option>
            <option value="documentation">文档编写</option>
            <option value="development">开发代码</option>
            <option value="testing">测试</option>
            <option value="operation">运维</option>
            <option value="other">其他</option>
          </select>
          <select v-model="newTaskPriority" class="btn btn-secondary">
            <option value="low">低优先级</option>
            <option value="medium">中优先级</option>
            <option value="high">高优先级</option>
          </select>
          <select v-model="newTaskImportance" class="btn btn-secondary">
            <option value="low">低重要性</option>
            <option value="medium">中重要性</option>
            <option value="high">高重要性</option>
          </select>
          <select v-model="newTaskUrgency" class="btn btn-secondary">
            <option value="low">低紧急性</option>
            <option value="medium">中紧急性</option>
            <option value="high">高紧急性</option>
          </select>
          <input
            v-model="newTaskStartTime"
            type="datetime-local"
            class="btn btn-secondary"
            style="min-width: 180px;"
          />
          <input
            v-model="newTaskEndTime"
            type="datetime-local"
            class="btn btn-secondary"
            style="min-width: 180px;"
          />
          <button @click="addTask" class="btn btn-primary">
            <span>➕</span>
            添加
          </button>
        </div>

        <!-- 过滤器 -->
        <div class="filters">
          <button
            v-for="filter in filters"
            :key="filter.value"
            @click="currentFilter = filter.value"
            :class="['filter-btn', { active: currentFilter === filter.value }]"
          >
            {{ filter.label }}
          </button>
          <select v-model="currentTypeFilter" class="filter-btn" style="min-width: 120px;">
            <option value="">所有类型</option>
            <option value="requirement">需求分析</option>
            <option value="documentation">文档编写</option>
            <option value="development">开发代码</option>
            <option value="testing">测试</option>
            <option value="operation">运维</option>
            <option value="other">其他</option>
          </select>
          <button @click="currentProject = ''" class="filter-btn" :class="{ active: currentProject === '' }">
            所有项目
          </button>
        </div>

        <!-- 任务列表 -->
        <div v-if="filteredTasks.length > 0" class="todo-list">
          <div
            v-for="task in filteredTasks"
            :key="task.id"
            :class="['todo-item', { completed: task.completed }]"
          >
            <!-- 复选框 -->
            <div
              :class="['todo-checkbox', { checked: task.completed }]"
              @click="toggleTask(task.id)"
            ></div>

            <!-- 任务内容 -->
            <div class="todo-content">
              <div class="todo-text">
                <span>{{ task.text }}</span>
              </div>
              <div class="todo-meta">
                <span class="todo-project" :class="`project-${task.projectId}`">
                  {{ getProjectName(task.projectId) }}
                </span>
                <span class="todo-type" :class="`type-${task.type}`">
                  {{ getTypeText(task.type) }}
                </span>
                <span class="todo-priority" :class="`priority-${task.priority}`">
                  {{ getPriorityText(task.priority) }}
                </span>
                <span class="todo-time">
                  <span v-if="task.startTime">🕐 {{ formatDateTime(task.startTime) }}</span>
                  <span v-if="task.endTime"> - {{ formatDateTime(task.endTime) }}</span>
                </span>
                <span class="todo-duration" v-if="task.startTime && task.endTime">
                  ⏱️ {{ calculateDuration(task.startTime, task.endTime) }}
                  <span v-if="isLongTask(task)" class="long-task-indicator">⏱️</span>
                </span>
                <span class="todo-timer" v-if="task.timerRunning || task.timerDuration">
                  <span v-if="task.timerRunning" class="timer-running">
                    ⏱️ {{ formatTimer(task) }}
                  </span>
                  <span v-else-if="task.timerDuration" class="timer-stopped">
                    ⏱️ {{ formatDuration(task.timerDuration) }}
                  </span>
                </span>
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="todo-actions">
              <button
                v-if="!task.startTime || !task.endTime"
                @click="toggleTimer(task)"
                :class="['btn-icon', task.timerRunning ? 'btn-stop' : 'btn-start']"
                :title="task.timerRunning ? '停止计时' : '开始计时'"
              >
                {{ task.timerRunning ? '⏹️' : '▶️' }}
              </button>
              <button
                @click="openEditTaskModal(task)"
                class="btn-icon btn-edit"
                title="编辑任务"
              >
                ✏️
              </button>
              <button
                @click="deleteTask(task.id)"
                class="btn-icon btn-delete"
                title="删除任务"
              >
                🗑️
              </button>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-else class="empty-state">
          <h3>🎉 太棒了！</h3>
          <p v-if="currentFilter === 'all'">
            您还没有任何任务。开始添加您的第一个任务吧！
          </p>
          <p v-else-if="currentFilter === 'completed'">
            还没有完成的任务。继续加油！
          </p>
          <p v-else-if="currentFilter === 'pending'">
            所有任务都已完成！您真是太棒了！
          </p>
        </div>
      </div>

      <!-- 工作分析页面 -->
      <div v-if="currentMenu === 'analysis'" class="menu-content">
        <div class="work-analysis">
          <div class="analysis-header">
            <div class="analysis-title">
              <h3>📊 工作分析</h3>
              <div class="date-range-display">
                {{ getSelectedDateText() }}
              </div>
            </div>
            <div class="analysis-controls">
              <div class="date-selector">
                <label>选择日期:</label>
                <div class="date-controls">
                  <button @click="previousDate" class="date-nav-btn" title="前一天">◀</button>
                  <input 
                    v-model="analysisSelectedDate" 
                    type="date" 
                    class="date-input"
                    @change="updateAnalysisData"
                  />
                  <button @click="nextDate" class="date-nav-btn" title="后一天">▶</button>
                  <button @click="goToToday" class="date-nav-btn today-btn" title="回到今天">今天</button>
                </div>
              </div>
              <div class="time-dimension-selector">
                <button 
                  v-for="dimension in timeDimensions" 
                  :key="dimension.value"
                  @click="currentTimeDimension = dimension.value"
                  :class="['dimension-btn', { active: currentTimeDimension === dimension.value }]"
                >
                  {{ dimension.label }}
                </button>
              </div>
            </div>
          </div>

          <!-- 概览卡片 -->
          <div class="overview-section">
            <div class="overview-grid">
              <div class="overview-card">
                <div class="overview-icon">📝</div>
                <div class="overview-content">
                  <div class="overview-number">{{ getOverviewData().totalTasks }}</div>
                  <div class="overview-label">总任务数</div>
                </div>
              </div>
              <div class="overview-card">
                <div class="overview-icon">✅</div>
                <div class="overview-content">
                  <div class="overview-number">{{ getOverviewData().completedTasks }}</div>
                  <div class="overview-label">已完成</div>
                </div>
              </div>
              <div class="overview-card">
                <div class="overview-icon">⏱️</div>
                <div class="overview-content">
                  <div class="overview-number">{{ getOverviewData().totalHours }}h</div>
                  <div class="overview-label">工作时长</div>
                </div>
              </div>
              <div class="overview-card">
                <div class="overview-icon">📈</div>
                <div class="overview-content">
                  <div class="overview-number">{{ getOverviewData().completionRate }}%</div>
                  <div class="overview-label">完成率</div>
                </div>
              </div>
            </div>
          </div>

          <!-- 协调点区域 -->
          <div class="coordination-section">
            <div class="coordination-header">
              <h4>🎯 工作协调点</h4>
              <p>关键指标和效率分析</p>
            </div>
            <div class="coordination-summary">
              <div class="summary-item">
                <span class="summary-label">综合评分</span>
                <span class="summary-value">{{ getOverallScore() }}%</span>
              </div>
              <div class="summary-item">
                <span class="summary-label">状态</span>
                <span class="summary-status" :class="getOverallStatusClass()">{{ getOverallStatus() }}</span>
              </div>
            </div>
            <div class="coordination-grid">
              <!-- 效率指标 -->
              <div class="coordination-card" :class="getEfficiencyClass()">
                <div class="coordination-icon">⚡</div>
                <div class="coordination-content">
                  <div class="coordination-title">工作效率</div>
                  <div class="coordination-value">{{ getEfficiencyScore() }}%</div>
                  <div class="coordination-description">
                    基于任务完成率和时间利用率的综合评分
                  </div>
                </div>
              </div>
              
              <!-- 项目平衡 -->
              <div class="coordination-card" :class="getProjectBalanceClass()">
                <div class="coordination-icon">⚖️</div>
                <div class="coordination-content">
                  <div class="coordination-title">项目平衡</div>
                  <div class="coordination-value">{{ getProjectBalanceScore() }}%</div>
                  <div class="coordination-description">
                    多个项目间的任务分配均衡度
                  </div>
                </div>
              </div>
              
              <!-- 质量指标 -->
              <div class="coordination-card" :class="getQualityClass()">
                <div class="coordination-icon">🏆</div>
                <div class="coordination-content">
                  <div class="coordination-title">工作质量</div>
                  <div class="coordination-value">{{ getQualityScore() }}%</div>
                  <div class="coordination-description">
                    基于任务完成质量和时间管理的综合评估
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 图表区域 -->
          <div class="charts-section">
            <!-- 第一行：项目占比、类型占比、活动趋势 -->
            <div class="charts-row">
              <div class="charts-grid">
                <!-- 项目占比饼图 -->
                <div class="chart-card pie-chart-card">
                  <div class="chart-header">
                    <h4>📊 项目占比</h4>
                    <div class="chart-legend">
                      <div v-for="item in getProjectChartData()" :key="item.name" class="legend-item">
                        <div class="legend-color" :style="{ backgroundColor: item.color }"></div>
                        <span class="legend-label">{{ item.name }}</span>
                        <span class="legend-value">{{ item.percentage }}%</span>
                      </div>
                    </div>
                  </div>
                  <div class="pie-chart">
                    <svg width="200" height="200" viewBox="0 0 200 200">
                      <!-- 背景圆环 -->
                      <circle cx="100" cy="100" r="80" fill="none" stroke="#f7fafc" stroke-width="20"/>
                      <!-- 数据圆环 -->
                      <g v-for="(item, index) in getProjectChartData()" :key="item.name">
                        <circle 
                          cx="100" 
                          cy="100" 
                          r="80" 
                          fill="none" 
                          :stroke="item.color" 
                          stroke-width="20"
                          :stroke-dasharray="item.dashArray"
                          :stroke-dashoffset="item.dashOffset"
                          transform="rotate(-90 100 100)"
                          class="pie-segment"
                        />
                      </g>
                      <!-- 中心文字 -->
                      <text x="100" y="95" text-anchor="middle" class="pie-center-text" fill="#4a5568" font-size="12" font-weight="600">
                        项目
                      </text>
                      <text x="100" y="110" text-anchor="middle" class="pie-center-text" fill="#718096" font-size="10">
                        分布
                      </text>
                    </svg>
                  </div>
                </div>

                <!-- 类型占比饼图 -->
                <div class="chart-card pie-chart-card">
                  <div class="chart-header">
                    <h4>📊 类型占比</h4>
                    <div class="chart-legend">
                      <div v-for="item in getTypeChartData()" :key="item.name" class="legend-item">
                        <div class="legend-color" :style="{ backgroundColor: item.color }"></div>
                        <span class="legend-label">{{ item.name }}</span>
                        <span class="legend-value">{{ item.percentage }}%</span>
                      </div>
                    </div>
                  </div>
                  <div class="pie-chart">
                    <svg width="200" height="200" viewBox="0 0 200 200">
                      <!-- 背景圆环 -->
                      <circle cx="100" cy="100" r="80" fill="none" stroke="#f7fafc" stroke-width="20"/>
                      <!-- 数据圆环 -->
                      <g v-for="(item, index) in getTypeChartData()" :key="item.name">
                        <circle 
                          cx="100" 
                          cy="100" 
                          r="80" 
                          fill="none" 
                          :stroke="item.color" 
                          stroke-width="20"
                          :stroke-dasharray="item.dashArray"
                          :stroke-dashoffset="item.dashOffset"
                          transform="rotate(-90 100 100)"
                          class="pie-segment"
                        />
                      </g>
                      <!-- 中心文字 -->
                      <text x="100" y="95" text-anchor="middle" class="pie-center-text" fill="#4a5568" font-size="12" font-weight="600">
                        类型
                      </text>
                      <text x="100" y="110" text-anchor="middle" class="pie-center-text" fill="#718096" font-size="10">
                        分布
                      </text>
                    </svg>
                  </div>
                </div>

                <!-- 活动趋势折线图 -->
                <div class="chart-card trend-chart-card">
                  <div class="chart-header">
                    <h4>📈 活动趋势</h4>
                  </div>
                  <div class="line-chart">
                    <svg width="100%" height="250" viewBox="0 0 800 250">
                      <defs>
                        <linearGradient id="lineGradient" x1="0%" y1="0%" x2="0%" y2="100%">
                          <stop offset="0%" style="stop-color:#667eea;stop-opacity:0.8" />
                          <stop offset="100%" style="stop-color:#667eea;stop-opacity:0.1" />
                        </linearGradient>
                      </defs>
                      
                      <!-- Y轴 -->
                      <line x1="60" y1="30" x2="60" y2="180" stroke="#e2e8f0" stroke-width="2"/>
                      <!-- Y轴标签 -->
                      <g v-for="i in 6" :key="`y-${i}`">
                        <line 
                          :x1="55" 
                          :y1="30 + (i-1) * 25" 
                          :x2="60" 
                          :y2="30 + (i-1) * 25" 
                          stroke="#e2e8f0" 
                          stroke-width="1"
                        />
                        <text 
                          x="50" 
                          :y="30 + (i-1) * 25 + 4" 
                          text-anchor="end" 
                          font-size="10" 
                          fill="#718096"
                        >
                          {{ Math.max(0, getMaxTaskCount() - (i-1) * Math.ceil(getMaxTaskCount() / 5)) }}
                        </text>
                      </g>
                      
                      <!-- X轴 -->
                      <line x1="60" y1="180" x2="760" y2="180" stroke="#e2e8f0" stroke-width="2"/>
                      <!-- X轴标签 -->
                      <g v-for="(label, index) in getXAxisLabels()" :key="`x-${index}`">
                        <text 
                          :x="60 + (index / (getXAxisLabels().length - 1)) * 700" 
                          y="195" 
                          text-anchor="middle" 
                          font-size="10" 
                          fill="#718096"
                        >
                          {{ label }}
                        </text>
                      </g>
                      
                      <!-- 网格线 -->
                      <g v-for="i in 5" :key="`grid-y-${i}`">
                        <line 
                          x1="60" 
                          :y1="30 + i * 25" 
                          x2="760" 
                          :y2="30 + i * 25" 
                          stroke="#f7fafc" 
                          stroke-width="1"
                          stroke-dasharray="2,2"
                        />
                      </g>
                      
                      <!-- 数据点和曲线 -->
                      <g v-for="(point, index) in getTrendData()" :key="index">
                        <circle 
                          :cx="point.x" 
                          :cy="point.y" 
                          r="5" 
                          fill="#667eea"
                          stroke="white"
                          stroke-width="2"
                          class="trend-point"
                        />
                      </g>
                      
                      <!-- 平滑曲线 -->
                      <path 
                        :d="getTrendCurvePath()" 
                        fill="none"
                        stroke="#667eea" 
                        stroke-width="3"
                        class="trend-curve"
                      />
                      
                      <!-- 填充区域 -->
                      <path 
                        :d="getTrendPath()" 
                        fill="url(#lineGradient)" 
                        opacity="0.3"
                      />
                    </svg>
                  </div>
                </div>
              </div>
            </div>

            <!-- 第二行：今日时间块 -->
            <div class="charts-row">
              <!-- 今日时间块 -->
              <div class="chart-card time-blocks-card">
                <div class="chart-header">
                  <h4>🕐 今日时间块</h4>
                </div>
                <div class="time-blocks">
                  <!-- 上午时间段 (00:00-11:59) -->
                  <div class="time-period">
                    <div class="period-label">上午</div>
                    <div class="period-blocks">
                      <div 
                        v-for="hour in 12" 
                        :key="`am-${hour}`"
                        :class="['time-block', { 'has-task': getHourTaskCount(hour-1) > 0 }]"
                        :style="{ 
                          backgroundColor: getHourTaskCount(hour-1) > 0 ? getHourColor(hour-1) : '#f7fafc',
                          opacity: getHourTaskCount(hour-1) > 0 ? 0.9 : 0.3
                        }"
                      >
                        <div class="time-label">{{ (hour-1).toString().padStart(2, '0') }}:00</div>
                        <div class="task-count" v-if="getHourTaskCount(hour-1) > 0">
                          {{ getHourTaskCount(hour-1) }}个任务
                        </div>
                      </div>
                    </div>
                  </div>
                  
                  <!-- 下午时间段 (12:00-23:59) -->
                  <div class="time-period">
                    <div class="period-label">下午</div>
                    <div class="period-blocks">
                      <div 
                        v-for="hour in 12" 
                        :key="`pm-${hour}`"
                        :class="['time-block', { 'has-task': getHourTaskCount(hour+11) > 0 }]"
                        :style="{ 
                          backgroundColor: getHourTaskCount(hour+11) > 0 ? getHourColor(hour+11) : '#f7fafc',
                          opacity: getHourTaskCount(hour+11) > 0 ? 0.9 : 0.3
                        }"
                      >
                        <div class="time-label">{{ (hour+11).toString().padStart(2, '0') }}:00</div>
                        <div class="task-count" v-if="getHourTaskCount(hour+11) > 0">
                          {{ getHourTaskCount(hour+11) }}个任务
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 四象限页面 -->
      <div v-if="currentMenu === 'quadrant'" class="menu-content">
        <div class="quadrant-container">
          <div class="quadrant-header">
            <h3>🎯 四象限任务管理</h3>
            <p>按照重要性和紧急性对任务进行分类，提高工作效率</p>
          </div>
          
          <div class="quadrant-grid">
            <!-- 第一象限：重要且紧急 -->
            <div class="quadrant" :style="{ borderColor: getQuadrantColor('q1') }">
              <div class="quadrant-header" :style="{ backgroundColor: getQuadrantColor('q1') }">
                <h4>{{ getQuadrantTitle('q1') }}</h4>
                <span class="quadrant-count">{{ quadrantTasks.q1.length }}个任务</span>
              </div>
              <div class="quadrant-description">{{ getQuadrantDescription('q1') }}</div>
              <div class="quadrant-tasks">
                <div 
                  v-for="task in quadrantTasks.q1" 
                  :key="task.id"
                  :class="['quadrant-task', { completed: task.completed }]"
                  @click="selectTask(task)"
                >
                  <div class="task-checkbox" @click.stop="toggleTask(task.id)">
                    <span v-if="task.completed" class="checkmark">✓</span>
                  </div>
                  <div class="task-content">
                    <div class="task-text">{{ task.text }}</div>
                    <div class="task-meta">
                      <span class="task-project">{{ getProjectName(task.projectId) }}</span>
                      <span class="task-type">{{ getTypeText(task.type) }}</span>
                    </div>
                  </div>
                  <div class="task-actions">
                    <button @click.stop="openEditTaskModal(task)" class="btn-icon btn-edit">✏️</button>
                    <button @click.stop="deleteTask(task.id)" class="btn-icon btn-delete">🗑️</button>
                  </div>
                </div>
                <div v-if="quadrantTasks.q1.length === 0" class="empty-quadrant">
                  暂无任务
                </div>
              </div>
            </div>

            <!-- 第二象限：重要不紧急 -->
            <div class="quadrant" :style="{ borderColor: getQuadrantColor('q2') }">
              <div class="quadrant-header" :style="{ backgroundColor: getQuadrantColor('q2') }">
                <h4>{{ getQuadrantTitle('q2') }}</h4>
                <span class="quadrant-count">{{ quadrantTasks.q2.length }}个任务</span>
              </div>
              <div class="quadrant-description">{{ getQuadrantDescription('q2') }}</div>
              <div class="quadrant-tasks">
                <div 
                  v-for="task in quadrantTasks.q2" 
                  :key="task.id"
                  :class="['quadrant-task', { completed: task.completed }]"
                  @click="selectTask(task)"
                >
                  <div class="task-checkbox" @click.stop="toggleTask(task.id)">
                    <span v-if="task.completed" class="checkmark">✓</span>
                  </div>
                  <div class="task-content">
                    <div class="task-text">{{ task.text }}</div>
                    <div class="task-meta">
                      <span class="task-project">{{ getProjectName(task.projectId) }}</span>
                      <span class="task-type">{{ getTypeText(task.type) }}</span>
                    </div>
                  </div>
                  <div class="task-actions">
                    <button @click.stop="openEditTaskModal(task)" class="btn-icon btn-edit">✏️</button>
                    <button @click.stop="deleteTask(task.id)" class="btn-icon btn-delete">🗑️</button>
                  </div>
                </div>
                <div v-if="quadrantTasks.q2.length === 0" class="empty-quadrant">
                  暂无任务
                </div>
              </div>
            </div>

            <!-- 第三象限：不重要但紧急 -->
            <div class="quadrant" :style="{ borderColor: getQuadrantColor('q3') }">
              <div class="quadrant-header" :style="{ backgroundColor: getQuadrantColor('q3') }">
                <h4>{{ getQuadrantTitle('q3') }}</h4>
                <span class="quadrant-count">{{ quadrantTasks.q3.length }}个任务</span>
              </div>
              <div class="quadrant-description">{{ getQuadrantDescription('q3') }}</div>
              <div class="quadrant-tasks">
                <div 
                  v-for="task in quadrantTasks.q3" 
                  :key="task.id"
                  :class="['quadrant-task', { completed: task.completed }]"
                  @click="selectTask(task)"
                >
                  <div class="task-checkbox" @click.stop="toggleTask(task.id)">
                    <span v-if="task.completed" class="checkmark">✓</span>
                  </div>
                  <div class="task-content">
                    <div class="task-text">{{ task.text }}</div>
                    <div class="task-meta">
                      <span class="task-project">{{ getProjectName(task.projectId) }}</span>
                      <span class="task-type">{{ getTypeText(task.type) }}</span>
                    </div>
                  </div>
                  <div class="task-actions">
                    <button @click.stop="openEditTaskModal(task)" class="btn-icon btn-edit">✏️</button>
                    <button @click.stop="deleteTask(task.id)" class="btn-icon btn-delete">🗑️</button>
                  </div>
                </div>
                <div v-if="quadrantTasks.q3.length === 0" class="empty-quadrant">
                  暂无任务
                </div>
              </div>
            </div>

            <!-- 第四象限：不重要不紧急 -->
            <div class="quadrant" :style="{ borderColor: getQuadrantColor('q4') }">
              <div class="quadrant-header" :style="{ backgroundColor: getQuadrantColor('q4') }">
                <h4>{{ getQuadrantTitle('q4') }}</h4>
                <span class="quadrant-count">{{ quadrantTasks.q4.length }}个任务</span>
              </div>
              <div class="quadrant-description">{{ getQuadrantDescription('q4') }}</div>
              <div class="quadrant-tasks">
                <div 
                  v-for="task in quadrantTasks.q4" 
                  :key="task.id"
                  :class="['quadrant-task', { completed: task.completed }]"
                  @click="selectTask(task)"
                >
                  <div class="task-checkbox" @click.stop="toggleTask(task.id)">
                    <span v-if="task.completed" class="checkmark">✓</span>
                  </div>
                  <div class="task-content">
                    <div class="task-text">{{ task.text }}</div>
                    <div class="task-meta">
                      <span class="task-project">{{ getProjectName(task.projectId) }}</span>
                      <span class="task-type">{{ getTypeText(task.type) }}</span>
                    </div>
                  </div>
                  <div class="task-actions">
                    <button @click.stop="openEditTaskModal(task)" class="btn-icon btn-edit">✏️</button>
                    <button @click.stop="deleteTask(task.id)" class="btn-icon btn-delete">🗑️</button>
                  </div>
                </div>
                <div v-if="quadrantTasks.q4.length === 0" class="empty-quadrant">
                  暂无任务
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 日历看板页面 -->
      <div v-if="currentMenu === 'calendar'" class="menu-content">
        <div class="calendar-container">
          <!-- 日历导航 -->
          <div class="calendar-nav">
            <button @click="previousPeriod" class="btn btn-secondary">
              ◀️ 上期
            </button>
            <h3 class="calendar-title">{{ calendarTitle }}</h3>
            <div class="calendar-actions">
              <button @click="scrollToCurrentTime" class="btn btn-secondary current-time-btn" title="滚动到当前时间">
                🕐 当前时间
              </button>
              <button @click="nextPeriod" class="btn btn-secondary">
                下期 ▶️
              </button>
            </div>
          </div>

          <!-- 日历视图切换 -->
          <div class="calendar-views">
            <button 
              @click="switchToDayView" 
              :class="['view-btn', { active: calendarView === 'day' }]"
            >
              日视图
            </button>
            <button 
              @click="switchToWeekView" 
              :class="['view-btn', { active: calendarView === 'week' }]"
            >
              周视图
            </button>
            <button 
              @click="calendarView = 'month'" 
              :class="['view-btn', { active: calendarView === 'month' }]"
            >
              月视图
            </button>
          </div>

          <!-- 日视图 -->
          <div v-if="calendarView === 'day'" class="day-view">
            <div class="day-header">
              <h4>{{ formatDate(selectedDate) }}</h4>
              <div class="day-stats">
                <span class="stat">任务: {{ dayTasks.length }}</span>
                <span class="stat">已完成: {{ completedDayTasks.length }}</span>
                <span class="stat">工作时长: {{ dayWorkHours }}小时</span>
              </div>
            </div>
            <div class="day-timeline">
              <div 
                v-for="hour in 24" 
                :key="hour" 
                :class="['time-slot', { 'current-time': isCurrentTimeLine(hour - 1) }]"
                :data-hour="hour - 1"
              >
                <div class="time-label">{{ (hour-1).toString().padStart(2, '0') }}:00</div>
                <div class="time-content">
                  <!-- 只显示在这个小时开始的任务 -->
                  <div 
                    v-for="task in getTasksStartingAtHour(hour - 1)" 
                    :key="task.id"
                    :class="['timeline-task', { completed: task.completed }]"
                    :style="getTaskTimelineStyle(task)"
                    @click="selectTask(task)"
                  >
                    <div class="task-time">{{ formatTime(task.startTime) }}</div>
                    <div class="task-text">{{ task.text }}</div>
                    <div class="task-meta">
                      <span class="task-project">{{ getProjectName(task.projectId) }}</span>
                      <span class="task-type">{{ getTypeText(task.type) }}</span>
                    </div>
                    <div v-if="task.startTime && task.endTime" class="task-duration">
                      {{ calculateDuration(task.startTime, task.endTime) }}
                      <span v-if="isLongTask(task)" class="long-task-indicator">⏱️</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 周视图 -->
          <div v-if="calendarView === 'week'" class="week-view">
            <div class="week-grid">
              <div class="week-header">
                <div class="time-column">时间</div>
                <div 
                  v-for="day in weekDays" 
                  :key="day.date" 
                  :class="['day-column', { today: isToday(day.date) }]"
                >
                  <div class="day-name">{{ day.name }}</div>
                  <div class="day-date">{{ formatDayDate(day.date) }}</div>
                  <div class="day-task-count">{{ getDayTaskCount(day.date) }}个任务</div>
                </div>
              </div>
              <div class="week-body">
                <div 
                  v-for="hour in 24" 
                  :key="hour" 
                  :class="['time-row', { 'current-time': isCurrentTimeLine(hour - 1) }]"
                  :data-hour="hour - 1"
                >
                  <div class="time-label">{{ (hour - 1).toString().padStart(2, '0') }}:00</div>
                  <div 
                    v-for="day in weekDays" 
                    :key="day.date" 
                    class="day-cell"
                  >
                    <div 
                      v-for="task in getTasksStartingForDayAndHour(day.date, hour - 1)" 
                      :key="task.id"
                      :class="['week-task', { completed: task.completed }]"
                      :style="getWeekTaskTimelineStyle(task, day.date, hour - 1)"
                      @click="selectTask(task)"
                    >
                      <div class="task-time">{{ formatTime(task.startTime) }}</div>
                      <div class="task-text">{{ task.text }}</div>
                      <div v-if="task.startTime && task.endTime" class="task-duration">
                        {{ calculateDuration(task.startTime, task.endTime) }}
                        <span v-if="isLongTask(task)" class="long-task-indicator">⏱️</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 月视图 -->
          <div v-if="calendarView === 'month'" class="month-view">
            <div class="month-grid">
              <div class="month-header">
                <div v-for="dayName in ['日', '一', '二', '三', '四', '五', '六']" :key="dayName" class="day-name">
                  {{ dayName }}
                </div>
              </div>
              <div class="month-body">
                <div 
                  v-for="day in monthDays" 
                  :key="day.date" 
                  :class="['month-day', { 
                    'other-month': !day.isCurrentMonth,
                    'today': isToday(day.date),
                    'has-tasks': getDayTaskCount(day.date) > 0
                  }]"
                  @click="selectDate(day.date)"
                >
                  <div class="day-number">{{ day.dayNumber }}</div>
                  <div class="day-tasks">
                    <div 
                      v-for="task in getTasksForDay(day.date).slice(0, 3)" 
                      :key="task.id"
                      :class="['month-task', { completed: task.completed }]"
                      @click.stop="selectTask(task)"
                    >
                      {{ task.text }}
                    </div>
                    <div v-if="getDayTaskCount(day.date) > 3" class="more-tasks">
                      +{{ getDayTaskCount(day.date) - 3 }}个
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 任务详情弹窗 -->
          <div v-if="selectedTask" class="modal-overlay" @click="selectedTask = null">
            <div class="modal task-modal" @click.stop>
              <h3>任务详情</h3>
              <div class="task-details">
                <div class="detail-item">
                  <label>任务内容:</label>
                  <span>{{ selectedTask.text }}</span>
                </div>
                <div class="detail-item">
                  <label>所属项目:</label>
                  <span>{{ getProjectName(selectedTask.projectId) }}</span>
                </div>
                <div class="detail-item">
                  <label>任务类型:</label>
                  <span>{{ getTypeText(selectedTask.type) }}</span>
                </div>
                <div class="detail-item">
                  <label>优先级:</label>
                  <span>{{ getPriorityText(selectedTask.priority) }}</span>
                </div>
                <div class="detail-item" v-if="selectedTask.startTime">
                  <label>开始时间:</label>
                  <span>{{ formatDateTime(selectedTask.startTime) }}</span>
                </div>
                <div class="detail-item" v-if="selectedTask.endTime">
                  <label>结束时间:</label>
                  <span>{{ formatDateTime(selectedTask.endTime) }}</span>
                </div>
                <div class="detail-item" v-if="selectedTask.startTime && selectedTask.endTime">
                  <label>工作时长:</label>
                  <span>{{ calculateDuration(selectedTask.startTime, selectedTask.endTime) }}</span>
                </div>
                <div class="detail-item" v-if="selectedTask.timerDuration">
                  <label>计时时长:</label>
                  <span>{{ formatDuration(selectedTask.timerDuration) }}</span>
                </div>
                <div class="detail-item">
                  <label>状态:</label>
                  <span :class="{ completed: selectedTask.completed }">
                    {{ selectedTask.completed ? '已完成' : '进行中' }}
                  </span>
                </div>
              </div>
              <div class="modal-actions">
                <button @click="selectedTask = null" class="btn btn-secondary">关闭</button>
                <button @click="editTaskFromCalendar(selectedTask)" class="btn btn-primary">编辑</button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 数据管理页面 -->
      <div v-if="currentMenu === 'data'" class="menu-content">
        <div class="data-management">
          <h3>💾 数据管理</h3>
          
          <!-- 服务器同步状态 -->
          <div class="sync-status">
            <div class="sync-info">
              <span class="sync-indicator" :class="{ online: isOnline, offline: !isOnline }">
                {{ isOnline ? '🟢 服务器在线' : '🔴 服务器离线' }}
              </span>
              <span v-if="lastServerUpdate" class="last-update">
                最后同步: {{ formatDateTime(lastServerUpdate) }}
              </span>
            </div>
            <div class="sync-actions">
              <button @click="checkServerConnection" class="btn btn-secondary">
                🔄 检查连接
              </button>
              <button @click="syncToServer" :disabled="!isOnline || syncStatus === 'syncing'" class="btn btn-primary">
                {{ syncStatus === 'syncing' ? '⏳ 同步中...' : '📤 同步到服务器' }}
              </button>
              <button @click="syncFromServer" :disabled="!isOnline || syncStatus === 'syncing'" class="btn btn-primary">
                {{ syncStatus === 'syncing' ? '⏳ 同步中...' : '📥 从服务器同步' }}
              </button>
            </div>
          </div>
          
          <div class="data-actions">
            <button @click="exportData" class="btn btn-secondary">
              📤 导出数据
            </button>
            <button @click="importData" class="btn btn-secondary">
              📥 导入数据
            </button>
            <button @click="clearData" class="btn btn-secondary">
              🗑️ 清空数据
            </button>
            <button @click="clearDefaultData" class="btn btn-secondary">
              🧹 清除默认数据
            </button>
            <input
              ref="fileInput"
              type="file"
              accept=".json"
              @change="handleFileImport"
              style="display: none;"
            />
          </div>
        </div>
      </div>

      <!-- 任务编辑弹窗 -->
      <div v-if="showEditTaskModal" class="modal-overlay" @click="closeEditTaskModal">
        <div class="modal edit-task-modal" @click.stop>
          <div class="modal-header">
            <h3>✏️ 编辑任务</h3>
            <button @click="closeEditTaskModal" class="btn-close">✕</button>
          </div>
          
          <div class="modal-body">
            <!-- 任务基本信息 -->
            <div class="edit-section">
              <h4>📝 基本信息</h4>
              <div class="form-group">
                <label>任务内容:</label>
                <input
                  v-model="editingTaskData.text"
                  type="text"
                  placeholder="输入任务内容..."
                  class="form-input"
                />
              </div>
              
              <div class="form-row">
                <div class="form-group">
                  <label>所属项目:</label>
                  <select v-model="editingTaskData.projectId" class="form-select">
                    <option value="">📁 选择项目</option>
                    <option v-for="project in projects" :key="project.id" :value="project.id">
                      📁 {{ project.name }}
                    </option>
                  </select>
                </div>
                
                <div class="form-group">
                  <label>任务类型:</label>
                  <select v-model="editingTaskData.type" class="form-select">
                    <option value="requirement">需求分析</option>
                    <option value="documentation">文档编写</option>
                    <option value="development">开发代码</option>
                    <option value="testing">测试</option>
                    <option value="operation">运维</option>
                    <option value="other">其他</option>
                  </select>
                </div>
              </div>
            </div>

            <!-- 优先级设置 -->
            <div class="edit-section">
              <h4>🎯 优先级设置</h4>
              <div class="form-row">
                <div class="form-group">
                  <label>优先级:</label>
                  <select v-model="editingTaskData.priority" class="form-select">
                    <option value="low">低优先级</option>
                    <option value="medium">中优先级</option>
                    <option value="high">高优先级</option>
                  </select>
                </div>
                
                <div class="form-group">
                  <label>重要性:</label>
                  <select v-model="editingTaskData.importance" class="form-select">
                    <option value="low">低重要性</option>
                    <option value="medium">中重要性</option>
                    <option value="high">高重要性</option>
                  </select>
                </div>
                
                <div class="form-group">
                  <label>紧急性:</label>
                  <select v-model="editingTaskData.urgency" class="form-select">
                    <option value="low">低紧急性</option>
                    <option value="medium">中紧急性</option>
                    <option value="high">高紧急性</option>
                  </select>
                </div>
              </div>
            </div>

            <!-- 时间设置 -->
            <div class="edit-section">
              <h4>🕐 时间设置</h4>
              <div class="form-row">
                <div class="form-group">
                  <label>开始时间:</label>
                  <input
                    v-model="editingTaskData.startTime"
                    type="datetime-local"
                    class="form-input"
                  />
                </div>
                
                <div class="form-group">
                  <label>结束时间:</label>
                  <input
                    v-model="editingTaskData.endTime"
                    type="datetime-local"
                    class="form-input"
                  />
                </div>
              </div>
              
              <div class="time-actions">
                <button @click="setCurrentTime('start')" class="btn btn-secondary btn-sm">
                  🕐 设为当前时间
                </button>
                <button @click="setCurrentTime('end')" class="btn btn-secondary btn-sm">
                  🕐 设为当前时间
                </button>
                <button @click="clearTime('start')" class="btn btn-secondary btn-sm">
                  🗑️ 清除开始时间
                </button>
                <button @click="clearTime('end')" class="btn btn-secondary btn-sm">
                  🗑️ 清除结束时间
                </button>
              </div>
              
              <div v-if="editingTaskData.startTime && editingTaskData.endTime" class="duration-display">
                <span>⏱️ 预计时长: {{ calculateDuration(editingTaskData.startTime, editingTaskData.endTime) }}</span>
              </div>
            </div>

            <!-- 计时器信息 -->
            <div v-if="editingTaskData.timerDuration" class="edit-section">
              <h4>⏱️ 计时器信息</h4>
              <div class="timer-info">
                <span>累计计时: {{ formatDuration(editingTaskData.timerDuration) }}</span>
                <button @click="clearTimer" class="btn btn-secondary btn-sm">
                  🗑️ 清除计时
                </button>
              </div>
            </div>

            <!-- 状态设置 -->
            <div class="edit-section">
              <h4>📊 状态设置</h4>
              <div class="status-toggle">
                <label class="toggle-label">
                  <input
                    type="checkbox"
                    v-model="editingTaskData.completed"
                    class="toggle-input"
                  />
                  <span class="toggle-slider"></span>
                  <span class="toggle-text">
                    {{ editingTaskData.completed ? '已完成' : '进行中' }}
                  </span>
                </label>
              </div>
            </div>
          </div>
          
          <div class="modal-actions">
            <button @click="closeEditTaskModal" class="btn btn-secondary">取消</button>
            <button @click="saveEditTask" class="btn btn-primary">保存</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, nextTick, onMounted, onUnmounted } from 'vue'
import { useLocalStorage } from '@vueuse/core'

export default {
  name: 'App',
  setup() {
    // 密码验证相关
    const isAuthenticated = ref(false)
    const pinDigits = ref(['', '', '', '', '', ''])
    const pinError = ref('')
    const correctPin = '961031' // 默认密码

    // 加密存储功能
    const encryptPin = (pin) => {
      // 简单的加密算法，实际应用中应使用更安全的加密方法
      let encrypted = ''
      for (let i = 0; i < pin.length; i++) {
        const charCode = pin.charCodeAt(i)
        const shifted = ((charCode - 48 + 7) % 10) + 48 // 数字0-9的ASCII码是48-57
        encrypted += String.fromCharCode(shifted)
      }
      return btoa(encrypted) // Base64编码
    }

    const decryptPin = (encrypted) => {
      try {
        const decoded = atob(encrypted) // Base64解码
        let decrypted = ''
        for (let i = 0; i < decoded.length; i++) {
          const charCode = decoded.charCodeAt(i)
          const shifted = ((charCode - 48 - 7 + 10) % 10) + 48
          decrypted += String.fromCharCode(shifted)
        }
        return decrypted
      } catch (error) {
        return correctPin // 如果解密失败，返回默认密码
      }
    }

    const getStoredPin = () => {
      const storedPin = localStorage.getItem('todo-pin')
      if (storedPin) {
        return decryptPin(storedPin)
      }
      return correctPin
    }

    const setStoredPin = (pin) => {
      const encrypted = encryptPin(pin)
      localStorage.setItem('todo-pin', encrypted)
    }

    // 响应式数据
    const tasks = useLocalStorage('todo-tasks', [])
    const projects = useLocalStorage('todo-projects', [])
    const isInitialized = useLocalStorage('todo-initialized', false)
    
    // 服务器同步相关数据
    const serverUrl = ref('')  // 使用相对路径，自动适配当前域名和端口
    const isOnline = ref(false)
    const lastServerUpdate = ref(null)
    const syncStatus = ref('idle') // idle, syncing, success, error
    
    // 通知系统
    const notification = ref(null)
    const showNotification = (message, type = 'info') => {
      notification.value = { message, type, timestamp: Date.now() }
      setTimeout(() => {
        notification.value = null
      }, 3000)
    }
    const newTask = ref('')
    const newTaskProject = ref('')
    const newTaskType = ref('development')
    const newTaskPriority = ref('medium')
    const newTaskImportance = ref('medium') // 重要性：low, medium, high
    const newTaskUrgency = ref('medium') // 紧急性：low, medium, high
    const newTaskStartTime = ref('')
    const newTaskEndTime = ref('')
    const currentFilter = ref('all')
    const currentTypeFilter = ref('')
    const currentProject = ref('')
    const currentMenu = ref('tasks')
    const editingTask = ref(null)
    const showAddProject = ref(false)
    const newProjectName = ref('')
    const timerInterval = ref(null)
    const fileInput = ref(null)
    
    // 日历相关数据
    const calendarView = ref('day')
    const selectedDate = ref(new Date().toISOString().split('T')[0]) // 默认选择今天
    const selectedTask = ref(null)
    const currentTime = ref(new Date())
    
    // 全屏相关数据
    const isFullscreen = ref(true)

    // 任务编辑弹窗相关数据
    const showEditTaskModal = ref(false)
    const editingTaskData = ref({
      id: null,
      text: '',
      projectId: '',
      type: 'development',
      priority: 'medium',
      importance: 'medium',
      urgency: 'medium',
      startTime: '',
      endTime: '',
      completed: false,
      timerDuration: null
    })

    // 工作分析相关数据
    const currentTimeDimension = ref('day')
    const analysisSelectedDate = ref(new Date().toISOString().split('T')[0]) // 默认选择今天
    const timeDimensions = [
      { label: '今日', value: 'day' },
      { label: '本周', value: 'week' },
      { label: '本月', value: 'month' },
      { label: '本年', value: 'year' }
    ]

    // 过滤器选项
    const filters = [
      { label: '全部', value: 'all' },
      { label: '待完成', value: 'pending' },
      { label: '已完成', value: 'completed' }
    ]

    // 计算属性
    const totalTasks = computed(() => tasks.value.length)
    const completedTasks = computed(() => 
      tasks.value.filter(task => task.completed).length
    )
    const pendingTasks = computed(() => 
      tasks.value.filter(task => !task.completed).length
    )

    const todayTasks = computed(() => {
      const today = new Date()
      const todayStr = today.toLocaleDateString('en-CA') // 格式: YYYY-MM-DD
      return tasks.value.filter(task => {
        if (task.startTime) {
          const taskDate = new Date(task.startTime).toLocaleDateString('en-CA')
          return taskDate === todayStr
        }
        return false
      }).length
    })

    // 工作分布分析
    const projectDistribution = computed(() => {
      const today = new Date()
      const todayStr = today.toLocaleDateString('en-CA') // 格式: YYYY-MM-DD
      const todayTasks = tasks.value.filter(task => {
        if (task.startTime) {
          const taskDate = new Date(task.startTime).toLocaleDateString('en-CA')
          return taskDate === todayStr
        }
        return false
      })

      const distribution = {}
      todayTasks.forEach(task => {
        if (!distribution[task.projectId]) {
          distribution[task.projectId] = 0
        }
        distribution[task.projectId]++
      })

      return Object.entries(distribution).map(([projectId, count]) => ({
        projectId,
        count
      }))
    })

    const typeDistribution = computed(() => {
      const today = new Date()
      const todayStr = today.toLocaleDateString('en-CA') // 格式: YYYY-MM-DD
      const todayTasks = tasks.value.filter(task => {
        if (task.startTime) {
          const taskDate = new Date(task.startTime).toLocaleDateString('en-CA')
          return taskDate === todayStr
        }
        return false
      })

      const distribution = {}
      todayTasks.forEach(task => {
        if (!distribution[task.type]) {
          distribution[task.type] = 0
        }
        distribution[task.type]++
      })

      return Object.entries(distribution).map(([type, count]) => ({
        type,
        count
      }))
    })

    const totalWorkHours = computed(() => {
      const today = new Date()
      const todayStr = today.toLocaleDateString('en-CA') // 格式: YYYY-MM-DD
      const todayTasks = tasks.value.filter(task => {
        if (task.startTime) {
          const taskDate = new Date(task.startTime).toLocaleDateString('en-CA')
          return taskDate === todayStr
        }
        return false
      })

      let totalHours = 0
      todayTasks.forEach(task => {
        if (task.startTime && task.endTime) {
          const start = new Date(task.startTime)
          const end = new Date(task.endTime)
          const duration = (end - start) / (1000 * 60 * 60) // 转换为小时
          totalHours += duration
        }
      })

      // 加上计时器的时长
      const timerTasks = tasks.value.filter(task => {
        if (task.timerDuration) {
          const taskDate = new Date(task.createdAt).toISOString().split('T')[0]
          return taskDate === todayStr
        }
        return false
      })

      timerTasks.forEach(task => {
        if (task.timerDuration) {
          const duration = task.timerDuration / 3600 // 转换为小时
          totalHours += duration
        }
      })

      return totalHours.toFixed(1)
    })

    const averageTaskHours = computed(() => {
      const today = new Date()
      const todayStr = today.toLocaleDateString('en-CA') // 格式: YYYY-MM-DD
      const todayTasks = tasks.value.filter(task => {
        if (task.startTime) {
          const taskDate = new Date(task.startTime).toLocaleDateString('en-CA')
          return taskDate === todayStr
        }
        return false
      })

      const tasksWithDuration = todayTasks.filter(task => task.startTime && task.endTime)
      const timerTasks = tasks.value.filter(task => {
        if (task.timerDuration) {
          const taskDate = new Date(task.createdAt).toLocaleDateString('en-CA')
          return taskDate === todayStr
        }
        return false
      })

      const allTasksWithDuration = [...tasksWithDuration, ...timerTasks]
      if (allTasksWithDuration.length === 0) return '0.0'

      let totalHours = 0
      tasksWithDuration.forEach(task => {
        const start = new Date(task.startTime)
        const end = new Date(task.endTime)
        const duration = (end - start) / (1000 * 60 * 60)
        totalHours += duration
      })

      timerTasks.forEach(task => {
        if (task.timerDuration) {
          const duration = task.timerDuration / 3600 // 转换为小时
          totalHours += duration
        }
      })

      return (totalHours / allTasksWithDuration.length).toFixed(1)
    })

    // 数据管理功能
    const exportData = () => {
      const data = {
        tasks: tasks.value,
        projects: projects.value,
        exportDate: new Date().toISOString(),
        version: '1.0.0'
      }
      
      const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `worktime-data-${new Date().toISOString().split('T')[0]}.json`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
    }

    const importData = () => {
      fileInput.value.click()
    }

    const handleFileImport = (event) => {
      const file = event.target.files[0]
      if (!file) return

      const reader = new FileReader()
      reader.onload = (e) => {
        try {
          const data = JSON.parse(e.target.result)
          
          // 验证数据格式
          if (data.tasks && data.projects) {
                      // 确认导入
          if (confirm('导入数据将覆盖当前所有数据，确定要继续吗？')) {
            tasks.value = data.tasks
            projects.value = data.projects
            isInitialized.value = true
            alert('数据导入成功！')
          }
          } else {
            alert('文件格式不正确，请选择正确的数据文件。')
          }
        } catch (error) {
          alert('文件读取失败，请检查文件格式。')
        }
      }
      reader.readAsText(file)
      
      // 清空文件输入，允许重复选择同一文件
      event.target.value = ''
    }

    // 密码验证方法
    const onPinInput = (index, event) => {
      const value = event.target.value
      if (value && /^\d$/.test(value)) {
        pinDigits.value[index] = value
        pinError.value = ''
        
        // 自动跳转到下一个输入框
        if (index < 5) {
          nextTick(() => {
            const nextInput = document.querySelector(`input[ref="pinInput${index + 1}"]`)
            if (nextInput) {
              nextInput.focus()
            }
          })
        } else {
          // 检查密码
          checkPin()
        }
      } else {
        pinDigits.value[index] = ''
      }
    }

    const onPinKeydown = (index, event) => {
      if (event.key === 'Backspace' && !pinDigits.value[index] && index > 0) {
        // 如果当前框为空且按退格键，跳转到上一个输入框
        nextTick(() => {
          const prevInput = document.querySelector(`input[ref="pinInput${index - 1}"]`)
          if (prevInput) {
            prevInput.focus()
          }
        })
      }
    }

    const onPinPaste = (event) => {
      event.preventDefault()
      const pastedData = event.clipboardData.getData('text')
      const digits = pastedData.replace(/\D/g, '').slice(0, 6).split('')
      
      // 更新显示的数字
      pinDigits.value = [...digits, '', '', '', '', '', ''].slice(0, 6)
      pinError.value = ''
      
      // 如果粘贴了6位数字，自动验证
      if (digits.length === 6) {
        checkPin()
      }
    }

    const checkPin = () => {
      const enteredPin = pinDigits.value.join('')
      const storedPin = getStoredPin()
      
      if (enteredPin === storedPin) {
        isAuthenticated.value = true
        pinError.value = ''
        // 保存认证状态到本地存储
        localStorage.setItem('todo-authenticated', 'true')
      } else {
        pinError.value = '密码错误，请重试'
        pinDigits.value = ['', '', '', '', '', '']
        // 清空隐藏输入框
        const hiddenInput = document.querySelector('.hidden-input')
        if (hiddenInput) {
          hiddenInput.value = ''
          hiddenInput.focus()
        }
      }
    }

    // 检查是否已经认证过
    const checkAuthentication = () => {
      const authenticated = localStorage.getItem('todo-authenticated')
      if (authenticated === 'true') {
        isAuthenticated.value = true
      }
    }

    // 页面加载时检查认证状态
    onMounted(() => {
      checkAuthentication()
      // 如果未认证，自动聚焦到隐藏输入框
      if (!isAuthenticated.value) {
        nextTick(() => {
          const hiddenInput = document.querySelector('.hidden-input')
          if (hiddenInput) {
            hiddenInput.focus()
          }
        })
      }
    })

    const clearData = () => {
      if (confirm('确定要清空所有数据吗？此操作不可恢复！')) {
        // 清空响应式数据
        tasks.value = []
        projects.value = []
        isInitialized.value = false
        
        // 清除本地存储
        localStorage.removeItem('todo-tasks')
        localStorage.removeItem('todo-projects')
        localStorage.removeItem('todo-initialized')
        
        // 重置当前选择
        currentProject.value = ''
        currentMenu.value = 'tasks'
        
        alert('数据已完全清空！页面将重新加载以应用更改。')
        
        // 重新加载页面以确保完全清除
        setTimeout(() => {
          window.location.reload()
        }, 1000)
      }
    }

    const clearDefaultData = () => {
      if (confirm('确定要清除所有默认数据吗？这将删除所有项目和任务，但保留应用设置。')) {
        // 清空项目和任务数据
        tasks.value = []
        projects.value = []
        
        // 清除本地存储中的项目和任务
        localStorage.removeItem('todo-tasks')
        localStorage.removeItem('todo-projects')
        
        // 重置当前选择
        currentProject.value = ''
        currentMenu.value = 'tasks'
        
        alert('默认数据已清除！现在您可以创建自己的项目了。')
      }
    }

    // 服务器同步相关方法
    const checkServerConnection = async () => {
      try {
        const response = await fetch(`${serverUrl.value}/api/health`)
        if (response.ok) {
          isOnline.value = true
          return true
        }
      } catch (error) {
        console.log('服务器连接失败:', error)
      }
      isOnline.value = false
      return false
    }

    const syncToServer = async () => {
      if (!isOnline.value) {
        alert('服务器未连接，无法同步数据')
        return false
      }

      syncStatus.value = 'syncing'
      try {
        const response = await fetch(`${serverUrl.value}/api/data`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            tasks: tasks.value,
            projects: projects.value
          })
        })

        if (response.ok) {
          const result = await response.json()
          lastServerUpdate.value = result.lastUpdated
          syncStatus.value = 'success'
          setTimeout(() => {
            syncStatus.value = 'idle'
          }, 2000)
          return true
        } else {
          throw new Error('同步失败')
        }
      } catch (error) {
        console.error('同步到服务器失败:', error)
        syncStatus.value = 'error'
        setTimeout(() => {
          syncStatus.value = 'idle'
        }, 3000)
        return false
      }
    }

    const syncFromServer = async () => {
      if (!isOnline.value) {
        alert('服务器未连接，无法同步数据')
        return false
      }

      syncStatus.value = 'syncing'
      try {
        const response = await fetch(`${serverUrl.value}/api/data`)
        if (response.ok) {
          const serverData = await response.json()
          tasks.value = serverData.tasks || []
          projects.value = serverData.projects || []
          lastServerUpdate.value = serverData.lastUpdated
          syncStatus.value = 'success'
          setTimeout(() => {
            syncStatus.value = 'idle'
          }, 2000)
          return true
        } else {
          throw new Error('获取数据失败')
        }
      } catch (error) {
        console.error('从服务器同步失败:', error)
        syncStatus.value = 'error'
        setTimeout(() => {
          syncStatus.value = 'idle'
        }, 3000)
        return false
      }
    }

    const autoSync = async () => {
      // 检查服务器连接
      const connected = await checkServerConnection()
      if (!connected) return

      // 检查服务器数据是否有更新
      try {
        const response = await fetch(`${serverUrl.value}/api/last-updated`)
        if (response.ok) {
          const { lastUpdated } = await response.json()
          if (lastUpdated !== lastServerUpdate.value) {
            // 服务器数据有更新，从服务器同步
            await syncFromServer()
          } else {
            // 本地数据可能有更新，同步到服务器
            await syncToServer()
          }
        }
      } catch (error) {
        console.error('自动同步失败:', error)
      }
    }

    const filteredTasks = computed(() => {
      let filtered = tasks.value
      
      // 按项目过滤
      if (currentProject.value) {
        filtered = filtered.filter(task => task.projectId === currentProject.value)
      }
      
      // 按状态过滤
      switch (currentFilter.value) {
        case 'completed':
          filtered = filtered.filter(task => task.completed)
          break
        case 'pending':
          filtered = filtered.filter(task => !task.completed)
          break
      }
      
      // 按类型过滤
      if (currentTypeFilter.value) {
        filtered = filtered.filter(task => task.type === currentTypeFilter.value)
      }
      
      return filtered
    })

    // 方法
    const addTask = () => {
      if (newTask.value.trim() && newTaskProject.value) {
        const task = {
          id: Date.now(),
          text: newTask.value.trim(),
          projectId: newTaskProject.value,
          type: newTaskType.value,
          completed: false,
          priority: newTaskPriority.value,
          importance: newTaskImportance.value,
          urgency: newTaskUrgency.value,
          startTime: newTaskStartTime.value || null,
          endTime: newTaskEndTime.value || null,
          timerRunning: false,
          timerStartTime: null,
          timerDuration: null,
          createdAt: new Date(),
          editing: false
        }
        tasks.value.unshift(task)
        newTask.value = ''
        newTaskProject.value = ''
        newTaskType.value = 'development'
        newTaskPriority.value = 'medium'
        newTaskImportance.value = 'medium'
        newTaskUrgency.value = 'medium'
        newTaskStartTime.value = ''
        newTaskEndTime.value = ''
      }
    }

    const addProject = () => {
      if (newProjectName.value.trim()) {
        const project = {
          id: Date.now().toString(),
          name: newProjectName.value.trim(),
          createdAt: new Date()
        }
        projects.value.push(project)
        newProjectName.value = ''
        showAddProject.value = false
        // 如果是第一个项目，自动选中
        if (projects.value.length === 1) {
          currentProject.value = project.id
        }
      }
    }

    const getProjectName = (projectId) => {
      const project = projects.value.find(p => p.id === projectId)
      return project ? project.name : '未知项目'
    }

    const getProjectTaskCount = (projectId) => {
      return tasks.value.filter(task => task.projectId === projectId).length
    }

    const toggleTask = (taskId) => {
      const task = tasks.value.find(t => t.id === taskId)
      if (task) {
        task.completed = !task.completed
      }
    }

    const deleteTask = (taskId) => {
      const index = tasks.value.findIndex(t => t.id === taskId)
      if (index > -1) {
        tasks.value.splice(index, 1)
      }
    }

    const editTask = (task) => {
      task.editing = true
      editingTask.value = task
      nextTick(() => {
        const editInput = document.querySelector('.edit-input')
        if (editInput) {
          editInput.focus()
          editInput.select()
        }
      })
    }

    // 新的编辑任务方法
    const openEditTaskModal = (task) => {
      // 复制任务数据到编辑表单
      editingTaskData.value = {
        id: task.id,
        text: task.text,
        projectId: task.projectId,
        type: task.type,
        priority: task.priority,
        importance: task.importance,
        urgency: task.urgency,
        startTime: task.startTime ? formatDateTimeForInput(new Date(task.startTime)) : '', // 转换为datetime-local格式
        endTime: task.endTime ? formatDateTimeForInput(new Date(task.endTime)) : '', // 转换为datetime-local格式
        completed: task.completed,
        timerDuration: task.timerDuration
      }
      showEditTaskModal.value = true
    }

    // 格式化日期时间为datetime-local输入框格式（本地时间）
    const formatDateTimeForInput = (date) => {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      return `${year}-${month}-${day}T${hours}:${minutes}`
    }

    const closeEditTaskModal = () => {
      showEditTaskModal.value = false
      editingTaskData.value = {
        id: null,
        text: '',
        projectId: '',
        type: 'development',
        priority: 'medium',
        importance: 'medium',
        urgency: 'medium',
        startTime: '',
        endTime: '',
        completed: false,
        timerDuration: null
      }
    }

    const saveEditTask = () => {
      if (!editingTaskData.value.text.trim()) {
        showNotification('任务内容不能为空', 'error')
        return
      }

      if (!editingTaskData.value.projectId) {
        showNotification('请选择所属项目', 'error')
        return
      }

      // 找到要编辑的任务
      const taskIndex = tasks.value.findIndex(t => t.id === editingTaskData.value.id)
      if (taskIndex === -1) {
        showNotification('任务不存在', 'error')
        return
      }

      // 更新任务数据
      const task = tasks.value[taskIndex]
      task.text = editingTaskData.value.text.trim()
      task.projectId = editingTaskData.value.projectId
      task.type = editingTaskData.value.type
      task.priority = editingTaskData.value.priority
      task.importance = editingTaskData.value.importance
      task.urgency = editingTaskData.value.urgency
      task.completed = editingTaskData.value.completed
      
      // 处理时间数据
      if (editingTaskData.value.startTime) {
        task.startTime = new Date(editingTaskData.value.startTime).toISOString()
      } else {
        task.startTime = null
      }
      
      if (editingTaskData.value.endTime) {
        task.endTime = new Date(editingTaskData.value.endTime).toISOString()
      } else {
        task.endTime = null
      }

      // 处理计时器数据
      if (editingTaskData.value.timerDuration !== null) {
        task.timerDuration = editingTaskData.value.timerDuration
      }

      showNotification('任务编辑成功', 'success')
      closeEditTaskModal()
    }

    const setCurrentTime = (type) => {
      const now = new Date()
      const timeString = formatDateTimeForInput(now) // 使用本地时间格式
      
      if (type === 'start') {
        editingTaskData.value.startTime = timeString
      } else if (type === 'end') {
        editingTaskData.value.endTime = timeString
      }
    }

    const clearTime = (type) => {
      if (type === 'start') {
        editingTaskData.value.startTime = ''
      } else if (type === 'end') {
        editingTaskData.value.endTime = ''
      }
    }

    const clearTimer = () => {
      editingTaskData.value.timerDuration = null
    }



    const getPriorityText = (priority) => {
      const texts = {
        high: '高',
        medium: '中',
        low: '低'
      }
      return texts[priority] || '中'
    }

    const getTypeText = (type) => {
      const texts = {
        requirement: '需求分析',
        documentation: '文档编写',
        development: '开发代码',
        testing: '测试',
        operation: '运维',
        other: '其他'
      }
      return texts[type] || '其他'
    }

    const formatDate = (date) => {
      const now = new Date()
      const taskDate = new Date(date)
      const diffTime = Math.abs(now - taskDate)
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

      if (diffDays === 1) {
        return '今天'
      } else if (diffDays === 2) {
        return '昨天'
      } else if (diffDays <= 7) {
        return `${diffDays - 1}天前`
      } else {
        return taskDate.toLocaleDateString('zh-CN')
      }
    }

    const formatDateTime = (dateTime) => {
      const date = new Date(dateTime)
      return date.toLocaleString('zh-CN', {
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    const calculateDuration = (startTime, endTime) => {
      const start = new Date(startTime)
      const end = new Date(endTime)
      const duration = (end - start) / (1000 * 60 * 60) // 转换为小时
      
      if (duration < 1) {
        const minutes = Math.round(duration * 60)
        return `${minutes}分钟`
      } else if (duration < 24) {
        return `${duration.toFixed(1)}小时`
      } else {
        const days = Math.floor(duration / 24)
        const hours = duration % 24
        return `${days}天${hours.toFixed(1)}小时`
      }
    }

    const formatDuration = (duration) => {
      if (duration < 60) {
        return `${duration}秒`
      } else if (duration < 3600) {
        const minutes = Math.floor(duration / 60)
        const seconds = duration % 60
        return `${minutes}分${seconds}秒`
      } else {
        const hours = Math.floor(duration / 3600)
        const minutes = Math.floor((duration % 3600) / 60)
        return `${hours}小时${minutes}分`
      }
    }

    const formatTimer = (task) => {
      if (!task) return '0秒'
      
      const duration = getCurrentTimerDuration(task)
      return formatDuration(duration)
    }

    // 日历相关计算属性
    const calendarTitle = computed(() => {
      const date = new Date(selectedDate.value)
      switch (calendarView.value) {
        case 'day':
          return date.toLocaleDateString('zh-CN', { 
            year: 'numeric', 
            month: 'long', 
            day: 'numeric',
            weekday: 'long'
          })
        case 'week':
          const weekStart = new Date(date)
          weekStart.setDate(date.getDate() - date.getDay())
          const weekEnd = new Date(weekStart)
          weekEnd.setDate(weekStart.getDate() + 6)
          return `${weekStart.toLocaleDateString('zh-CN', { month: 'long', day: 'numeric' })} - ${weekEnd.toLocaleDateString('zh-CN', { month: 'long', day: 'numeric' })}`
        case 'month':
          return date.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long' })
        default:
          return date.toLocaleDateString('zh-CN')
      }
    })



    const weekDays = computed(() => {
      const date = new Date(selectedDate.value)
      const weekStart = new Date(date)
      weekStart.setDate(date.getDate() - date.getDay())
      
      const days = []
      for (let i = 0; i < 7; i++) {
        const day = new Date(weekStart)
        day.setDate(weekStart.getDate() + i)
        days.push({
          date: day,
          name: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][i]
        })
      }
      return days
    })

    const monthDays = computed(() => {
      const date = new Date(selectedDate.value)
      const year = date.getFullYear()
      const month = date.getMonth()
      
      // 获取当月第一天
      const firstDay = new Date(year, month, 1)
      // 获取当月最后一天
      const lastDay = new Date(year, month + 1, 0)
      
      // 计算日历开始日期（包含上个月的日期）
      const startDate = new Date(firstDay)
      const dayOfWeek = firstDay.getDay() // 0 = 周日, 1 = 周一, ..., 6 = 周六
      startDate.setDate(firstDay.getDate() - dayOfWeek)
      
      const days = []
      // 生成6周（42天）的日历网格
      for (let i = 0; i < 42; i++) {
        const day = new Date(startDate)
        day.setDate(startDate.getDate() + i)
        days.push({
          date: day,
          dayNumber: day.getDate(),
          isCurrentMonth: day.getMonth() === month
        })
      }
      return days
    })

    const dayTasks = computed(() => {
      const date = new Date(selectedDate.value)
      // 使用本地日期字符串比较，避免时区问题
      const dateStr = date.toLocaleDateString('en-CA') // 格式: YYYY-MM-DD
      return tasks.value.filter(task => {
        if (task.startTime) {
          const taskDate = new Date(task.startTime).toLocaleDateString('en-CA')
          return taskDate === dateStr
        }
        return false
      })
    })

    const completedDayTasks = computed(() => {
      return dayTasks.value.filter(task => task.completed)
    })

    const dayWorkHours = computed(() => {
      let totalHours = 0
      dayTasks.value.forEach(task => {
        if (task.startTime && task.endTime) {
          const start = new Date(task.startTime)
          const end = new Date(task.endTime)
          totalHours += (end - start) / (1000 * 60 * 60)
        } else if (task.timerDuration) {
          totalHours += task.timerDuration / 3600
        }
      })
      return totalHours.toFixed(1)
    })

    const toggleTimer = (task) => {
      if (task.timerRunning) {
        // 停止计时
        stopTimer(task)
      } else {
        // 开始计时
        startTimer(task)
      }
    }

    const startTimer = (task) => {
      task.timerRunning = true
      task.timerStartTime = new Date().toISOString()
      
      // 启动定时器更新显示
      if (!timerInterval.value) {
        timerInterval.value = setInterval(() => {
          // 强制更新视图
          tasks.value = [...tasks.value]
        }, 1000)
      }
    }

    const stopTimer = (task) => {
      task.timerRunning = false
      const now = new Date()
      const start = new Date(task.timerStartTime)
      const duration = Math.floor((now - start) / 1000)
      task.timerDuration = (task.timerDuration || 0) + duration
      
      // 记录是否需要补充时间
      const needsStartTime = !task.startTime
      const needsEndTime = !task.endTime
      
      // 自动补充开始时间和结束时间
      if (!task.startTime) {
        // 如果没有开始时间，使用计时器开始时间
        task.startTime = task.timerStartTime
      }
      
      if (!task.endTime) {
        // 如果没有结束时间，使用当前时间
        task.endTime = now.toISOString()
      }
      
      task.timerStartTime = null
      
      // 显示时间补充通知
      if (needsStartTime || needsEndTime) {
        showNotification(`已自动为任务"${task.text}"补充时间信息`, 'success')
      }
      
      // 检查是否还有其他正在运行的任务
      const runningTasks = tasks.value.filter(t => t.timerRunning)
      if (runningTasks.length === 0 && timerInterval.value) {
        clearInterval(timerInterval.value)
        timerInterval.value = null
      }
    }

    const restoreTimerState = () => {
      // 恢复所有正在运行的任务的计时器
      const runningTasks = tasks.value.filter(task => task.timerRunning && task.timerStartTime)
      
      if (runningTasks.length > 0) {
        // 启动定时器更新显示
        if (!timerInterval.value) {
          timerInterval.value = setInterval(() => {
            // 强制更新视图
            tasks.value = [...tasks.value]
          }, 1000)
        }
      }
    }

    const getCurrentTimerDuration = (task) => {
      if (!task.timerRunning || !task.timerStartTime) {
        return task.timerDuration || 0
      }
      
      const now = new Date()
      const start = new Date(task.timerStartTime)
      const currentDuration = Math.floor((now - start) / 1000)
      return (task.timerDuration || 0) + currentDuration
    }

    // 日历相关方法
    const previousPeriod = () => {
      const date = new Date(selectedDate.value)
      switch (calendarView.value) {
        case 'day':
          date.setDate(date.getDate() - 1)
          break
        case 'week':
          date.setDate(date.getDate() - 7)
          break
        case 'month':
          date.setMonth(date.getMonth() - 1)
          break
      }
      selectedDate.value = date.toISOString().split('T')[0]
    }

    const nextPeriod = () => {
      const date = new Date(selectedDate.value)
      switch (calendarView.value) {
        case 'day':
          date.setDate(date.getDate() + 1)
          break
        case 'week':
          date.setDate(date.getDate() + 7)
          break
        case 'month':
          date.setMonth(date.getMonth() + 1)
          break
      }
      selectedDate.value = date.toISOString().split('T')[0]
    }

    const getTasksForHour = (hour) => {
      return dayTasks.value.filter(task => {
        if (task.startTime) {
          const taskHour = new Date(task.startTime).getHours()
          return taskHour === hour
        }
        return false
      })
    }

    // 获取在指定小时开始的任务（日视图用）
    const getTasksStartingAtHour = (hour) => {
      const selectedDateStr = new Date(selectedDate.value).toLocaleDateString('en-CA')
      return tasks.value.filter(task => {
        if (task.startTime) {
          const taskDate = new Date(task.startTime).toLocaleDateString('en-CA')
          const taskHour = new Date(task.startTime).getHours()
          return taskDate === selectedDateStr && taskHour === hour
        }
        return false
      })
    }

    // 获取在指定小时有活动的任务（日视图用）
    const getTasksActiveAtHour = (hour) => {
      const selectedDateStr = new Date(selectedDate.value).toLocaleDateString('en-CA')
      return tasks.value.filter(task => {
        if (task.startTime && task.endTime) {
          const taskStartDate = new Date(task.startTime).toLocaleDateString('en-CA')
          const taskEndDate = new Date(task.endTime).toLocaleDateString('en-CA')
          const startHour = new Date(task.startTime).getHours()
          const endHour = new Date(task.endTime).getHours()
          
          // 检查任务是否在指定日期有活动
          const isTaskActiveOnDate = taskStartDate === selectedDateStr || taskEndDate === selectedDateStr
          
          // 检查任务是否在指定小时有活动
          let isTaskActiveInHour = false
          if (taskStartDate === selectedDateStr && taskEndDate === selectedDateStr) {
            // 任务在同一天内
            isTaskActiveInHour = hour >= startHour && hour <= endHour
          } else if (taskStartDate === selectedDateStr) {
            // 任务开始于这一天
            isTaskActiveInHour = hour >= startHour
          } else if (taskEndDate === selectedDateStr) {
            // 任务结束于这一天
            isTaskActiveInHour = hour <= endHour
          } else {
            // 任务跨越这一天
            isTaskActiveInHour = true
          }
          
          return isTaskActiveOnDate && isTaskActiveInHour
        }
        return false
      })
    }

    // 计算任务的显示样式
    const getTaskTimelineStyle = (task) => {
      if (!task.startTime || !task.endTime) {
        return {}
      }

      const startTime = new Date(task.startTime)
      const endTime = new Date(task.endTime)
      
      // 计算任务在时间线中的位置和宽度
      const startHour = startTime.getHours()
      const startMinute = startTime.getMinutes()
      const endHour = endTime.getHours()
      const endMinute = endTime.getMinutes()
      
      // 计算开始位置（从小时槽左边缘开始）
      const startPosition = 0 // 从0开始，左对齐
      
      // 计算宽度（基于任务持续时间，但限制最大宽度）
      const durationHours = (endTime - startTime) / (1000 * 60 * 60)
      const width = Math.max(durationHours * 100, 20) // 最小宽度20%
      
      // 计算高度（基于任务的总持续时间）
      const totalDurationMinutes = (endTime - startTime) / (1000 * 60)
      const height = Math.max(totalDurationMinutes * (99/60), 40) // 每分钟1.65px，最小40px
      
      // 计算垂直位置（确保对齐）
      const taskIndex = getTaskIndexInHour(task, startHour)
      const topOffset = taskIndex * 70 // 增加任务间距，确保对齐
      
      // 判断是否为长时间任务
      const isLongTask = durationHours > 4
      
      return {
        position: 'absolute',
        left: `${startPosition}%`,
        top: `${topOffset}px`,
        width: `${width}%`,
        height: `${height}px`,
        zIndex: 10,
        minWidth: '120px',
        maxWidth: 'calc(100% - 10px)', // 恢复最大宽度限制
        borderRight: isLongTask ? '2px dashed #3182ce' : 'none'
      }
    }

    // 获取任务在指定小时中的索引（用于垂直排列）
    const getTaskIndexInHour = (task, hour) => {
      const tasksInHour = getTasksStartingAtHour(hour)
      return tasksInHour.findIndex(t => t.id === task.id)
    }

    const getTasksForDayAndHour = (date, hour) => {
      // 使用本地日期字符串比较，避免时区问题
      const dateStr = date.toLocaleDateString('en-CA') // 格式: YYYY-MM-DD
      return tasks.value.filter(task => {
        if (task.startTime) {
          const taskDate = new Date(task.startTime).toLocaleDateString('en-CA')
          const taskHour = new Date(task.startTime).getHours()
          return taskDate === dateStr && taskHour === hour
        }
        return false
      })
    }

    const getTasksForDay = (date) => {
      // 使用本地日期字符串比较，避免时区问题
      const dateStr = date.toLocaleDateString('en-CA') // 格式: YYYY-MM-DD
      return tasks.value.filter(task => {
        if (task.startTime) {
          const taskDate = new Date(task.startTime).toLocaleDateString('en-CA')
          return taskDate === dateStr
        }
        return false
      })
    }

    const getDayTaskCount = (date) => {
      return getTasksForDay(date).length
    }

    const isToday = (date) => {
      const today = new Date()
      return date.toDateString() === today.toDateString()
    }

    const formatDayDate = (date) => {
      return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' })
    }

    const formatTime = (dateTime) => {
      const date = new Date(dateTime)
      return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
    }

    // 获取当前时间线位置
    const currentTimeLine = computed(() => {
      const now = currentTime.value
      const hour = now.getHours()
      const minute = now.getMinutes()
      return hour + minute / 60
    })

    // 判断是否为当前时间线
    const isCurrentTimeLine = (hour) => {
      const currentHour = currentTime.value.getHours()
      return hour === currentHour
    }

    // 四象限计算属性
    const quadrantTasks = computed(() => {
      const quadrants = {
        q1: [], // 重要且紧急
        q2: [], // 重要不紧急
        q3: [], // 不重要但紧急
        q4: []  // 不重要不紧急
      }

      tasks.value.forEach(task => {
        const importance = task.importance || 'medium'
        const urgency = task.urgency || 'medium'
        
        if (importance === 'high' && urgency === 'high') {
          quadrants.q1.push(task)
        } else if (importance === 'high' && urgency === 'low') {
          quadrants.q2.push(task)
        } else if (importance === 'low' && urgency === 'high') {
          quadrants.q3.push(task)
        } else {
          quadrants.q4.push(task)
        }
      })

      return quadrants
    })

    // 获取象限标题
    const getQuadrantTitle = (quadrant) => {
      const titles = {
        q1: '重要且紧急',
        q2: '重要不紧急',
        q3: '不重要但紧急',
        q4: '不重要不紧急'
      }
      return titles[quadrant] || ''
    }

    // 获取象限描述
    const getQuadrantDescription = (quadrant) => {
      const descriptions = {
        q1: '立即处理',
        q2: '计划安排',
        q3: '委托他人',
        q4: '删除或延迟'
      }
      return descriptions[quadrant] || ''
    }

    // 获取象限颜色
    const getQuadrantColor = (quadrant) => {
      const colors = {
        q1: '#ff4757', // 红色
        q2: '#2ed573', // 绿色
        q3: '#ffa502', // 橙色
        q4: '#747d8c'  // 灰色
      }
      return colors[quadrant] || '#747d8c'
    }

    // 工作分析图表数据计算
    const getOverviewData = () => {
      const filteredTasks = getFilteredTasksByDimension()
      const totalTasks = filteredTasks.length
      const completedTasks = filteredTasks.filter(task => task.completed).length
      const totalHours = calculateTotalHours(filteredTasks)
      const completionRate = totalTasks > 0 ? Math.round((completedTasks / totalTasks) * 100) : 0
      
      return {
        totalTasks,
        completedTasks,
        totalHours: totalHours.toFixed(1),
        completionRate
      }
    }

    const getFilteredTasksByDimension = () => {
      const selectedDateObj = new Date(analysisSelectedDate.value)
      const dimension = currentTimeDimension.value
      
      return tasks.value.filter(task => {
        if (!task.startTime) return false
        
        const taskDate = new Date(task.startTime)
        const taskDateStr = taskDate.toLocaleDateString('en-CA')
        const selectedDateStr = selectedDateObj.toLocaleDateString('en-CA')
        
        switch (dimension) {
          case 'day':
            // 根据选择的日期过滤
            return taskDateStr === selectedDateStr
          case 'week':
            // 获取选择日期所在周的开始和结束
            const weekStart = new Date(selectedDateObj)
            weekStart.setDate(selectedDateObj.getDate() - selectedDateObj.getDay())
            const weekEnd = new Date(weekStart)
            weekEnd.setDate(weekStart.getDate() + 6)
            
            return taskDate >= weekStart && taskDate <= weekEnd
          case 'month':
            // 获取选择日期所在月的开始和结束
            const monthStart = new Date(selectedDateObj.getFullYear(), selectedDateObj.getMonth(), 1)
            const monthEnd = new Date(selectedDateObj.getFullYear(), selectedDateObj.getMonth() + 1, 0)
            
            return taskDate >= monthStart && taskDate <= monthEnd
          case 'year':
            // 获取选择日期所在年的开始和结束
            const yearStart = new Date(selectedDateObj.getFullYear(), 0, 1)
            const yearEnd = new Date(selectedDateObj.getFullYear(), 11, 31)
            
            return taskDate >= yearStart && taskDate <= yearEnd
          default:
            return false
        }
      })
    }

    const calculateTotalHours = (taskList) => {
      let totalHours = 0
      taskList.forEach(task => {
        if (task.startTime && task.endTime) {
          const start = new Date(task.startTime)
          const end = new Date(task.endTime)
          totalHours += (end - start) / (1000 * 60 * 60)
        } else if (task.timerDuration) {
          totalHours += task.timerDuration / 3600
        }
      })
      return totalHours
    }

    const getProjectChartData = () => {
      const filteredTasks = getFilteredTasksByDimension()
      const projectCounts = {}
      
      filteredTasks.forEach(task => {
        const projectName = getProjectName(task.projectId)
        projectCounts[projectName] = (projectCounts[projectName] || 0) + 1
      })
      
      const total = Object.values(projectCounts).reduce((sum, count) => sum + count, 0)
      const colors = ['#667eea', '#f093fb', '#f5576c', '#4facfe', '#00f2fe', '#43e97b']
      
      let currentAngle = 0
      return Object.entries(projectCounts).map(([name, count], index) => {
        const percentage = total > 0 ? Math.round((count / total) * 100) : 0
        const angle = (count / total) * 360
        const dashArray = `${(angle / 360) * 502.4} ${502.4}`
        const dashOffset = -currentAngle * 502.4 / 360
        currentAngle += angle
        
        return {
          name,
          count,
          percentage,
          color: colors[index % colors.length],
          dashArray,
          dashOffset
        }
      })
    }

    const getTypeChartData = () => {
      const filteredTasks = getFilteredTasksByDimension()
      const typeCounts = {}
      
      filteredTasks.forEach(task => {
        const typeName = getTypeText(task.type)
        typeCounts[typeName] = (typeCounts[typeName] || 0) + 1
      })
      
      const total = Object.values(typeCounts).reduce((sum, count) => sum + count, 0)
      const colors = ['#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#ffeaa7', '#dda0dd']
      
      let currentAngle = 0
      return Object.entries(typeCounts).map(([name, count], index) => {
        const percentage = total > 0 ? Math.round((count / total) * 100) : 0
        const angle = (count / total) * 360
        const dashArray = `${(angle / 360) * 502.4} ${502.4}`
        const dashOffset = -currentAngle * 502.4 / 360
        currentAngle += angle
        
        return {
          name,
          count,
          percentage,
          color: colors[index % colors.length],
          dashArray,
          dashOffset
        }
      })
    }

    const getTrendData = () => {
      const dimension = currentTimeDimension.value
      const points = []
      const maxCount = getMaxTaskCount()
      
      switch (dimension) {
        case 'day':
          // 24小时趋势
          for (let hour = 0; hour < 24; hour++) {
            const taskCount = getHourTaskCount(hour)
            const taskMinutes = getHourTaskMinutes(hour) // 获取分钟数
            const y = 30 + (1 - taskMinutes / 60) * 150 // 按分钟比例计算高度
            points.push({ x: 60 + (hour / 23) * 700, y: Math.max(y, 30) })
          }
          break
        case 'week':
          // 7天趋势
          for (let day = 0; day < 7; day++) {
            const taskCount = getDayTaskCountByOffset(day)
            const y = 30 + (1 - taskCount / maxCount) * 150
            points.push({ x: 60 + (day / 6) * 700, y: Math.max(y, 30) })
          }
          break
        case 'month':
          // 30天趋势
          for (let day = 0; day < 30; day++) {
            const taskCount = getDayTaskCountByOffset(day)
            const y = 30 + (1 - taskCount / maxCount) * 150
            points.push({ x: 60 + (day / 29) * 700, y: Math.max(y, 30) })
          }
          break
        case 'year':
          // 12个月趋势
          for (let month = 0; month < 12; month++) {
            const taskCount = getMonthTaskCount(month)
            const y = 30 + (1 - taskCount / maxCount) * 150
            points.push({ x: 60 + (month / 11) * 700, y: Math.max(y, 30) })
          }
          break
      }
      
      return points
    }

    const getTrendPath = () => {
      const points = getTrendData()
      if (points.length === 0) return ''
      
      // 创建平滑的曲线路径
      let path = `M ${points[0].x} ${points[0].y}`
      
      for (let i = 1; i < points.length; i++) {
        const prevPoint = points[i - 1]
        const currentPoint = points[i]
        
        // 计算控制点
        const controlPoint1X = prevPoint.x + (currentPoint.x - prevPoint.x) * 0.5
        const controlPoint1Y = prevPoint.y
        const controlPoint2X = currentPoint.x - (currentPoint.x - prevPoint.x) * 0.5
        const controlPoint2Y = currentPoint.y
        
        // 使用三次贝塞尔曲线创建平滑曲线
        path += ` C ${controlPoint1X} ${controlPoint1Y}, ${controlPoint2X} ${controlPoint2Y}, ${currentPoint.x} ${currentPoint.y}`
      }
      
      // 添加填充区域的路径
      path += ` L ${points[points.length-1].x} 180 L ${points[0].x} 180 Z`
      
      return path
    }

    const getTrendCurvePath = () => {
      const points = getTrendData()
      if (points.length === 0) return ''
      
      // 创建平滑的曲线路径（不包含填充区域）
      let path = `M ${points[0].x} ${points[0].y}`
      
      for (let i = 1; i < points.length; i++) {
        const prevPoint = points[i - 1]
        const currentPoint = points[i]
        
        // 计算控制点
        const controlPoint1X = prevPoint.x + (currentPoint.x - prevPoint.x) * 0.5
        const controlPoint1Y = prevPoint.y
        const controlPoint2X = currentPoint.x - (currentPoint.x - prevPoint.x) * 0.5
        const controlPoint2Y = currentPoint.y
        
        // 使用三次贝塞尔曲线创建平滑曲线
        path += ` C ${controlPoint1X} ${controlPoint1Y}, ${controlPoint2X} ${controlPoint2Y}, ${currentPoint.x} ${currentPoint.y}`
      }
      
      return path
    }

    const getMaxTaskCount = () => {
      const dimension = currentTimeDimension.value
      let maxCount = 0
      
      switch (dimension) {
        case 'day':
          for (let hour = 0; hour < 24; hour++) {
            maxCount = Math.max(maxCount, getHourTaskCount(hour))
          }
          break
        case 'week':
          for (let day = 0; day < 7; day++) {
            maxCount = Math.max(maxCount, getDayTaskCountByOffset(day))
          }
          break
        case 'month':
          for (let day = 0; day < 30; day++) {
            maxCount = Math.max(maxCount, getDayTaskCountByOffset(day))
          }
          break
        case 'year':
          for (let month = 0; month < 12; month++) {
            maxCount = Math.max(maxCount, getMonthTaskCount(month))
          }
          break
      }
      
      return Math.min(Math.max(maxCount, 1), 1) // 限制最大值为1
    }

    const getMaxBarTaskCount = () => {
      const dimension = currentTimeDimension.value
      let maxCount = 0
      
      switch (dimension) {
        case 'day':
          for (let hour = 0; hour < 24; hour++) {
            maxCount = Math.max(maxCount, getHourTaskCount(hour))
          }
          break
        case 'week':
          for (let day = 0; day < 7; day++) {
            maxCount = Math.max(maxCount, getDayTaskCountByOffset(day))
          }
          break
        case 'month':
          for (let day = 0; day < 30; day++) {
            maxCount = Math.max(maxCount, getDayTaskCountByOffset(day))
          }
          break
        case 'year':
          for (let month = 0; month < 12; month++) {
            maxCount = Math.max(maxCount, getMonthTaskCount(month))
          }
          break
      }
      
      return Math.min(Math.max(maxCount, 1), 1) // 限制最大值为1
    }



    const getXAxisLabels = () => {
      const dimension = currentTimeDimension.value
      
      switch (dimension) {
        case 'day':
          return ['00:00', '06:00', '12:00', '18:00', '23:59']
        case 'week':
          const weekLabels = []
          const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
          for (let i = 0; i < 7; i++) {
            const date = new Date(selectedDate.value)
            date.setDate(date.getDate() - date.getDay() + i)
            weekLabels.push(weekDays[date.getDay()])
          }
          return weekLabels
        case 'month':
          return ['1日', '5日', '10日', '15日', '20日', '25日', '30日']
        case 'year':
          const monthNames = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
          return monthNames
        default:
          return []
      }
    }



    const getHourTaskCount = (hour) => {
      const filteredTasks = getFilteredTasksByDimension()
      return filteredTasks.filter(task => {
        if (task.startTime && task.endTime) {
          const startTime = new Date(task.startTime)
          const endTime = new Date(task.endTime)
          const startHour = startTime.getHours()
          const endHour = endTime.getHours()
          
          // 只统计在这个小时开始的任务
          if (startHour === hour) {
            return true
          }
          
          // 如果任务横跨多个小时，且不是在这个小时开始，则显示在下一个小时
          if (startHour < hour && endHour >= hour) {
            // 检查是否应该显示在这个小时
            const hoursDiff = hour - startHour
            // 如果横跨时间超过1小时，显示在下一个小时
            if (hoursDiff > 0) {
              return true
            }
          }
          
          return false
        } else if (task.startTime) {
          // 只有开始时间，检查是否在这个小时开始
          return new Date(task.startTime).getHours() === hour
        }
        return false
      }).length
    }

    const getHourTaskMinutes = (hour) => {
      const filteredTasks = getFilteredTasksByDimension()
      let totalMinutes = 0
      
      filteredTasks.forEach(task => {
        if (task.startTime && task.endTime) {
          const startTime = new Date(task.startTime)
          const endTime = new Date(task.endTime)
          const startHour = startTime.getHours()
          const endHour = endTime.getHours()
          
          // 计算任务在这个小时内的分钟数
          if (startHour === hour) {
            // 任务在这个小时开始
            const startMinutes = startTime.getMinutes()
            if (endHour === hour) {
              // 任务在同一小时内结束
              const endMinutes = endTime.getMinutes()
              totalMinutes += Math.max(0, endMinutes - startMinutes)
            } else {
              // 任务跨小时结束
              totalMinutes += 60 - startMinutes
            }
          } else if (startHour < hour && endHour >= hour) {
            // 任务横跨这个小时
            if (endHour === hour) {
              // 任务在这个小时结束
              const endMinutes = endTime.getMinutes()
              totalMinutes += endMinutes
            } else {
              // 任务完全覆盖这个小时
              totalMinutes += 60
            }
          }
        } else if (task.startTime) {
          // 只有开始时间，检查是否在这个小时开始
          const taskHour = new Date(task.startTime).getHours()
          if (taskHour === hour) {
            totalMinutes += 30 // 默认30分钟
          }
        }
      })
      
      return Math.min(totalMinutes, 60) // 限制最大值为60分钟
    }

    const getHourColor = (hour) => {
      const count = getHourTaskCount(hour)
      if (count === 0) return '#f7fafc'
      if (count <= 2) return '#4facfe'
      if (count <= 4) return '#667eea'
      return '#f093fb'
    }

    const getDayTaskCountByOffset = (offset) => {
      const selectedDateObj = new Date(analysisSelectedDate.value)
      const targetDate = new Date(selectedDateObj)
      targetDate.setDate(selectedDateObj.getDate() - offset)
      const targetDateStr = targetDate.toLocaleDateString('en-CA')
      
      return tasks.value.filter(task => {
        if (task.startTime && task.endTime) {
          const startTime = new Date(task.startTime)
          const endTime = new Date(task.endTime)
          const startDateStr = startTime.toLocaleDateString('en-CA')
          const endDateStr = endTime.toLocaleDateString('en-CA')
          
          // 只统计在目标日期开始的任务
          if (startDateStr === targetDateStr) {
            return true
          }
          
          // 如果任务横跨多个日期，且不是在目标日期开始，则显示在下一个日期
          if (startDateStr < targetDateStr && endDateStr >= targetDateStr) {
            // 检查是否应该显示在这个日期
            const startDate = new Date(startDateStr)
            const targetDateCheck = new Date(targetDateStr)
            const daysDiff = Math.floor((targetDateCheck - startDate) / (1000 * 60 * 60 * 24))
            // 如果横跨时间超过1天，显示在下一个日期
            if (daysDiff > 0) {
              return true
            }
          }
          
          return false
        } else if (task.startTime) {
          // 只有开始时间，检查是否在目标日期
          const taskDate = new Date(task.startTime).toLocaleDateString('en-CA')
          return taskDate === targetDateStr
        }
        return false
      }).length
    }

    const getMonthTaskCount = (monthOffset) => {
      const selectedDateObj = new Date(analysisSelectedDate.value)
      const targetMonth = new Date(selectedDateObj.getFullYear(), selectedDateObj.getMonth() - monthOffset, 1)
      const targetMonthStr = `${targetMonth.getFullYear()}-${(targetMonth.getMonth() + 1).toString().padStart(2, '0')}`
      
      return tasks.value.filter(task => {
        if (task.startTime && task.endTime) {
          const startTime = new Date(task.startTime)
          const endTime = new Date(task.endTime)
          const startMonthStr = `${startTime.getFullYear()}-${(startTime.getMonth() + 1).toString().padStart(2, '0')}`
          const endMonthStr = `${endTime.getFullYear()}-${(endTime.getMonth() + 1).toString().padStart(2, '0')}`
          
          // 只统计在目标月份开始的任务
          if (startMonthStr === targetMonthStr) {
            return true
          }
          
          // 如果任务横跨多个月份，且不是在目标月份开始，则显示在下一个月份
          if (startMonthStr < targetMonthStr && endMonthStr >= targetMonthStr) {
            // 检查是否应该显示在这个月份
            const startMonth = new Date(startTime.getFullYear(), startTime.getMonth(), 1)
            const targetMonthCheck = new Date(targetMonth)
            const monthsDiff = (targetMonthCheck.getFullYear() - startMonth.getFullYear()) * 12 + 
                             (targetMonthCheck.getMonth() - startMonth.getMonth())
            // 如果横跨时间超过1个月，显示在下一个月份
            if (monthsDiff > 0) {
              return true
            }
          }
          
          return false
        } else if (task.startTime) {
          // 只有开始时间，检查是否在目标月份
          const taskDate = new Date(task.startTime)
          const taskMonthStr = `${taskDate.getFullYear()}-${(taskDate.getMonth() + 1).toString().padStart(2, '0')}`
          return taskMonthStr === targetMonthStr
        }
        return false
      }).length
    }



    // 协调点计算函数
    const getEfficiencyScore = () => {
      const overviewData = getOverviewData()
      const completionRate = overviewData.completionRate
      const totalHours = parseFloat(overviewData.totalHours)
      
      // 计算时间利用率（假设8小时工作制）
      const timeUtilization = Math.min((totalHours / 8) * 100, 100)
      
      // 综合评分：完成率占60%，时间利用率占40%
      const efficiencyScore = (completionRate * 0.6) + (timeUtilization * 0.4)
      
      return Math.round(efficiencyScore)
    }



    const getProjectBalanceScore = () => {
      const projectData = getProjectChartData()
      if (projectData.length === 0) return 0
      
      // 计算项目分布的均衡度
      const percentages = projectData.map(item => item.percentage)
      const maxPercentage = Math.max(...percentages)
      const minPercentage = Math.min(...percentages)
      
      // 如果项目数量太少，给予基础分数
      if (projectData.length < 2) {
        return 60
      }
      
      // 计算均衡度：最大值和最小值的差距越小，分数越高
      const balanceScore = Math.max(0, 100 - (maxPercentage - minPercentage))
      
      return Math.round(balanceScore)
    }

    const getQualityScore = () => {
      const overviewData = getOverviewData()
      const completionRate = overviewData.completionRate
      const totalTasks = overviewData.totalTasks
      const completedTasks = overviewData.completedTasks
      
      if (totalTasks === 0) return 0
      
      // 计算任务质量指标
      const taskQuality = completionRate // 完成率作为质量指标
      
      // 计算时间管理质量（基于任务完成情况）
      const timeManagementQuality = Math.min((completedTasks / totalTasks) * 100, 100)
      
      // 综合评分：任务质量占70%，时间管理占30%
      const qualityScore = (taskQuality * 0.7) + (timeManagementQuality * 0.3)
      
      return Math.round(qualityScore)
    }

    // CSS类函数
    const getEfficiencyClass = () => {
      const score = getEfficiencyScore()
      if (score >= 80) return 'efficiency-high'
      if (score >= 60) return 'efficiency-medium'
      return 'efficiency-low'
    }



    const getProjectBalanceClass = () => {
      const score = getProjectBalanceScore()
      if (score >= 80) return 'efficiency-high'
      if (score >= 60) return 'efficiency-medium'
      return 'efficiency-low'
    }

    const getQualityClass = () => {
      const score = getQualityScore()
      if (score >= 80) return 'efficiency-high'
      if (score >= 60) return 'efficiency-medium'
      return 'efficiency-low'
    }

    // 综合评分和状态
    const getOverallScore = () => {
      const efficiency = getEfficiencyScore()
      const projectBalance = getProjectBalanceScore()
      const quality = getQualityScore()
      
      // 加权平均：效率40%，项目平衡25%，质量35%
      const overallScore = (efficiency * 0.4) + (projectBalance * 0.25) + (quality * 0.35)
      
      return Math.round(overallScore)
    }

    const getOverallStatus = () => {
      const score = getOverallScore()
      if (score >= 85) return '优秀'
      if (score >= 70) return '良好'
      if (score >= 55) return '一般'
      return '需改进'
    }

    const getOverallStatusClass = () => {
      const score = getOverallScore()
      if (score >= 85) return 'status-excellent'
      if (score >= 70) return 'status-good'
      if (score >= 55) return 'status-average'
      return 'status-needs-improvement'
    }

    const selectDate = (date) => {
      selectedDate.value = date.toISOString().split('T')[0]
      calendarView.value = 'day'
    }

    // 滚动到当前时间线
    const scrollToCurrentTime = () => {
      nextTick(() => {
        const currentHour = currentTime.value.getHours()
        const timeSlot = document.querySelector(`[data-hour="${currentHour}"]`)
        if (timeSlot) {
          timeSlot.scrollIntoView({ 
            behavior: 'smooth', 
            block: 'center' 
          })
        }
      })
    }

    const selectTask = (task) => {
      selectedTask.value = task
    }

    const editTaskFromCalendar = (task) => {
      selectedTask.value = null
      openEditTaskModal(task)
    }

    // 全屏相关方法
    const toggleFullscreen = () => {
      isFullscreen.value = !isFullscreen.value
    }

    // 生命周期
    onMounted(async () => {
      // 设置初始化标志，不再加载示例数据
      if (!isInitialized.value) {
        isInitialized.value = true
      }
      
      // 恢复计时器状态
      restoreTimerState()
      
      // 检查服务器连接
      await checkServerConnection()
      
      // 如果服务器在线，尝试自动同步
      if (isOnline.value) {
        await autoSync()
      }
      
      // 设置定期同步（每5分钟）
      setInterval(async () => {
        if (isOnline.value) {
          await autoSync()
        }
      }, 5 * 60 * 1000)

      // 设置当前时间更新定时器（每分钟更新一次）
      setInterval(() => {
        currentTime.value = new Date()
      }, 60 * 1000)

      // 初始化时滚动到当前时间线
      if (calendarView.value === 'day') {
        setTimeout(scrollToCurrentTime, 500)
      }
    })

    // 页面卸载时清理计时器
    onUnmounted(() => {
      if (timerInterval.value) {
        clearInterval(timerInterval.value)
        timerInterval.value = null
      }
    })

    // 获取在指定日期和小时有活动的任务（周视图用）
    const getTasksActiveForDayAndHour = (date, hour) => {
      const dateStr = date.toLocaleDateString('en-CA') // 格式: YYYY-MM-DD
      return tasks.value.filter(task => {
        if (task.startTime && task.endTime) {
          const taskStartDate = new Date(task.startTime).toLocaleDateString('en-CA')
          const taskEndDate = new Date(task.endTime).toLocaleDateString('en-CA')
          const startHour = new Date(task.startTime).getHours()
          const endHour = new Date(task.endTime).getHours()
          
          // 检查任务是否在指定日期有活动
          const isTaskActiveOnDate = taskStartDate === dateStr || taskEndDate === dateStr
          
          // 检查任务是否在指定小时有活动
          let isTaskActiveInHour = false
          if (taskStartDate === dateStr && taskEndDate === dateStr) {
            // 任务在同一天内
            isTaskActiveInHour = hour >= startHour && hour <= endHour
          } else if (taskStartDate === dateStr) {
            // 任务开始于这一天
            isTaskActiveInHour = hour >= startHour
          } else if (taskEndDate === dateStr) {
            // 任务结束于这一天
            isTaskActiveInHour = hour <= endHour
          } else {
            // 任务跨越这一天
            isTaskActiveInHour = true
          }
          
          return isTaskActiveOnDate && isTaskActiveInHour
        }
        return false
      })
    }

    // 计算周视图任务的显示样式
    const getWeekTaskTimelineStyle = (task, date, hour) => {
      if (!task.startTime || !task.endTime) {
        return {}
      }

      const startTime = new Date(task.startTime)
      const endTime = new Date(task.endTime)
      
      // 检查任务是否在这个小时开始
      const taskStartHour = startTime.getHours()
      const isTaskStartingThisHour = taskStartHour === hour
      
      // 只显示在任务开始的小时槽内
      if (!isTaskStartingThisHour) {
        return { display: 'none' }
      }
      
      // 计算任务在时间线中的位置和宽度
      const startMinute = startTime.getMinutes()
      const endMinute = endTime.getMinutes()
      const startHour = startTime.getHours()
      const endHour = endTime.getHours()
      
      // 计算开始位置（从小时槽左边缘开始）
      const startPosition = 0 // 从0开始，左对齐
      
      // 计算宽度（基于任务持续时间，但限制最大宽度）
      const durationHours = (endTime - startTime) / (1000 * 60 * 60)
      const width = Math.max(durationHours * 100, 20) // 最小宽度20%
      
      // 计算高度（基于任务的总持续时间）
      const totalDurationMinutes = (endTime - startTime) / (1000 * 60)
      const height = Math.max(totalDurationMinutes * 1.0, 30) // 每分钟1.0px，最小30px
      
      // 计算垂直位置（确保对齐）
      const tasksInCell = getTasksStartingForDayAndHour(date, hour)
      const taskIndex = tasksInCell.findIndex(t => t.id === task.id)
      const topOffset = taskIndex * 60 // 每个任务间隔60px
      
      // 判断是否为长时间任务
      const isLongTask = durationHours > 4
      
      return {
        position: 'absolute',
        left: `${startPosition}%`,
        top: `${topOffset}px`,
        width: `${width}%`,
        height: `${height}px`,
        zIndex: 10,
        minWidth: '80px',
        maxWidth: 'calc(100% - 5px)', // 恢复最大宽度限制
        borderRight: isLongTask ? '2px dashed #3182ce' : 'none'
      }
    }

    // 获取在指定日期和小时开始的任务（周视图用）
    const getTasksStartingForDayAndHour = (date, hour) => {
      const dateStr = date.toLocaleDateString('en-CA') // 格式: YYYY-MM-DD
      return tasks.value.filter(task => {
        if (task.startTime) {
          const taskDate = new Date(task.startTime).toLocaleDateString('en-CA')
          const taskHour = new Date(task.startTime).getHours()
          return taskDate === dateStr && taskHour === hour
        }
        return false
      })
    }

    const isLongTask = (task) => {
      const durationHours = (new Date(task.endTime) - new Date(task.startTime)) / (1000 * 60 * 60)
      return durationHours > 6
    }

    // 更新分析数据
    const updateAnalysisData = () => {
      // 触发响应式更新
      // 由于使用了computed属性，数据会自动更新
    }

    // 获取当前选择日期的显示文本
    const getSelectedDateText = () => {
      const date = new Date(analysisSelectedDate.value)
      const dimension = currentTimeDimension.value
      
      switch (dimension) {
        case 'day':
          return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' })
        case 'week':
          const weekStart = new Date(date)
          weekStart.setDate(date.getDate() - date.getDay())
          const weekEnd = new Date(weekStart)
          weekEnd.setDate(weekStart.getDate() + 6)
          return `${weekStart.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' })} - ${weekEnd.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' })}`
        case 'month':
          return date.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit' })
        case 'year':
          return date.getFullYear().toString()
        default:
          return date.toLocaleDateString('zh-CN')
      }
    }

    const previousDate = () => {
      const date = new Date(analysisSelectedDate.value)
      date.setDate(date.getDate() - 1)
      analysisSelectedDate.value = date.toISOString().split('T')[0]
    }

    const nextDate = () => {
      const date = new Date(analysisSelectedDate.value)
      date.setDate(date.getDate() + 1)
      analysisSelectedDate.value = date.toISOString().split('T')[0]
    }

    const goToToday = () => {
      analysisSelectedDate.value = new Date().toISOString().split('T')[0]
    }

    const switchToDayView = () => {
      calendarView.value = 'day'
      scrollToCurrentTime()
    }

    const switchToWeekView = () => {
      calendarView.value = 'week'
      scrollToCurrentTime()
    }

    const focusHiddenInput = () => {
      nextTick(() => {
        const hiddenInput = document.querySelector('.hidden-input')
        if (hiddenInput) {
          hiddenInput.focus()
        }
      })
    }

    const onHiddenInput = (event) => {
      const value = event.target.value
      const digits = value.replace(/\D/g, '').slice(0, 6).split('')
      
      // 更新显示的数字
      pinDigits.value = [...digits, '', '', '', '', '', ''].slice(0, 6)
      pinError.value = ''
      
      // 如果输入了6位数字，自动验证
      if (digits.length === 6) {
        checkPin()
        // 清空隐藏输入框
        event.target.value = ''
      }
    }

    const onHiddenKeydown = (event) => {
      // 只允许数字输入
      if (!/^\d$/.test(event.key) && 
          event.key !== 'Backspace' && 
          event.key !== 'Delete' && 
          event.key !== 'Tab' && 
          event.key !== 'Enter' &&
          !event.ctrlKey && 
          !event.metaKey) {
        event.preventDefault()
      }
      
      // 如果按回车键且输入了6位数字，验证密码
      if (event.key === 'Enter' && event.target.value.length === 6) {
        checkPin()
        event.target.value = ''
      }
    }

          return {
        tasks,
        projects,
        newTask,
        newTaskProject,
        newTaskType,
        newTaskPriority,
        newTaskImportance,
        newTaskUrgency,
        newTaskStartTime,
        newTaskEndTime,
        currentFilter,
        currentTypeFilter,
        currentProject,
        currentMenu,
        showAddProject,
        newProjectName,
        showEditTaskModal,
        editingTaskData,
        filters,
        totalTasks,
        completedTasks,
        pendingTasks,
        todayTasks,
        projectDistribution,
        typeDistribution,
        totalWorkHours,
        averageTaskHours,
        filteredTasks,
        addTask,
        addProject,
        toggleTask,
        deleteTask,
        openEditTaskModal,
        closeEditTaskModal,
        saveEditTask,
        setCurrentTime,
        clearTime,
        clearTimer,
        toggleTimer,
        startTimer,
        stopTimer,
        restoreTimerState,
        getCurrentTimerDuration,
        notification,
        showNotification,
        exportData,
        importData,
        clearData,
        clearDefaultData,
        handleFileImport,
        getPriorityText,
        getTypeText,
        getProjectName,
        getProjectTaskCount,
        formatDate,
        formatDateTime,
        calculateDuration,
        formatDuration,
        formatTimer,
        // 日历相关方法
        calendarView,
        selectedDate,
        selectedTask,
        calendarTitle,
        weekDays,
        monthDays,
        dayTasks,
        completedDayTasks,
        dayWorkHours,
        previousPeriod,
        nextPeriod,
        getTasksForHour,
        getTasksStartingAtHour,
        getTasksActiveAtHour,
        getTasksActiveForDayAndHour,
        getTasksStartingForDayAndHour,
        getTaskTimelineStyle,
        getWeekTaskTimelineStyle,
        getTasksForDayAndHour,
        getTasksForDay,
        getDayTaskCount,
        isToday,
        formatDayDate,
        formatTime,
        currentTimeLine,
        isCurrentTimeLine,
        selectDate,
        selectTask,
        editTaskFromCalendar,
        scrollToCurrentTime,
        // 四象限相关方法
        quadrantTasks,
        getQuadrantTitle,
        getQuadrantDescription,
        getQuadrantColor,
        // 工作分析相关方法
        currentTimeDimension,
        timeDimensions,
        getOverviewData,
        getProjectChartData,
        getTypeChartData,
        getTrendData,
        getTrendPath,
        getTrendCurvePath,
        getMaxTaskCount,
        getMaxBarTaskCount,
        getXAxisLabels,
        getHourTaskCount,
        getHourTaskMinutes,
        getHourColor,
        getEfficiencyScore,
        getProjectBalanceScore,
        getQualityScore,
        getEfficiencyClass,
        getProjectBalanceClass,
        getQualityClass,
        getOverallScore,
        getOverallStatus,
        getOverallStatusClass,
        // 全屏相关方法
        isFullscreen,
        toggleFullscreen,
        // 服务器同步相关方法
        serverUrl,
        isOnline,
        lastServerUpdate,
        syncStatus,
        checkServerConnection,
        syncToServer,
        syncFromServer,
        autoSync,
        isLongTask,
        updateAnalysisData,
        getSelectedDateText,
        previousDate,
        nextDate,
        goToToday,
        fileInput,
        switchToDayView,
        switchToWeekView,
        // 密码验证相关
        isAuthenticated,
        pinDigits,
        pinError,
        onPinInput,
        onPinKeydown,
        onPinPaste,
        // 加密存储相关
        getStoredPin,
        setStoredPin,
        focusHiddenInput,
        onHiddenInput,
        onHiddenKeydown
      }
  }
}
</script>

<style scoped>
.edit-input {
  width: 100%;
  padding: 8px 12px;
  border: 2px solid #667eea;
  border-radius: 8px;
  font-size: 1.1rem;
  font-weight: 500;
  color: #2d3748;
  background: white;
}

.edit-input:focus {
  outline: none;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

/* 编辑任务弹窗样式 */
.edit-task-modal {
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 1rem;
  border-bottom: 1px solid #e2e8f0;
  margin-bottom: 1.5rem;
}

.btn-close {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #718096;
  padding: 0.5rem;
  border-radius: 0.5rem;
  transition: all 0.2s;
}

.btn-close:hover {
  background: #f7fafc;
  color: #2d3748;
}

.modal-body {
  padding: 0;
}

.edit-section {
  margin-bottom: 2rem;
  padding: 1.5rem;
  background: #f8fafc;
  border-radius: 12px;
  border: 1px solid #e2e8f0;
}

.edit-section h4 {
  margin: 0 0 1rem 0;
  color: #2d3748;
  font-size: 1.1rem;
  font-weight: 600;
}

.form-group {
  margin-bottom: 1rem;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  color: #4a5568;
  font-weight: 500;
  font-size: 0.9rem;
}

.form-input,
.form-select {
  width: 100%;
  padding: 0.75rem 1rem;
  border: 2px solid #e2e8f0;
  border-radius: 8px;
  font-size: 1rem;
  color: #2d3748;
  background: white;
  transition: all 0.2s;
}

.form-input:focus,
.form-select:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.time-actions {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
  margin-top: 1rem;
}

.btn-sm {
  padding: 0.5rem 1rem;
  font-size: 0.875rem;
}

.duration-display {
  margin-top: 1rem;
  padding: 0.75rem 1rem;
  background: #e6fffa;
  border: 1px solid #81e6d9;
  border-radius: 8px;
  color: #234e52;
  font-weight: 500;
}

.timer-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  background: #fef5e7;
  border: 1px solid #f6ad55;
  border-radius: 8px;
  color: #744210;
  font-weight: 500;
}

.status-toggle {
  display: flex;
  align-items: center;
}

.toggle-label {
  display: flex;
  align-items: center;
  cursor: pointer;
  user-select: none;
}

.toggle-input {
  display: none;
}

.toggle-slider {
  position: relative;
  width: 50px;
  height: 24px;
  background: #cbd5e0;
  border-radius: 12px;
  margin-right: 0.75rem;
  transition: all 0.3s;
}

.toggle-slider:before {
  content: '';
  position: absolute;
  top: 2px;
  left: 2px;
  width: 20px;
  height: 20px;
  background: white;
  border-radius: 50%;
  transition: all 0.3s;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.toggle-input:checked + .toggle-slider {
  background: #667eea;
}

.toggle-input:checked + .toggle-slider:before {
  transform: translateX(26px);
}

.toggle-text {
  font-weight: 500;
  color: #2d3748;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .edit-task-modal {
    margin: 1rem;
    max-width: calc(100vw - 2rem);
  }
  
  .form-row {
    grid-template-columns: 1fr;
  }
  
  .time-actions {
    flex-direction: column;
  }
  
  .time-actions .btn {
    width: 100%;
  }
}
</style> 