<% @page_title = '清巡 - 自定义集成代码' %>
<% @active_page = 'custom_integration' %>

<style>
.custom-integration-wrapper {
  max-width: none;
  width: 100%;
  margin: 0 auto;
  padding: 0 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.status-info {
  margin-bottom: 24px;
}

.editor-section {
  margin-top: 24px;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.editor-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.code-editor-container {
  margin: 16px 0;
}

.code-editor-container .el-textarea__inner {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 14px;
  width: 100%;
  min-width: 100%;
  max-width: 100%;
  overflow-x: auto;
  white-space: pre;
  word-wrap: normal;
}

.save-notes {
  margin-top: 16px;
}

.history-list {
  padding: 16px;
}

.code-preview {
  background: #f5f7fa;
  padding: 12px;
  border-radius: 4px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  overflow-x: auto;
  white-space: pre-wrap;
  word-break: break-all;
}

.server-code-container {
  max-height: 70vh;
  overflow-y: auto;
}

.readonly-code-editor .el-textarea__inner {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 14px;
  background-color: #f9f9f9;
  cursor: default;
  user-select: text;
  white-space: pre;
  overflow-x: auto;
  overflow-y: auto;
  max-height: 70vh;
}

.readonly-code-editor .el-textarea__inner:focus {
  border-color: #dcdfe6;
}
</style>

<div id="custom-integration-app">
  <div class="custom-integration-wrapper">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>自定义集成代码管理</span>
          <div class="header-actions">
            <el-button type="primary" size="small" @click="syncCode" :loading="syncLoading">
              同步服务器版本
            </el-button>
            <el-button type="info" size="small" @click="showServerVersion">
              查看服务器版本
            </el-button>
            <el-button size="small" @click="showHistory = !showHistory">
              查看历史
            </el-button>
          </div>
        </div>
      </template>

      <!-- 状态信息 -->
      <div class="status-info" v-if="status">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="当前版本">
            <el-tag type="success">
              客户端版本
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="服务器版本哈希">
            {{ status.server_version_hash || '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="客户端版本哈希">
            {{ status.user_version_hash || '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="最后同步时间">
            {{ formatTime(status.last_synced_at) }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 代码编辑器区域 -->
      <div class="editor-section">
        <div class="editor-header">
          <h3>自定义集成代码（客户端版本）</h3>
          <div class="editor-actions">
            <el-button type="primary" @click="saveCode" :loading="saveLoading">
              保存客户端版本
            </el-button>
          </div>
        </div>

        

        <div class="code-editor-container">
          <el-input
            v-model="code"
            type="textarea"
            :rows="20"
            placeholder="请输入自定义集成代码（客户端版本）..."
            resize="none"
          />
        </div>

        <!-- 保存备注 -->
        <div class="save-notes">
          <el-input
            v-model="notes"
            placeholder="添加备注（可选）"
            clearable
          >
            <template #prepend>
              备注：
            </template>
          </el-input>
        </div>
      </div>

      <!-- 历史记录抽屉 -->
      <el-drawer
        v-model="showHistory"
        title="编辑历史"
        direction="rtl"
        size="40%"
      >
        <div class="history-list">
          <el-timeline v-if="history.length > 0">
            <el-timeline-item
              v-for="item in history"
              :key="item.timestamp"
              :timestamp="formatTime(item.timestamp)"
              placement="top"
            >
              <el-card>
                <h4>版本哈希：{{ item.version_hash }}</h4>
                <p>备注：{{ item.notes || '无' }}</p>
                <p>代码长度：{{ item.length }} 字符</p>
                <el-collapse>
                  <el-collapse-item title="代码预览">
                    <div style="margin-bottom: 10px;">
                      <el-button type="primary" size="small" @click="showFullCode(item)">
                        查看完整代码
                      </el-button>
                    </div>
                    <pre class="code-preview">{{ item.code_preview ? item.code_preview.slice(0, 500) + (item.code_preview.length > 500 ? '...（预览已截断，点击查看完整代码）' : '') : '' }}</pre>
                  </el-collapse-item>
                </el-collapse>
              </el-card>
            </el-timeline-item>
          </el-timeline>
          <el-empty v-else description="暂无历史记录" />
        </div>
      </el-drawer>

      <!-- 服务器版本查看对话框 -->
      <el-dialog
        v-model="showServerVersionDialog"
        title="服务器版本代码"
        width="80%"
        top="5vh"
      >
        <div class="server-code-container">
          <el-descriptions :column="1" border size="small" style="margin-bottom: 16px;">
            <el-descriptions-item label="版本哈希">
              {{ serverVersionData.version_hash || '无' }}
            </el-descriptions-item>
            <el-descriptions-item label="更新时间">
              {{ formatTime(serverVersionData.updated_at) }}
            </el-descriptions-item>
          </el-descriptions>
          <el-input
            v-model="serverVersionData.code"
            type="textarea"
            :rows="30"
            readonly
            resize="none"
            class="readonly-code-editor"
          />
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showServerVersionDialog = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 完整代码查看对话框 -->
      <el-dialog
        v-model="showFullCodeDialog"
        :title="'历史代码版本：' + (selectedHistoryItem?.version_hash || '')"
        width="80%"
        top="5vh"
      >
        <div class="server-code-container">
          <el-descriptions :column="1" border size="small" style="margin-bottom: 16px;">
            <el-descriptions-item label="版本哈希">
              {{ selectedHistoryItem?.version_hash || '无' }}
            </el-descriptions-item>
            <el-descriptions-item label="时间">
              {{ formatTime(selectedHistoryItem?.timestamp) }}
            </el-descriptions-item>
            <el-descriptions-item label="备注">
              {{ selectedHistoryItem?.notes || '无' }}
            </el-descriptions-item>
            <el-descriptions-item label="代码长度">
              {{ selectedHistoryItem?.length || 0 }} 字符
            </el-descriptions-item>
          </el-descriptions>
          <el-input
            :value="selectedHistoryItem?.code_preview || ''"
            type="textarea"
            :rows="30"
            readonly
            resize="none"
            class="readonly-code-editor"
          />
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showFullCodeDialog = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</div>

<% content_for :xxx do %>
<script>
const { createApp, ref, onMounted, computed, watch } = Vue;
const { ElMessage, ElMessageBox } = ElementPlus;

const app = createApp({
  setup() {
    // 状态
    const status = ref(null);
    const code = ref('');
    const notes = ref('');
    const showHistory = ref(false);
    const showServerVersionDialog = ref(false);
    const history = ref([]);
    const saveLoading = ref(false);
    const syncLoading = ref(false);
    const showFullCodeDialog = ref(false);
    const selectedHistoryItem = ref(null);
    const historyLoading = ref(false);
    const serverVersionData = ref({
      code: '',
      version_hash: '',
      updated_at: ''
    });

    // 计算属性
    const hasClientVersion = computed(() => {
      return status.value && status.value.user_version_hash;
    });

    // 方法
    const loadStatus = async () => {
      try {
        const response = await fetch('/api/custom-integration/status');
        const result = await response.json();
        if (result.success) {
          status.value = result.data;
        } else {
          ElMessage.error(result.message || '获取状态失败');
        }
      } catch (error) {
        ElMessage.error('网络请求失败：' + error.message);
      }
    };

    const loadCode = async () => {
      try {
        const response = await fetch('/api/custom-integration/code');
        const result = await response.json();
        if (result.success) {
          code.value = result.data.code;
        } else {
          ElMessage.error(result.message || '获取代码失败');
        }
      } catch (error) {
        ElMessage.error('网络请求失败：' + error.message);
      }
    };

    const loadHistory = async () => {
      if (historyLoading.value) return; // 防止重复加载

      historyLoading.value = true;
      try {
        console.log('[CustomIntegration] 开始加载历史记录...');
        const response = await fetch('/api/custom-integration/history');
        console.log('[CustomIntegration] 历史记录响应状态:', response.status);
        const result = await response.json();
        console.log('[CustomIntegration] 历史记录结果:', result);
        if (result.success) {
          console.log('[CustomIntegration] 获取到历史记录数量:', result.data.length);
          history.value = result.data;
        } else {
          console.error('[CustomIntegration] 获取历史记录失败:', result.message);
          ElMessage.error(result.message || '获取历史记录失败');
        }
      } catch (error) {
        console.error('[CustomIntegration] 加载历史记录异常:', error);
        ElMessage.error('网络请求失败：' + error.message);
      } finally {
        historyLoading.value = false;
      }
    };

    const saveCode = async () => {
      if (!code.value.trim()) {
        ElMessage.warning('代码内容不能为空');
        return;
      }

      saveLoading.value = true;
      try {
        console.log('[CustomIntegration] 开始保存代码...');
        const response = await fetch('/api/custom-integration/code', {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            code: code.value,
            notes: notes.value
          })
        });
        console.log('[CustomIntegration] 保存响应状态:', response.status);
        const result = await response.json();
        console.log('[CustomIntegration] 保存结果:', result);
        if (result.success) {
          ElMessage.success('客户端版本代码已保存');
          notes.value = '';
          console.log('[CustomIntegration] 保存成功，重新加载状态和历史...');
          await loadStatus();
          await loadHistory();
          console.log('[CustomIntegration] 重新加载完成');
        } else {
          console.error('[CustomIntegration] 保存失败:', result.message);
          ElMessage.error(result.message || '保存失败');
        }
      } catch (error) {
        console.error('[CustomIntegration] 保存异常:', error);
        ElMessage.error('网络请求失败：' + error.message);
      } finally {
        saveLoading.value = false;
      }
    };

    const clearClientVersion = () => {
      ElMessageBox.confirm(
        '确定要从服务器版本恢复吗？这将清除您的客户端版本代码。',
        '确认操作',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          const response = await fetch('/api/custom-integration/code', {
            method: 'DELETE'
          });
          const result = await response.json();
          if (result.success) {
            ElMessage.success('已从服务器版本恢复');
            await loadStatus();
            await loadCode();
            await loadHistory();
          } else {
            ElMessage.error(result.message || '操作失败');
          }
        } catch (error) {
          ElMessage.error('网络请求失败：' + error.message);
        }
      }).catch(() => {
        // 用户取消
      });
    };

    const syncCode = async () => {
      syncLoading.value = true;
      try {
        const response = await fetch('/api/custom-integration/sync', {
          method: 'POST'
        });
        const result = await response.json();
        if (result.success) {
          ElMessage.success(result.message || '同步请求已发送');
          await loadStatus();
          await loadCode();
        } else {
          ElMessage.error(result.message || '同步失败');
        }
      } catch (error) {
        ElMessage.error('网络请求失败：' + error.message);
      } finally {
        syncLoading.value = false;
      }
    };

    const showServerVersion = async () => {
      try {
        const response = await fetch('/api/custom-integration/server-code');
        const result = await response.json();
        if (result.success) {
          serverVersionData.value = result.data;
          showServerVersionDialog.value = true;
        } else {
          ElMessage.error(result.message || '获取服务器版本失败');
        }
      } catch (error) {
        ElMessage.error('网络请求失败：' + error.message);
      }
    };

    const formatTime = (timeStr) => {
      if (!timeStr) return '未知时间';
      return new Date(timeStr).toLocaleString('zh-CN');
    };

    const showFullCode = (item) => {
      selectedHistoryItem.value = item;
      showFullCodeDialog.value = true;
    };

    // 监听历史抽屉显示状态，每次打开时重新加载历史数据
    watch(showHistory, (newValue) => {
      if (newValue) {
        // 使用立即执行的异步函数加载历史，确保错误被捕获
        (async () => {
          await loadHistory();
        })();
      }
    });

    // 初始化
    onMounted(async () => {
      await Promise.all([loadStatus(), loadCode(), loadHistory()]);
    });

    return {
      status,
      code,
      notes,
      showHistory,
      showServerVersionDialog,
      serverVersionData,
      history,
      saveLoading,
      syncLoading,
      historyLoading,
      hasClientVersion,
      showFullCodeDialog,
      selectedHistoryItem,
      loadStatus,
      loadCode,
      loadHistory,
      saveCode,
      clearClientVersion,
      syncCode,
      showServerVersion,
      formatTime,
      showFullCode
    };
  }
});

app.use(ElementPlus);
app.mount('#custom-integration-app');
</script>
<% end %>