<template>
  <div class="wps-editor-container">
    <div v-if="loading" class="loading-container">
      <el-icon class="is-loading"><Loading /></el-icon>
      <span>正在加载 WPS 编辑器...</span>
    </div>
    <div v-if="error" class="error-container">
      <el-alert type="error" title="加载失败" :closable="false">
        <div style="white-space: pre-line; line-height: 1.6">{{ error }}</div>
      </el-alert>
    </div>
    <div ref="wpsContainerRef" class="wps-container"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import { Loading } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

interface Props {
  fileUrl: string;
  fileName?: string;
  fileType?: 'doc' | 'docx' | 'xls' | 'xlsx' | 'ppt' | 'pptx' | 'pdf';
  mode?: 'simple' | 'normal';
  userId?: string;
  userName?: string;
  enableComment?: boolean;
  enableRevision?: boolean;
  enableWatermark?: boolean;
  watermarkText?: string;
  enableDownload?: boolean;
  enablePrint?: boolean;
  enableCopy?: boolean;
  enableSave?: boolean;
  enableShare?: boolean;
  enableHistory?: boolean;
  readOnly?: boolean;
}

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

const props = withDefaults(defineProps<Props>(), {
  mode: 'normal',
  fileName: '未命名文档',
  userId: 'user_' + Date.now(),
  userName: '当前用户',
  enableComment: true,
  enableRevision: true,
  enableWatermark: false,
  watermarkText: '',
  enableDownload: true,
  enablePrint: true,
  enableCopy: true,
  enableSave: true,
  enableShare: false,
  enableHistory: false,
  readOnly: false
});

const emit = defineEmits<Emits>();

const wpsContainerRef = ref<HTMLDivElement>();
const loading = ref(true);
const error = ref('');
let wpsInstance: any = null;

// WPS 配置
const WPS_APP_ID = 'SX20251229FLIAPDAPP';

// 初始化 WPS 编辑器（符合官方文档）
const initWpsEditor = async () => {
  if (!wpsContainerRef.value || !props.fileUrl) {
    error.value = '缺少必要参数';
    loading.value = false;
    emit('error', error.value);
    return;
  }

  try {
    loading.value = true;
    error.value = '';

    // 检查 WPS SDK 是否已加载
    if (!(window as any).WebOfficeSDK) {
      const errorMsg =
        'WPS SDK 未加载。请按以下步骤操作：\n\n1. 从 WPS 官网下载 JSSDK\n2. 将 SDK 文件放到 public 目录\n3. 在 index.html 中引入 SDK 脚本\n\n或使用 CDN（需要网络连接）';
      error.value = errorMsg;
      loading.value = false;
      emit('error', errorMsg);
      return;
    }

    const WebOfficeSDK = (window as any).WebOfficeSDK;

    // 根据文件类型确定 officeType
    let officeType = WebOfficeSDK.OfficeType.Writer;
    if (props.fileType === 'xlsx' || props.fileType === 'xls') {
      officeType = WebOfficeSDK.OfficeType.Spreadsheet;
    } else if (props.fileType === 'pptx' || props.fileType === 'ppt') {
      officeType = WebOfficeSDK.OfficeType.Presentation;
    } else if (props.fileType === 'pdf') {
      officeType = WebOfficeSDK.OfficeType.Pdf;
    }

    // 生成唯一的文件ID
    const fileId = `${props.userId}_${Date.now()}`;

    // 构建初始化配置（符合官方文档）
    const config: any = {
      // 必需参数
      appId: WPS_APP_ID,
      officeType: officeType,
      fileId: fileId,

      // 挂载节点
      mount: wpsContainerRef.value,

      // 自定义参数（会传递到回调接口）
      customArgs: {
        fileName: props.fileName,
        fileUrl: props.fileUrl,
        userId: props.userId,
        userName: props.userName,
        readOnly: props.readOnly,
        enableComment: props.enableComment,
        enableRevision: props.enableRevision
      }
    };

    console.log('[WPS] 初始化配置:', config);

    // 初始化 WebOffice
    wpsInstance = await WebOfficeSDK.init(config);

    loading.value = false;
    emit('ready');
    console.log('[WPS] 编辑器初始化成功');
  } catch (err: any) {
    console.error('[WPS] 初始化失败:', err);
    error.value = err.message || '初始化失败';
    loading.value = false;
    emit('error', error.value);
  }
};

// 保存文档
const saveDocument = async () => {
  if (!wpsInstance) {
    ElMessage.warning('编辑器未初始化');
    return null;
  }

  try {
    console.log('[WPS] 开始保存文档');
    // 调用 WPS 的保存方法
    const result = await wpsInstance.save();
    console.log('[WPS] 保存成功:', result);
    ElMessage.success('保存成功');
    emit('save', result);
    return result;
  } catch (err: any) {
    console.error('[WPS] 保存失败:', err);
    ElMessage.error('保存失败');
    throw err;
  }
};

// 销毁编辑器
const destroyEditor = () => {
  if (wpsInstance) {
    try {
      if (wpsInstance.destroy) {
        wpsInstance.destroy();
      }
      wpsInstance = null;
      console.log('[WPS] 编辑器已销毁');
    } catch (err) {
      console.error('[WPS] 销毁编辑器失败:', err);
    }
  }
};

// 监听文件 URL 变化
watch(
  () => props.fileUrl,
  (newUrl) => {
    if (newUrl) {
      destroyEditor();
      initWpsEditor();
    }
  }
);

onMounted(() => {
  // 等待 WPS SDK 加载完成
  let checkCount = 0;
  const maxChecks = 100; // 10秒超时（100 * 100ms）

  const checkWpsSDK = setInterval(() => {
    checkCount++;

    if ((window as any).WebOfficeSDK) {
      clearInterval(checkWpsSDK);
      console.log('[WPS] SDK 加载成功');
      if (props.fileUrl) {
        initWpsEditor();
      }
    } else if (checkCount >= maxChecks) {
      clearInterval(checkWpsSDK);
      console.error('[WPS] SDK 加载超时');
      error.value = 'WPS SDK 加载超时。请检查：\n1. 网络连接是否正常\n2. index.html 中的 SDK 脚本是否正确引入\n3. SDK CDN 地址是否可访问';
      loading.value = false;
      emit('error', error.value);
    }
  }, 100);
});

onBeforeUnmount(() => {
  destroyEditor();
});

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

<style scoped lang="scss">
.wps-editor-container {
  width: 100%;
  height: 100%;
  position: relative;

  .loading-container,
  .error-container {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 10;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;

    .el-icon {
      font-size: 32px;
      color: #409eff;
    }
  }

  .wps-container {
    width: 100%;
    height: 100%;
  }
}
</style>
