<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';

import { Page } from '@vben/common-ui';

import { QuillEditor } from '@vueup/vue-quill';
import {
  Button,
  Card,
  Input,
  message,
  Radio,
  RadioGroup,
  Select,
  SelectOption,
  Textarea,
} from 'ant-design-vue';

import { uploadFile } from '#/api/core/upload';
import { getUserOptionApi, sendNoticeApi } from '#/views/notice/api';

// Import Markdown editor (using a popular Vue 3 Markdown editor)
import { MdEditor } from 'md-editor-v3';

import 'md-editor-v3/lib/style.css';

// eslint-disable-next-line n/no-extraneous-import
import '@vueup/vue-quill/dist/vue-quill.snow.css';

// 基础数据定义
const title = ref('');
const detail = ref('总结本周任务，计划下周任务');
const content = ref('');
const markdownContent = ref(''); // For 1 content
const type = ref(2);
const userIds = ref([]);
const editorMode = ref(1); // 0 or 1
const typeOption = ref([
  {
    label: '周报',
    value: 2,
  },
]);

// 用户选项数据
const userOption = ref([]);

// 创建对QuillEditor的引用，用于后续获取Quill实例
const quillEditorRef = ref(null);

// 获取用户选项数据的函数
const getUserOption = () => {
  getUserOptionApi().then((res) => {
    userOption.value = res;
  });
};
getUserOption();

// Watch for editor mode changes to convert content between formats
watch(editorMode, (newMode, oldMode) => {
  if (newMode === oldMode) return;

  if (newMode === 1 && oldMode === 0) {
    // Convert HTML to Markdown (simplified conversion)
    // In a real app, you would use a proper HTML-to-Markdown converter library
    try {
      // This is a placeholder - you should use a proper library like turndown
      const tempDiv = document.createElement('div');
      tempDiv.innerHTML = content.value;
      markdownContent.value = tempDiv.textContent || '';
      message.info('已切换到Markdown编辑模式');
    } catch (error) {
      console.error('转换HTML到Markdown失败:', error);
    }
  } else if (newMode === 0 && oldMode === 1) {
    // Convert Markdown to HTML (simplified conversion)
    // In a real app, you would use a proper Markdown-to-HTML converter library
    try {
      // This is a placeholder - you should use a proper library like marked
      content.value = markdownContent.value;
      message.info('已切换到富文本编辑模式');
    } catch (error) {
      console.error('转换Markdown到HTML失败:', error);
    }
  }
});

// 发送周报的函数
const send = () => {
  // Use the appropriate content based on editor mode
  const finalContent =
    editorMode.value === 1 ? markdownContent.value : content.value;

  sendNoticeApi({
    title: title.value,
    type: type.value,
    edit_type: editorMode.value,
    detail: detail.value,
    content: finalContent,
    content_type: editorMode.value, // Add content type to API
    user_ids: userIds.value,
  }).then(() => {
    detail.value = '';
    content.value = '';
    markdownContent.value = '';
    userIds.value = [];
    title.value = '';
    // 清除富文本编辑器内容
    if (quillEditorRef.value?.getQuill()) {
      quillEditorRef.value.getQuill().setContents([]);
    }
    message.success('发送成功');
  });
};
const isUpload = ref(false);

// 富文本编辑器配置选项
const editorOptions = {
  theme: 'snow',
  modules: {
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'],
      ['blockquote', 'code-block'],
      [{ header: 1 }, { header: 2 }],
      [{ list: 'ordered' }, { list: 'bullet' }],
      [{ script: 'sub' }, { script: 'super' }],
      [{ indent: '-1' }, { indent: '+1' }],
      [{ direction: 'rtl' }],
      [{ size: ['small', false, 'large', 'huge'] }],
      [{ header: [1, 2, 3, 4, 5, 6, false] }],
      [{ color: [] }, { background: [] }],
      [{ font: [] }],
      [{ align: [] }],
      ['clean'],
      ['link', 'image', 'video'],
    ],
  },
  placeholder: '请输入周报内容',
};

/**
 * 图片上传函数
 * @param {File} file - 要上传的图片文件
 * @returns {Promise<string>} - 返回上传后的图片URL
 */
const uploadImage = async (file: File): Promise<string> => {
  try {
    // 创建FormData对象，用于发送文件数据
    const formData = new FormData();
    formData.append('file', file);

    // 显示上传中的提示
    message.loading({ content: '图片上传中...', key: 'imageUpload' });

    return uploadFile({
      file,
    }).then((data: any) => {
      message.success({
        content: '图片上传成功',
        key: 'imageUpload',
        duration: 2,
      });
      isUpload.value = false;
      return data.url;
    });
  } catch (error) {
    // 处理上传错误
    console.error('图片上传错误:', error);
    message.error({ content: '图片上传失败', key: 'imageUpload', duration: 2 });
    return '';
  }
};

/**
 * 从剪贴板数据中提取图片文件
 * @param {ClipboardEvent} event - 剪贴板事件
 * @returns {File|null} - 返回图片文件或null
 */
const getImageFromClipboard = (event: ClipboardEvent): File | null => {
  const clipboardData = event.clipboardData;
  if (!clipboardData) return null;

  // 遍历剪贴板中的所有项目
  const items = clipboardData.items;
  for (const item of items) {
    // 检查是否是图片类型
    if (item.type.includes('image')) {
      return item.getAsFile();
    }
  }

  return null;
};

/**
 * 在编辑器中插入图片
 * @param {any} quill - Quill编辑器实例
 * @param {string} imageUrl - 图片URL
 */
const insertImageToEditor = (quill: any, imageUrl: string): void => {
  if (!quill) return;

  // 获取当前光标位置
  const range = quill.getSelection();

  if (range) {
    // 在光标位置插入图片
    quill.insertEmbed(range.index, 'image', imageUrl);
    // 将光标移动到图片后面
    quill.setSelection(range.index + 1);
  } else {
    // 如果没有选择范围，则在文档末尾插入
    const length = quill.getLength();
    quill.insertEmbed(length - 1, 'image', imageUrl);
    quill.setSelection(length);
  }
};

// 处理Markdown编辑器的图片上传
const handleMdImageUpload = async (
  files: FileList,
  callback: (urls: string[]) => void,
) => {
  if (!files || files.length === 0) return;

  const urls = [];
  for (const file of files) {
    if (isUpload.value === true) continue;

    isUpload.value = true;
    const url = await uploadImage(file);
    if (url) urls.push(url);
    isUpload.value = false;
  }

  callback(urls);
};

// 组件挂载后设置剪贴板事件监听
onMounted(() => {
  // 等待DOM更新后获取编辑器元素
  setTimeout(() => {
    // 获取Quill编辑器实例
    const quill = quillEditorRef.value?.getQuill();

    if (!quill) {
      console.error('无法获取Quill编辑器实例');
      return;
    }

    // 为编辑器添加粘贴事件监听器
    const editorElement = document.querySelector('.ql-editor');
    if (editorElement) {
      editorElement.addEventListener('paste', async (event) => {
        // 从剪贴板获取图片
        const imageFile = getImageFromClipboard(event as ClipboardEvent);

        if (imageFile) {
          // 阻止默认粘贴行为，以便我们可以自定义处理
          event.preventDefault();

          if (isUpload.value === true) {
            return;
          }
          isUpload.value = true;

          // 上传图片到服务器
          const imageUrl = await uploadImage(imageFile);

          // 如果成功获取到图片URL，则将图片插入到编辑器中
          if (imageUrl) {
            insertImageToEditor(quill, imageUrl);
          }
        }
        // 如果不是图片，则让默认粘贴行为继续
      });

      console.log('已设置编辑器粘贴事件监听器');
    } else {
      console.error('无法找到编辑器元素');
    }
  }, 500); // 给予足够的时间让编辑器渲染完成
});

/**
 * 直接处理编辑器的粘贴事件
 * 这是一个备用方法，通过Quill的clipboard模块直接处理粘贴事件
 */
const setupQuillPasteHandler = () => {
  // 确保编辑器已经挂载
  if (!quillEditorRef.value) return;

  const quill = quillEditorRef.value.getQuill();
  if (!quill) return;

  // 获取Quill的clipboard模块
  const clipboard = quill.getModule('clipboard');

  // 保存原始的粘贴处理函数
  const originalMatchers = clipboard.matchers;

  // 重写粘贴处理函数
  clipboard.addMatcher('img', (node: any, delta: any) => {
    // 这里可以处理HTML中的img标签
    // 但对于直接粘贴的图片文件，这个方法不会被触发
    return delta;
  });

  // 监听编辑器的paste事件
  quill.root.addEventListener('paste', async (e: ClipboardEvent) => {
    const imageFile = getImageFromClipboard(e);

    if (imageFile) {
      e.preventDefault();

      if (isUpload.value === true) {
        return;
      }
      isUpload.value = true;
      const imageUrl = await uploadImage(imageFile);

      if (imageUrl) {
        insertImageToEditor(quill, imageUrl);
      }
    }
  });
};
</script>

<template>
  <Page title="通知群发">
    <Card class="w-1/2" style="margin: 0 auto" title="发送周报">
      <!-- 周报标题输入框 -->
      <Input v-model:value="title" placeholder="请输入周报标题" />

      <!-- 周报类型选择器 -->
      <Select
        v-model:value="type"
        class="mt-5 w-full"
        placeholder="请选择周报类型"
        disabled
      >
        <template v-for="item in typeOption" :key="item.value">
          <SelectOption :value="item.value">{{ item.label }}</SelectOption>
        </template>
      </Select>

      <!-- 用户选择器，仅在类型为2时显示 -->
      <Select
        v-if="type === 2"
        v-model:value="userIds"
        class="mt-5 w-full"
        mode="multiple"
        placeholder="请选择接受周报的用户"
      >
        <template v-for="item in userOption" :key="item.value">
          <SelectOption :value="item.id">{{ item.nick_name }}</SelectOption>
        </template>
      </Select>

      <!-- 周报简介输入框 -->
      <Textarea
        v-model:value="detail"
        class="mt-5"
        placeholder="请输入周报简介"
      />

      <!-- 编辑器类型选择 -->
      <div class="mt-5">
        <RadioGroup v-model:value="editorMode" button-style="solid">
          <Radio :value="0">富文本编辑器</Radio>
          <Radio :value="1">Markdown编辑器</Radio>
        </RadioGroup>
      </div>

      <!-- 富文本编辑器 - 仅在富文本模式下显示 -->
      <div v-if="editorMode === 0" class="mt-5">
        <QuillEditor
          ref="quillEditorRef"
          v-model:content="content"
          :options="editorOptions"
          class="editor-container"
          content-type="html"
          theme="snow"
          @ready="setupQuillPasteHandler"
        />
      </div>

      <!-- Markdown编辑器 - 仅在Markdown模式下显示 -->
      <div v-if="editorMode === 1" class="mt-5">
<!--        <MdEditor-->
<!--          v-model="markdownContent"-->
<!--          :theme="prefersDarkMode ? 'dark' : 'light'"-->
<!--          :toolbars-exclude="['github']"-->
<!--          class="md-editor-container"-->
<!--          editor-id="notice-md-editor"-->
<!--          preview-only-->
<!--          @on-upload-img="handleMdImageUpload"-->
<!--        />-->
        <MdEditor
          v-model="markdownContent"
          :toolbars-exclude="['github']"
          class="md-editor-container"
          editor-id="notice-md-editor"
          preview-only
          theme="dark"
          @on-upload-img="handleMdImageUpload"
        />
      </div>

      <!-- 发送按钮 -->
      <Button class="mt-5 w-full" type="primary" @click="send">发送</Button>
    </Card>
  </Page>
</template>

<style scoped>
/* 编辑器容器样式 */
.editor-container {
  height: 250px;
  margin-bottom: 40px;
  /* 确保编辑器有足够的空间显示工具栏和内容区域 */
}

/* Markdown编辑器样式 */
.md-editor-container {
  min-height: 400px;
  margin-bottom: 40px;
}

/* 可以添加额外的样式来自定义编辑器外观 */
:deep(.ql-editor) {
  min-height: 200px;
  font-size: 14px;
  line-height: 1.6;
}

/* 确保图片在编辑器中显示正常 */
:deep(.ql-editor img) {
  max-width: 100%;
  height: auto;
}

/* 自定义 Markdown 编辑器样式 */
:deep(.md-editor) {
  border-radius: 4px;
}

:deep(.md-editor-dark) {
  --md-bk-color: #1e1e1e;
  --md-border-color: #333;
}
</style>
