<% @page_title = '清巡 - 我的脚本' %>
<% @active_page = 'scripts' %>

  <div id="app">
    <div class="page-wrapper">
      
      <main class="main-content">
        <div class="content-card">
          <div class="card-header">
            <h3><i class="el-icon-document" style="margin-right: 8px;"></i>我的脚本</h3>
            <div style="display: flex; gap: 12px;">
              <el-button type="primary" @click="syncScripts" :loading="syncing">同步脚本</el-button>
            </div>
          </div>
          <div class="card-body">
            <div style="margin-bottom: 20px; display: flex; gap: 16px; align-items: center;">
              <el-input
                v-model="searchQuery"
                placeholder="搜索脚本名称或描述..."
                clearable
                style="width: 300px;"
              ></el-input>
              <div style="flex: 1;"></div>
              <el-text>
                共 {{ filteredScripts.length }} 个脚本
                <span v-if="lastSyncTime" style="margin-left: 16px; color: #909399;">
                  上次同步: {{ formatTime(lastSyncTime) }}
                </span>
              </el-text>
            </div>

            <div v-if="filteredScripts.length > 0">
              <el-table :data="filteredScripts" stripe style="width: 100%;" v-loading="loading">
                <el-table-column prop="name" label="脚本名称" min-width="180"></el-table-column>
                <el-table-column prop="description" label="描述" min-width="250" show-overflow-tooltip></el-table-column>
                <el-table-column prop="version" label="版本" width="100">
                  <template #default="scope">
                    v{{ scope.row.version }}
                  </template>
                </el-table-column>
                <el-table-column prop="device_model_pattern" label="适配设备" width="180" show-overflow-tooltip></el-table-column>
                <el-table-column prop="updated_at" label="更新时间" width="160">
                  <template #default="scope">
                    {{ formatTime(scope.row.updated_at) }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120" fixed="right">
                  <template #default="scope">
                    <el-button type="primary" size="small" link @click="viewScript(scope.row)">查看详情</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <div class="empty-state" v-else-if="!loading">
              <div class="empty-icon">📜</div>
              <p>暂无脚本</p>
              <p style="margin-top: 8px; font-size: 14px;">点击"同步脚本"按钮从云端获取脚本</p>
            </div>

            <div class="empty-state" v-else>
              <div style="font-size: 48px; animation: rotating 2s linear infinite;">⏳</div>
              <p style="margin-top: 16px;">加载中...</p>
            </div>
          </div>
        </div>
      </main>

      <!-- 脚本详情对话框 -->
      <el-dialog
        v-model="detailDialogVisible"
        title="脚本详情"
        width="70%"
        :close-on-click-modal="false"
      >
        <div v-if="currentScript">
          <el-descriptions :column="2" border style="margin-bottom: 20px;">
            <el-descriptions-item label="脚本名称">{{ currentScript.name }}</el-descriptions-item>
            <el-descriptions-item label="版本">v{{ currentScript.version }}</el-descriptions-item>
            <el-descriptions-item label="描述" :span="2">{{ currentScript.description }}</el-descriptions-item>
            <el-descriptions-item label="设备型号匹配">{{ currentScript.device_model_pattern || '未指定' }}</el-descriptions-item>
            <el-descriptions-item label="更新时间">{{ formatTime(currentScript.updated_at) }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ formatTime(currentScript.created_at) }}</el-descriptions-item>
          </el-descriptions>

          <h4 style="margin-bottom: 12px; color: #303133;">脚本代码</h4>
          <pre style="background: #f5f7fa; padding: 16px; border-radius: 4px; overflow: auto; max-height: 400px; font-size: 13px; line-height: 1.6;">{{ currentScript.code || '暂无代码' }}</pre>
        </div>
        <template #footer>
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </template>
      </el-dialog>
    </div>
  </div>

  <% content_for :xxx do %>
  <script>
    const { createApp, ref, onMounted, computed } = Vue;
    const app = createApp({
      setup() {
        const scripts = ref([]);
        const searchQuery = ref('');
        const loading = ref(true);
        const syncing = ref(false);
        const lastSyncTime = ref(null);
        const detailDialogVisible = ref(false);
        const currentScript = ref(null);

        const filteredScripts = computed(() => {
          if (!searchQuery.value) {
            return scripts.value;
          }
          const query = searchQuery.value.toLowerCase();
          return scripts.value.filter(script => 
            (script.name && script.name.toLowerCase().includes(query)) ||
            (script.description && script.description.toLowerCase().includes(query))
          );
        });

        const fetchScripts = async () => {
          try {
            console.log('[DEBUG] 开始获取脚本列表...');
            loading.value = true;
            const response = await fetch('/api/v1/scripts');
            console.log('[DEBUG] 响应状态:', response.status, response.statusText);
            console.log('[DEBUG] 响应头:', Object.fromEntries(response.headers.entries()));
            
            const text = await response.text();
            console.log('[DEBUG] 响应内容 (前500字符):', text.substring(0, 500));
            
            if (!response.ok) {
              throw new Error(`HTTP ${response.status}: ${text}`);
            }
            
            const data = JSON.parse(text);
            console.log('[DEBUG] 解析后的数据:', data);
            scripts.value = Array.isArray(data) ? data : [];
            console.log('[DEBUG] 脚本数量:', scripts.value.length);
          } catch (error) {
            console.error('[DEBUG] 获取脚本列表失败:', error);
            ElementPlus.ElMessage.error('获取脚本列表失败: ' + error.message);
          } finally {
            loading.value = false;
          }
        };

        const fetchSyncStatus = async () => {
          try {
            const response = await fetch('/api/v1/scripts/sync/status');
            const data = await response.json();
            if (data.success && data.data && data.data.last_sync_time) {
              lastSyncTime.value = data.data.last_sync_time;
            }
          } catch (error) {
            console.error('获取同步状态失败:', error);
          }
        };

        const syncScripts = async () => {
          try {
            syncing.value = true;
            ElementPlus.ElMessage.info('正在同步脚本...');
            
            const response = await fetch('/api/v1/scripts/sync', {
              method: 'POST'
            });
            const result = await response.json();
            
            if (result.success) {
              ElementPlus.ElMessage.success(
                `同步完成！共处理 ${result.synced} 个，新增 ${result.created} 个，更新 ${result.updated} 个`
              );
              await fetchScripts();
              await fetchSyncStatus();
            } else {
              ElementPlus.ElMessage.error(result.error || '同步失败');
            }
          } catch (error) {
            console.error('同步脚本失败:', error);
            ElementPlus.ElMessage.error('同步脚本失败');
          } finally {
            syncing.value = false;
          }
        };

        const viewScript = (script) => {
          currentScript.value = script;
          detailDialogVisible.value = true;
        };

        const formatTime = (timestamp) => {
          if (!timestamp) return '-';
          const date = new Date(timestamp);
          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} ${hours}:${minutes}`;
        };

        onMounted(() => {
          fetchScripts();
          fetchSyncStatus();
        });

        return {
          scripts,
          searchQuery,
          filteredScripts,
          loading,
          syncing,
          lastSyncTime,
          detailDialogVisible,
          currentScript,
          fetchScripts,
          syncScripts,
          viewScript,
          formatTime
        };
      }
    });
    app.use(ElementPlus);
  app.mount('#app');
  </script>
<% end %>