<template>
  <div class="annotation-editor">
    <!-- 文档预览区域 -->
    <div v-if="ossId && canPreview" class="editor-wrapper">
      <!-- 顶部工具栏 -->
      <div class="editor-header">
        <!-- 文件信息 -->
        <div class="file-info">
          <el-icon class="file-icon"><Document /></el-icon>
          <span class="file-name">{{ fileName || '未命名文档' }}</span>
          <el-tag v-if="fileType" size="small" effect="plain">{{ fileType.toUpperCase() }}</el-tag>
        </div>

        <!-- 操作按钮 -->
        <div class="editor-actions">
          <!-- 编辑模式切换（所有文档类型） -->
          <el-switch v-model="useWpsEditor" active-text="在线编辑" inactive-text="预览模式" inline-prompt size="large" />

          <!-- WPS 设置按钮 -->
          <el-button v-if="useWpsEditor" @click="showSettings" circle>
            <el-icon><Setting /></el-icon>
          </el-button>

          <!-- 保存按钮 -->
          <el-button v-if="useWpsEditor && wpsEditorRef" type="primary" @click="handleSaveEdit" :loading="saving">
            <el-icon><Download /></el-icon>
            保存
          </el-button>
        </div>
      </div>

      <!-- 文档内容区域 -->
      <div class="editor-content">
        <!-- WPS 编辑器（支持所有格式：Word/Excel/PPT/PDF） -->
        <div v-if="useWpsEditor && fileUrl" class="wps-wrapper">
          <WpsEditor
            :file-url="fileUrl"
            :file-name="fileName"
            :file-type="fileType"
            :mode="wpsMode"
            :user-id="userStore.userId?.toString()"
            :user-name="userStore.userName"
            :enable-comment="wpsOptions.enableComment"
            :enable-revision="wpsOptions.enableRevision"
            :enable-watermark="wpsOptions.enableWatermark"
            :watermark-text="wpsOptions.watermarkText"
            :enable-download="wpsOptions.enableDownload"
            :enable-print="wpsOptions.enablePrint"
            :enable-copy="wpsOptions.enableCopy"
            :enable-save="wpsOptions.enableSave"
            :enable-share="wpsOptions.enableShare"
            :enable-history="wpsOptions.enableHistory"
            :read-only="wpsOptions.readOnly"
            @ready="handleWpsReady"
            @error="handleWpsError"
            @save="handleWpsSave"
            @file-change="handleWpsFileChange"
            ref="wpsEditorRef"
          />
        </div>

        <!-- Word 预览 -->
        <div v-else-if="fileType === 'docx' && fileBlob && !useWpsEditor" class="preview-wrapper">
          <VueOfficeDocx :src="fileBlob" @rendered="handleRendered" @error="handlePreviewError" />
        </div>

        <!-- Excel 预览 -->
        <div v-else-if="fileType === 'xlsx' && fileBlob && !useWpsEditor" class="preview-wrapper">
          <VueOfficeExcel :src="fileBlob" @rendered="handleRendered" @error="handlePreviewError" />
        </div>

        <!-- PDF 预览 -->
        <div v-else-if="fileType === 'pdf' && fileBlob && !useWpsEditor" class="pdf-wrapper">
          <div class="pdf-viewer">
            <VueOfficePdf :src="fileBlob" @rendered="handleRendered" @error="handlePreviewError" />
          </div>
        </div>

        <!-- 加载状态 -->
        <div v-if="previewLoading" class="loading-state">
          <el-icon class="is-loading"><Loading /></el-icon>
          <p>文档加载中...</p>
        </div>

        <!-- 错误状态 -->
        <el-result v-if="previewError" icon="error" title="加载失败" :sub-title="previewError">
          <template #extra>
            <el-button type="primary" @click="downloadFileForPreview">重新加载</el-button>
          </template>
        </el-result>
      </div>
    </div>

    <!-- 空状态 -->
    <el-empty v-else description="暂无文档" :image-size="120" />

    <!-- WPS 设置抽屉 -->
    <el-drawer v-model="settingsVisible" title="编辑器设置" direction="rtl" size="400px">
      <el-tabs v-model="activeTab" class="settings-tabs">
        <!-- 编辑模式 -->
        <el-tab-pane label="编辑模式" name="mode">
          <div class="settings-section">
            <el-radio-group v-model="wpsMode" class="mode-radio-group">
              <el-radio value="normal" border>
                <div class="radio-label">
                  <div class="label-title">完整模式</div>
                  <div class="label-desc">显示所有编辑工具</div>
                </div>
              </el-radio>
              <el-radio value="simple" border>
                <div class="radio-label">
                  <div class="label-title">简洁模式</div>
                  <div class="label-desc">只显示基本工具</div>
                </div>
              </el-radio>
            </el-radio-group>
          </div>
        </el-tab-pane>

        <!-- 功能开关 -->
        <el-tab-pane label="功能开关" name="features">
          <div class="settings-section">
            <div class="setting-item">
              <div class="item-label">
                <span>批注功能</span>
                <span class="item-desc">允许添加和查看批注</span>
              </div>
              <el-switch v-model="wpsOptions.enableComment" />
            </div>
            <el-divider />

            <div class="setting-item">
              <div class="item-label">
                <span>修订功能</span>
                <span class="item-desc">跟踪文档修改记录</span>
              </div>
              <el-switch v-model="wpsOptions.enableRevision" />
            </div>
            <el-divider />

            <div class="setting-item">
              <div class="item-label">
                <span>水印功能</span>
                <span class="item-desc">在文档中显示水印</span>
              </div>
              <el-switch v-model="wpsOptions.enableWatermark" />
            </div>

            <div v-if="wpsOptions.enableWatermark" class="watermark-input">
              <el-input v-model="wpsOptions.watermarkText" placeholder="输入水印文字" clearable />
            </div>
          </div>
        </el-tab-pane>

        <!-- 权限控制 -->
        <el-tab-pane label="权限控制" name="permissions">
          <div class="settings-section">
            <div class="setting-item">
              <div class="item-label">
                <span>下载权限</span>
                <span class="item-desc">允许下载文档</span>
              </div>
              <el-switch v-model="wpsOptions.enableDownload" />
            </div>
            <el-divider />

            <div class="setting-item">
              <div class="item-label">
                <span>打印权限</span>
                <span class="item-desc">允许打印文档</span>
              </div>
              <el-switch v-model="wpsOptions.enablePrint" />
            </div>
            <el-divider />

            <div class="setting-item">
              <div class="item-label">
                <span>复制权限</span>
                <span class="item-desc">允许复制内容</span>
              </div>
              <el-switch v-model="wpsOptions.enableCopy" />
            </div>
            <el-divider />

            <div class="setting-item">
              <div class="item-label">
                <span>只读模式</span>
                <span class="item-desc">文档只能查看</span>
              </div>
              <el-switch v-model="wpsOptions.readOnly" />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>

      <template #footer>
        <div class="drawer-footer">
          <el-button @click="settingsVisible = false">取消</el-button>
          <el-button type="primary" @click="applySettings">应用设置</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue';
import { Document, Loading, Close, Edit, ChatLineSquare, Setting, Download, Delete } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import VueOfficeDocx from '@vue-office/docx';
import VueOfficeExcel from '@vue-office/excel';
import VueOfficePdf from '@vue-office/pdf';
import '@vue-office/docx/lib/index.css';
import '@vue-office/excel/lib/index.css';
import request from '@/utils/request';
import WpsEditor from '@/components/WpsEditor/index.vue';
import { useUserStore } from '@/store/modules/user';

interface Props {
  ossId?: number | string;
  fileName?: string;
}

interface Emits {
  (e: 'ready'): void;
  (e: 'save', data: any): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const userStore = useUserStore();

const previewLoading = ref(false);
const previewError = ref('');
const fileBlob = ref<ArrayBuffer | null>(null);
const fileUrl = ref('');
const useWpsEditor = ref(false);
const wpsMode = ref<'simple' | 'normal'>('normal');
const wpsEditorRef = ref<InstanceType<typeof WpsEditor>>();
const saving = ref(false);
const settingsVisible = ref(false);
const activeTab = ref('mode');

// WPS 高级选项
const wpsOptions = ref({
  enableComment: true,
  enableRevision: true,
  enableWatermark: false,
  watermarkText: '',
  enableDownload: true,
  enablePrint: true,
  enableCopy: true,
  enableSave: true,
  enableShare: false,
  enableHistory: false,
  readOnly: false
});

// 获取文件类型
const fileType = computed(() => {
  if (!props.fileName) return '';
  const fileName = props.fileName.toLowerCase();
  if (fileName.endsWith('.docx') || fileName.endsWith('.doc')) return 'docx';
  if (fileName.endsWith('.xlsx') || fileName.endsWith('.xls')) return 'xlsx';
  if (fileName.endsWith('.pdf')) return 'pdf';
  return '';
});

// 判断是否可以预览
const canPreview = computed(() => {
  return ['docx', 'xlsx', 'pdf'].includes(fileType.value);
});

// 下载文件用于预览
const downloadFileForPreview = async () => {
  if (!props.ossId || !canPreview.value) {
    previewLoading.value = false;
    return;
  }

  try {
    previewLoading.value = true;
    previewError.value = '';
    fileBlob.value = null;
    fileUrl.value = '';

    const baseURL = import.meta.env.VITE_APP_BASE_API;
    fileUrl.value = `${baseURL}/resource/oss/downloadWithoutPermission/${props.ossId}`;

    if (!useWpsEditor.value) {
      const response = await request({
        url: `/resource/oss/downloadWithoutPermission/${props.ossId}`,
        method: 'get',
        responseType: 'arraybuffer'
      });
      fileBlob.value = response;
    }
  } catch (error) {
    console.error('下载文件失败:', error);
    previewError.value = '文件下载失败，请重试';
    previewLoading.value = false;
  }
};

// WPS 编辑器就绪
const handleWpsReady = () => {
  previewLoading.value = false;
  emit('ready');
};

// WPS 编辑器错误
const handleWpsError = (error: string) => {
  previewError.value = error;
  previewLoading.value = false;
};

// WPS 编辑器保存
const handleWpsSave = (data: any) => {
  ElMessage.success('文档已保存');
  emit('save', data);
};

// WPS 文件变化
const handleWpsFileChange = (data: any) => {
  console.log('WPS 文件变化:', data);
};

// 文档渲染完成
const handleRendered = () => {
  previewLoading.value = false;
};

// 文档预览错误
const handlePreviewError = (error: any) => {
  previewLoading.value = false;
  previewError.value = '文档预览失败，请尝试重新加载';
  console.error('文档预览错误:', error);
};

// 显示设置
const showSettings = () => {
  settingsVisible.value = true;
};

// 应用设置
const applySettings = () => {
  settingsVisible.value = false;
  ElMessage.success('设置已应用');
  // 重新加载编辑器
  if (useWpsEditor.value) {
    downloadFileForPreview();
  }
};

// 保存编辑
const handleSaveEdit = async () => {
  if (!wpsEditorRef.value) {
    ElMessage.warning('编辑器未初始化');
    return;
  }

  saving.value = true;
  try {
    const result = await wpsEditorRef.value.saveDocument();
    ElMessage.success('文档已保存');
    emit('save', result);
  } catch (error) {
    console.error('保存编辑失败:', error);
    ElMessage.error('保存编辑失败');
  } finally {
    saving.value = false;
  }
};

// 获取所有批注数据（WPS 自带的批注）
const getAnnotations = () => {
  // WPS 的批注数据由 WPS SDK 管理，不需要我们自己维护
  return {
    textAnnotations: [],
    signatures: []
  };
};

// 保存文档
const saveDocument = async () => {
  if (useWpsEditor.value && wpsEditorRef.value) {
    return await wpsEditorRef.value.saveDocument();
  }
  return null;
};

// 监听 ossId 变化
watch(
  () => props.ossId,
  (newId) => {
    if (newId) {
      downloadFileForPreview();
    }
  },
  { immediate: true }
);

// 监听 useWpsEditor 变化
watch(useWpsEditor, () => {
  downloadFileForPreview();
});

// 暴露方法
defineExpose({
  getAnnotations,
  saveDocument
});
</script>

<style scoped lang="scss">
.annotation-editor {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
  position: relative;
}

.editor-wrapper {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
}

.editor-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  background: #fff;
  border-bottom: 1px solid #e4e7ed;
  flex-shrink: 0;
  z-index: 10;

  .file-info {
    display: flex;
    align-items: center;
    gap: 12px;

    .file-icon {
      font-size: 24px;
      color: #409eff;
    }

    .file-name {
      font-size: 16px;
      font-weight: 500;
      color: #303133;
      max-width: 300px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

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

.editor-content {
  position: absolute;
  top: 68px;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
}

.wps-wrapper,
.preview-wrapper,
.pdf-wrapper {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: auto;

  // 自定义滚动条样式
  &::-webkit-scrollbar {
    width: 8px;
    height: 8px;
  }

  &::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
  }

  &::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 4px;

    &:hover {
      background: #a8a8a8;
    }
  }
}

.wps-wrapper {
  :deep(.wps-editor-container) {
    height: 100%;

    .wps-container {
      height: 100%;
    }
  }
}

.preview-wrapper {
  padding: 20px;

  :deep(.docx-wrapper),
  :deep(.excel-wrapper) {
    height: auto !important;
    max-height: none !important;
  }
}

.pdf-wrapper {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;

  .pdf-viewer {
    width: 100%;
    height: 100%;
    overflow: auto;

    // 自定义滚动条样式
    &::-webkit-scrollbar {
      width: 8px;
      height: 8px;
    }

    &::-webkit-scrollbar-track {
      background: #f1f1f1;
      border-radius: 4px;
    }

    &::-webkit-scrollbar-thumb {
      background: #c1c1c1;
      border-radius: 4px;

      &:hover {
        background: #a8a8a8;
      }
    }

    :deep(canvas) {
      display: block;
      margin: 20px auto;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    }
  }
}

.signature-item,
.annotation-item {
  position: absolute;
  z-index: 10;

  .remove-btn {
    position: absolute;
    top: -10px;
    right: -10px;
    opacity: 0;
    transition: opacity 0.3s;
  }

  &:hover .remove-btn {
    opacity: 1;
  }
}

.signature-item {
  width: 100px;
  height: 50px;

  img {
    width: 100%;
    height: 100%;
    border: 2px solid #409eff;
    border-radius: 4px;
    background: rgba(64, 158, 255, 0.05);
    transition: transform 0.3s;
  }

  &:hover img {
    transform: scale(1.05);
  }
}

.annotation-item {
  min-width: 200px;
  max-width: 300px;
  background: #fff;
  border: 2px solid #ffc107;
  border-radius: 8px;
  padding: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);

  .annotation-display {
    cursor: pointer;

    .annotation-text {
      color: #303133;
      font-size: 14px;
      line-height: 1.6;
      word-break: break-all;
      min-height: 40px;
    }
  }

  .annotation-actions {
    display: flex;
    gap: 8px;
    margin-top: 8px;
    justify-content: flex-end;
  }
}

.loading-state {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  z-index: 100;

  .el-icon {
    font-size: 48px;
    color: #409eff;
    margin-bottom: 16px;
  }

  p {
    font-size: 14px;
    color: #909399;
  }
}

:deep(.el-result),
:deep(.el-empty) {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100%;
}

.settings-tabs {
  :deep(.el-tabs__content) {
    padding: 0;
  }
}

.settings-section {
  padding: 20px 0;
}

.mode-radio-group {
  display: flex;
  flex-direction: column;
  gap: 12px;

  :deep(.el-radio) {
    margin: 0;
    padding: 16px;

    &.is-bordered {
      border-radius: 8px;
    }
  }

  .radio-label {
    .label-title {
      font-size: 14px;
      font-weight: 500;
      color: #303133;
      margin-bottom: 4px;
    }

    .label-desc {
      font-size: 12px;
      color: #909399;
    }
  }
}

.setting-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 0;

  .item-label {
    display: flex;
    flex-direction: column;
    gap: 4px;

    > span:first-child {
      font-size: 14px;
      color: #303133;
    }

    .item-desc {
      font-size: 12px;
      color: #909399;
    }
  }
}

.watermark-input {
  margin-top: 12px;
  padding-left: 20px;
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-divider) {
  margin: 12px 0;
}
</style>
