<template>
  <div class="tinymce-editor fade-in">
    <!-- 页面标题 -->
    <div class="editor-header">
      <h1 class="editor-title">{{ articleId ? "编辑文章" : "创建新文章" }}</h1>
      <p class="editor-subtitle">
        {{ articleId ? "完善你的知识分享" : "分享你的知识、经验和创意" }}
      </p>
    </div>

    <!-- 文章标题输入 -->
    <a-input
      v-model="ArticleTitle"
      placeholder="请输入文章标题 (5-50字)"
      class="article-title-input"
      :maxLength="50"
      :allowClear="true"
    />

    <!-- 文章信息 -->
    <div class="article-info-card fade-in-delay-1">
      <div class="info-title">
        <a-icon type="info-circle" />
        <span>文章信息</span>
      </div>

      <div class="form-item-container">
        <!-- 选择比赛 -->
        <a-form-item label="选择相关比赛">
          <a-select
            v-model="competitionId"
            :options="grades"
            allowClear
            placeholder="请选择相关比赛"
            :showSearch="true"
            :filterOption="filterOption"
          >
            <template slot="suffixIcon">
              <a-icon type="trophy" />
            </template>
          </a-select>
        </a-form-item>

        <!-- 选择文章类型 -->
        <a-form-item label="文章类型">
          <a-select
            v-model="articleType"
            :options="message"
            allowClear
            placeholder="请选择文章类型"
          >
            <template slot="suffixIcon">
              <a-icon type="tags" />
            </template>
          </a-select>
        </a-form-item>
      </div>
    </div>

    <!-- 编辑器容器 -->
    <div class="tinymce-editor">
      <div class="editor-container">
        <Editor
          :id="tinymceId"
          :init="init"
          :disabled="disabled"
          v-model="myValue"
          @onClick="onClick"
        ></Editor>
      </div>

      <div class="editor-footer">
        <div class="button-group">
          <a-button type="primary" class="publish-btn" @click="SendTinymce">
            <a-icon :type="articleId ? 'edit' : 'plus'" />
            {{ articleId ? "保存修改" : "发布文章" }}
          </a-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { message } from "@/utils/const";
import {
  createArticle,
  AllCompetition,
  SendSMS,
  SendEmail,
  AllArticle,
  UpArtile,
} from "@/api";
import tinymce from "tinymce/tinymce"; //tinymce默认hidden，不引入不显示
import Editor from "@tinymce/tinymce-vue"; //编辑器引入
import "tinymce/themes/silver/theme"; //编辑器主题
import "tinymce/icons/default"; //引入编辑器图标icon，不引入则不显示对应图标
// 引入编辑器插件（基本免费插件都在这儿了）
import "tinymce/plugins/advlist"; //高级列表
import "tinymce/plugins/autolink"; //自动链接
import "tinymce/plugins/link"; //超链接
import "tinymce/plugins/image"; //插入编辑图片
import "tinymce/plugins/lists"; //列表插件
import "tinymce/plugins/charmap"; //特殊字符
import "tinymce/plugins/media"; //插入编辑媒体
import "tinymce/plugins/wordcount"; // 字数统计
//   import Cookies from "js-cookie";
const fonts = [
  "宋体=宋体",
  "微软雅黑=微软雅黑",
  "新宋体=新宋体",
  "黑体=黑体",
  "楷体=楷体",
  "隶书=隶书",
  "Courier New=courier new,courier",
  "AkrutiKndPadmini=Akpdmi-n",
  "Andale Mono=andale mono,times",
  "Arial=arial,helvetica,sans-serif",
  "Arial Black=arial black,avant garde",
  "Book Antiqua=book antiqua,palatino",
  "Comic Sans MS=comic sans ms,sans-serif",
  "Courier New=courier new,courier",
  "Georgia=georgia,palatino",
  "Helvetica=helvetica",
  "Impact=impact,chicago",
  "Symbol=symbol",
  "Tahoma=tahoma,arial,helvetica,sans-serif",
  "Terminal=terminal,monaco",
  "Times New Roman=times new roman,times",
  "Trebuchet MS=trebuchet ms,geneva",
  "Verdana=verdana,geneva",
  "Webdings=webdings",
  "Wingdings=wingdings,zapf dingbats",
];
export default {
  components: {
    Editor,
  },
  props: {
    //内容
    value: {
      type: String,
      default: "",
    },
    //是否禁用
    disabled: {
      type: Boolean,
      default: false,
    },
    // 用于区分单个tinymce
    tinymceId: {
      type: String,
      default: "tinymce",
    },
    //插件
    plugins: {
      type: [String, Array],
      default: "advlist autolink link image lists charmap  media wordcount",
    },
    //工具栏
    toolbar: {
      type: [String, Array],
      default:
        "undo redo |  formatselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | lists image media table",
    },
  },
  data() {
    return {
      message,
      //初始化配置
      grades: [],
      articleId: this.$route.query.id || "",
      myValue: this.value,
      ArticleTitle: "",
      competitionId: "",
      articleType: "",
      briefContent: "",
      init: {
        selector: "#" + this.tinymceId,
        language_url: "@/components/edit/zh_CN.js", //汉化路径是自定义的，一般放在public或static里面
        language: "zh_CN",
        skin_url: "/tinymce/skins/ui/oxide", //皮肤
        plugins: this.plugins, //插件
        //工具栏
        toolbar: this.toolbar,
        toolbar_location: "/",
        fontsize_formats:
          "12px 14px 16px 18px 20px 22px 24px 28px 32px 36px 48px 56px 72px", //字体大小
        font_formats: fonts.join(";"),
        content_style: "p {margin: 0px; border:0px ; padding: 0px}", // 设置p的行间距
        width: "100%",
        // height: 500,//高度
        placeholder: "在这里输入文字",

        branding: false, //隐藏右下角技术支持
        //图片上传
      },
      ArticleId: "",
      Article: {},
    };
  },
  watch: {
    //监听内容变化
    value(newValue) {
      this.myValue = newValue == null ? "" : newValue;
    },
    myValue(newValue) {
      if (this.triggerChange) {
        this.$emit("change", newValue);
      } else {
        this.$emit("input", newValue);
      }
    },
  },
  mounted() {
    if (this.articleId) {
      this.GetAritle();
    }
    tinymce.init({});
    // console.log(this.toolbar,'======')
    this.GetAritle();
    AllCompetition()
      .then((response) => {
        // 获取竞赛数据
        const competitions = response.data;

        // 转换数据为适合select选项的格式
        const selectOptions = competitions.map((competition) => ({
          label: competition.competitionName,
          value: competition.competitionId,
        }));
        // 将转换后的数据存储在Vue实例中，以便在模板中使用
        this.grades = selectOptions;
      })
      .catch((error) => {
        console.error(error);
      });
  },
  methods: {
    // GetAritle() {
    //   console.log(this.ArticleId);
    //   if (this.ArticleId != "" || null) {
    //     AllArticle().then((res) => {
    //       res.data.forEach((item) => {
    //         console.log(item);
    //         if (item.articleId == this.ArticleId) {
    //           console.log(item);
    //           this.competitionId = item.competitionId;
    //           (this.ArticleTitle = item.articleTitle),
    //             (this.myValue = item.articleContent),
    //             (this.articleType = item.articleType),
    //             (this.briefContent = item.briefContent);
    //         }
    //       });
    //     });
    //   }
    // },
    onClick(e) {
      this.$emit("onClick", e, tinymce);
    },
    //可以添加一些自己的自定义事件，如清空内容
    clear() {
      this.myValue = "";
    },
    GetAritle() {
      AllArticle().then((res) => {
        const article = res.data.find(
          (item) => item.articleId == this.articleId
        );
        if (article) {
          this.competitionId = article.competitionId;
          this.ArticleTitle = article.articleTitle;
          this.myValue = article.articleContent;
          this.articleType = article.articleType;
          this.briefContent = article.briefContent;
        }
      });
    },
    // 在import部分添加UpArtile

    SendTinymce() {
      const data = {
        userId: this.$store.state.user.userId,
        briefContent: this.briefContent,
        competitionId: this.competitionId,
        articleType: this.articleType,
        articleTitle: this.ArticleTitle,
        articleContent: this.myValue,
      };

      const apiCall = this.articleId
        ? UpArtile({ ...data, articleId: this.articleId })
        : createArticle(data);

      apiCall
        .then((res) => {
          if (res.code == 200) {
            this.$message.success(this.articleId ? "修改成功" : "发布成功");
            // this.articleId = res.data;

            if (this.articleType == "公告") {
              this.$modal.confirm({
                title: `确认发送短信与邮件通知用户?`,
                onOk: () => {
                  console.log("articleId", this.articleId, this.articleId);
                  let notificationData = {
                    competitionId: this.competitionId,
                    articleId: this.articleId,
                  };
                  this.$api
                    .SendEmail(notificationData)
                    .then(() => {
                      return this.$api.SendSMS(notificationData);
                    })
                    .then(() => {
                      this.$message.success("短信邮件提醒成功!");
                    })
                    .catch((e) => {
                      this.$message.error(e.msg || "发送失败!");
                      throw e;
                    });
                },
              });
            }
          } else {
            throw new Error("发布失败");
          }
        })
        .catch((error) => {
          console.error(error);
          this.$notify.error({
            title: "错误",
            message: this.articleId ? "修改失败" : "发布失败",
          });
        });
    },
  },
};
</script>
<style scoped>
/* 在线发帖页面美化样式 */

/* 整体容器样式 */
.tinymce-editor {
  /* max-width: 1200px; */
  margin: 0 auto;
  padding: 30px;
  background-color: #fff;
  border-radius: 16px;
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.08);
  position: relative;
}

/* 页面标题 */
.editor-header {
  text-align: center;
  margin-bottom: 40px;
  position: relative;
}

.editor-title {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin-bottom: 10px;
  position: relative;
  display: inline-block;
}

.editor-title::after {
  content: "";
  position: absolute;
  bottom: -10px;
  left: 50%;
  transform: translateX(-50%);
  width: 80px;
  height: 4px;
  background: linear-gradient(90deg, #3690cf, #6dc6ff);
  border-radius: 2px;
}

.editor-subtitle {
  font-size: 16px;
  color: #666;
  margin-top: 20px;
}

/* 输入框美化 */
.tinymce-editor .ant-input,
.tinymce-editor .ant-input-affix-wrapper {
  border-radius: 10px;
  border: 1px solid #e8e8e8;
  padding: 12px 16px;
  font-size: 16px;
  transition: all 0.3s;
  margin-bottom: 20px;
  box-shadow: 0 0 0 2px transparent;
}

.tinymce-editor .ant-input:hover,
.tinymce-editor .ant-input-affix-wrapper:hover {
  border-color: #3690cf;
}

.tinymce-editor .ant-input:focus,
.tinymce-editor .ant-input-affix-wrapper-focused {
  border-color: #3690cf;
  box-shadow: 0 0 0 2px rgba(54, 144, 207, 0.2);
}

/* 标题输入框特殊样式 */
.article-title-input {
  font-size: 20px !important;
  font-weight: 500;
  padding: 16px 20px !important;
  margin-bottom: 20px;
  border-radius: 12px !important;
}

.article-title-input::placeholder {
  color: #aaa;
}

/* 文章简介美化 */
.article-brief-textarea {
  border-radius: 10px;
  min-height: 80px !important;
  margin-bottom: 30px;
  background-color: #f9fafc;
}

/* 表单项美化 */
.form-item-container {
  display: flex;
  gap: 20px;
  margin-bottom: 25px;
}

.form-item-container .ant-form-item {
  flex: 1;
  margin-bottom: 0;
}

.tinymce-editor .ant-form-item-label {
  margin-bottom: 8px;
}

.tinymce-editor .ant-form-item-label > label {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  height: auto;
}

/* 下拉选择框美化 */
.tinymce-editor .ant-select {
  width: 100%;
}

.tinymce-editor .ant-select-selector {
  border-radius: 10px !important;
  padding: 8px 16px !important;
  height: auto !important;
  min-height: 48px !important;
  display: flex;
  align-items: center;
  transition: all 0.3s;
}

.tinymce-editor .ant-select-search {
  display: flex;
  align-items: center;
}

.tinymce-editor .ant-select:hover .ant-select-selector {
  border-color: #3690cf !important;
}

.tinymce-editor .ant-select-focused .ant-select-selector {
  border-color: #3690cf !important;
  box-shadow: 0 0 0 2px rgba(54, 144, 207, 0.2) !important;
}

/* 编辑器容器 */
.editor-container {
  position: relative;
  margin-bottom: 25px;
  border-radius: 12px;
  overflow: hidden;
  border: 1px solid #e8e8e8;
  transition: all 0.3s;
}

.editor-container:hover {
  border-color: #3690cf;
  box-shadow: 0 0 0 2px rgba(54, 144, 207, 0.05);
}

/* TinyMCE编辑器自定义样式 */
.tox-tinymce {
  border-radius: 12px !important;
  overflow: hidden;
  border: none !important;
}

.tox .tox-toolbar__group {
  border-radius: 6px !important;
  margin: 2px 4px !important;
  padding: 0 4px !important;
}

.tox .tox-tbtn {
  border-radius: 6px !important;
}

.tox .tox-tbtn:hover {
  background-color: rgba(54, 144, 207, 0.1) !important;
}

.tox .tox-tbtn--enabled {
  background-color: rgba(54, 144, 207, 0.2) !important;
}

/* 发布按钮容器 */
.publish-container {
  display: flex;
  justify-content: center;
  margin-top: 40px;
  position: relative;
}

/* 发布按钮 */
.publish-btn {
  min-width: 180px;
  height: 50px;
  padding: 0 30px;
  font-size: 16px;
  font-weight: 500;
  background: linear-gradient(135deg, #3690cf, #2a78b8) !important;
  border: none !important;
  border-radius: 25px !important;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8px 15px rgba(54, 144, 207, 0.3);
  transition: all 0.3s !important;
}

.publish-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 10px 20px rgba(54, 144, 207, 0.4) !important;
  background: linear-gradient(135deg, #2a78b8, #1e5c8e) !important;
}

.publish-btn .anticon {
  margin-right: 8px;
  font-size: 18px;
}

/* 文章信息卡片 */
.article-info-card {
  background-color: #f9fafc;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 25px;
  border: 1px dashed #e0e0e0;
}

.article-info-card .info-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.article-info-card .info-title .anticon {
  color: #3690cf;
  margin-right: 8px;
  font-size: 18px;
}

/* 编辑器底部状态栏 */
.tox-statusbar {
  border-top: 1px solid #eee !important;
}

/* 上传图片区域 */
.upload-box {
  border: 2px dashed #e0e0e0;
  border-radius: 12px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 25px;
}

.upload-box:hover {
  border-color: #3690cf;
  background-color: rgba(54, 144, 207, 0.05);
}

.upload-icon {
  font-size: 48px;
  color: #d0d0d0;
  margin-bottom: 10px;
  transition: all 0.3s;
}

.upload-box:hover .upload-icon {
  color: #3690cf;
}

.upload-text {
  color: #666;
  font-size: 14px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .tinymce-editor {
    padding: 20px 15px;
  }

  .form-item-container {
    flex-direction: column;
    gap: 15px;
  }

  .editor-title {
    font-size: 24px;
  }

  .publish-btn {
    width: 100%;
  }
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.fade-in {
  animation: fadeIn 0.5s ease forwards;
}

.fade-in-delay-1 {
  animation: fadeIn 0.5s ease 0.1s forwards;
  opacity: 0;
}

.fade-in-delay-2 {
  animation: fadeIn 0.5s ease 0.2s forwards;
  opacity: 0;
}

/* 字数统计提示 */
.word-count {
  position: absolute;
  right: 15px;
  bottom: 15px;
  font-size: 12px;
  color: #999;
  background: rgba(255, 255, 255, 0.9);
  padding: 4px 10px;
  border-radius: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 预览效果区域 */
.preview-container {
  margin-top: 30px;
  padding: 20px;
  border-radius: 12px;
  background-color: #f9fafc;
  border: 1px solid #eee;
}

.preview-title {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  color: #333;
  display: flex;
  align-items: center;
}

.preview-title .anticon {
  margin-right: 8px;
  color: #3690cf;
}

.preview-content {
  padding: 15px;
  background: white;
  border-radius: 8px;
  min-height: 100px;
}

/* 自定义悬停效果 */
.hover-lift {
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.hover-lift:hover {
  transform: translateY(-3px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

/* 标签选择区域 */
.tags-container {
  margin-bottom: 25px;
}

.tags-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 12px;
}

.tag-select {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag-item {
  display: inline-flex;
  align-items: center;
  padding: 6px 12px;
  background-color: #f0f2f5;
  color: #555;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.tag-item:hover {
  background-color: #e6f7ff;
  color: #3690cf;
}

.tag-item.active {
  background-color: #3690cf;
  color: white;
}

.tag-item .anticon {
  margin-right: 5px;
}

/* 文章封面上传区域 */
.cover-upload {
  margin-bottom: 25px;
}

.cover-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 12px;
}

.cover-description {
  font-size: 14px;
  color: #888;
  margin-bottom: 15px;
}

.cover-preview {
  width: 100%;
  height: 200px;
  border-radius: 12px;
  overflow: hidden;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.cover-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.cover-upload-btn {
  position: absolute;
  bottom: 15px;
  right: 15px;
  z-index: 5;
}
</style>
