<template>
  <div class="edit-task" :class="[type && type !== 'personal' ? 'edit-task_template' : '']">
    <MenuPage
      v-if="!type || type === 'personal'"
      :only-key="type ? '/personal_workbench/template_list' : '/personal_workbench/edit_task'"
    />

    <div class="edit-task__header" :style="{ top: type && type !== 'personal' ? '0' : '' }">
      <div class="menu-container">
        <span class="name">{{ courseware_info.book_name }}</span>
      </div>
      <div class="courseware">
        <span class="name-path">{{ courseware_info.name_path }}</span>
        <div class="switch">
          <span :class="['link', { active: isEdit }]" @click="toggleEditMode(true)">内容编辑</span>
          <span :class="['link', { active: !isEdit }]" @click="toggleEditMode(false)">位置调整</span>
        </div>
        <div class="operator">
          <el-switch
            v-show="!isEdit"
            v-model="chinese"
            active-value="zh-Hant"
            inactive-value="zh-Hans"
            active-color="#ff4949"
            inactive-color="#165dff"
            active-text="繁"
            inactive-text="简"
          />
          <span v-if="!isEdit" class="link">
            <el-select v-model="lang" placeholder="请选择语言" size="mini" class="lang-select">
              <el-option v-for="item in langList" :key="item.type" :label="item.name" :value="item.type" />
            </el-select>
          </span>
          <template v-if="!type">
            <span class="link" @click="copyFormat">复制格式</span>
            <span :class="['link', { disabled: !format.isCopy }]" @click="pasteFormat">粘贴格式</span>
            <span class="link" @click="pasteComponent('bottom')">粘贴组件</span>
            <el-popover placement="bottom" width="100" trigger="click">
              <el-link type="primary" @click="pasteComponent('bottom')">粘贴到下方</el-link>
              <el-link type="primary" @click="pasteComponent('top')">粘贴到上方</el-link>
              <el-link type="primary" @click="pasteComponent('left')">粘贴到左侧</el-link>
              <el-link type="primary" @click="pasteComponent('right')">粘贴到右侧</el-link>
              <i slot="reference" class="link el-icon-caret-bottom" :style="{ margin: '0 -10px 0 -4px' }"></i>
            </el-popover>
            <span class="link"></span>
            <span class="link" @click="useTemplate">使用模板</span>
          </template>
          <span class="link" @click="showSetBackground">背景图</span>
          <span class="link" @click="saveCoursewareContent('quit')">退出编辑</span>
          <span class="link" @click="saveCoursewareContent">保存</span>
          <span v-if="isEdit && !type" class="link" @click="showFullTextSettings">全文设置</span>
          <span v-if="type" class="link" @click="goBackTemplateList">返回模板列表</span>
          <span v-else class="link" @click="goBackBookList">返回教材列表</span>
        </div>
      </div>
    </div>

    <CreatePage ref="create" class="edit-task__content" @goBackPreview="goBackPreview" />
    <UseTemplate :visible.sync="visibleTemplate" @useTemplate="handleUseTemplate" />
  </div>
</template>

<script>
import CreatePage from '@/views/book/courseware/create/index.vue';
import MenuPage from '@/views/personal_workbench/common/menu.vue';
import UseTemplate from './UseTemplate.vue';

import tinymce from 'tinymce';
import * as OpenCC from 'opencc-js';
import { GetBookCoursewareInfo, GetMyBookCoursewareTaskList } from '@/api/project';
import { GetLanguageTypeList } from '@/api/book';

export default {
  name: 'EditTaskPage',
  components: {
    CreatePage,
    MenuPage,
    UseTemplate,
  },
  provide() {
    return {
      getLang: () => this.lang,
      getChinese: () => this.chinese,
      getLangList: () => this.langList,
      convertText: this.convertText,
      getTemporaryCoursewareID: () => this.temporaryCoursewareID,
    };
  },
  data() {
    return {
      id: this.$route.params.courseware_id,
      project_id: this.$route.query.project_id,
      type: this.$route.query.template_type,
      courseware_info: {},
      courseware_list: [],
      isEdit: true, // 是否编辑状态
      opencc: OpenCC.Converter({ from: 'cn', to: 'tw' }),
      langList: [],
      lang: 'ZH',
      chinese: 'zh-Hans',
      visibleTemplate: false,
      temporaryCoursewareID: '',
      format: {
        isCopy: false, // 是否已复制格式
        font_size: 12, // 字体大小
        font_family: 'Arial', // 字体
        weight: 400, // 字体粗细
        color: '#000000', // 文字颜色
        text_decoration: 'none', // 装饰线样式
        font_style: 'normal', // 字体样式
      },
    };
  },
  created() {
    this.getBookCoursewareInfo();
    this.getMyBookCoursewareTaskList();
  },
  mounted() {
    this.$nextTick(() => {
      this.$watch(
        () => this.$refs.create.isEdit,
        (newVal) => {
          this.isEdit = newVal;
        },
        { immediate: true },
      );
    });
  },
  methods: {
    // 复制格式
    copyFormat() {
      const selection = tinymce.activeEditor.selection.getNode();
      let content = tinymce.activeEditor.selection.getContent({ format: 'text' });
      if (!content || content.trim() === '') {
        this.$message.warning('请先选中需要复制格式的文本');
        return;
      }
      // 向下找找到第一个字的父节点，获取样式
      let node = selection;

      // 如果选中了文本节点，使用它的父元素；如果选中了元素，查找第一个非空文本子节点并使用它的父元素，
      // 以保证获取到应用样式的元素而不是直接的文本节点，避免丢失样式
      if (node && node.nodeType === 3) {
        node = node.parentElement || node.parentNode;
      } else if (node && node.nodeType === 1) {
        const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT, {
          acceptNode(n) {
            return n.nodeValue && n.nodeValue.trim() ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
          },
        });
        const textNode = walker.nextNode();
        if (textNode && textNode.parentElement) {
          node = textNode.parentElement;
        }
      }
      const style = window.getComputedStyle(node);

      // 将字体大小转为 pt
      const pxSize = style.fontSize ? parseFloat(style.fontSize) : 12;
      // px -> pt (1pt = 1.3333px => pt = px * 0.75)
      this.format.font_size = Math.round(pxSize * 0.75);
      this.format.font_family = style.fontFamily || 'Arial';
      this.format.weight = style.fontWeight ? parseInt(style.fontWeight) : 400;
      this.format.color = style.color || '#000000';
      this.format.text_decoration = style.textDecoration || 'none';
      this.format.font_style = style.fontStyle || 'normal';
      this.format.isCopy = true;
    },
    // 粘贴格式
    pasteFormat() {
      if (!this.format.isCopy) {
        return;
      }
      const activeEditor = tinymce.activeEditor;
      // 格式刷到tinymce 选中的文字上
      activeEditor.formatter.register('customFormat', {
        inline: 'span',
        styles: {
          'font-size': `${this.format.font_size}pt`,
          'font-family': this.format.font_family,
          'font-weight': this.format.weight,
          color: this.format.color,
          'text-decoration': this.format.text_decoration,
          'font-style': this.format.font_style,
        },
      });
      activeEditor.formatter.apply('customFormat');
    },
    /**
     * @description 粘贴组件
     */
    pasteComponent(position = 'bottom') {
      this.$refs.create.pasteComponent(position);
    },
    /**
     * 得到教材课件信息
     */
    getBookCoursewareInfo() {
      GetBookCoursewareInfo({ id: this.id }).then(({ courseware_info }) => {
        this.courseware_info = courseware_info;
        this.getLangList();
      });
    },
    goBackBookList() {
      this.$router.push({ path: '/personal_workbench/edit_task', query: { book_id: this.courseware_info.book_id } });
    },
    showSetBackground() {
      this.$refs.create.showSetBackground();
    },
    toggleEditMode(isEdit) {
      if (this.isEdit !== isEdit) {
        this.saveCoursewareContent('edit');
      }
    },
    saveCoursewareContent(type = '') {
      this.temporaryCoursewareID = '';
      this.$refs.create.saveCoursewareContent(type);
    },
    showFullTextSettings() {
      this.$refs.create.showFullTextSettings();
    },
    goBackPreview() {
      /* eslint-disable */ console.log(...oo_oo(`2987550641_136_6_136_27_4`, 'tuichu'));
      if (this.$route.query.template_type) {
        this.$router.push({
          path: `/personal_workbench/template_list/preview/${this.id}`,
          query: { template_type: this.$route.query.template_type },
        });
      } else {
        this.$router.push({
          path: `/personal_workbench/edit_task/preview/${this.id}`,
          query: { project_id: this.project_id },
        });
      }
    },
    getLangList() {
      GetLanguageTypeList({ book_id: this.courseware_info.book_id, is_contain_zh: 'true' }).then(
        ({ language_type_list }) => {
          this.langList = language_type_list;
        },
      );
    },
    /**
     * 得到我的教材课件任务列表
     */
    getMyBookCoursewareTaskList() {
      GetMyBookCoursewareTaskList({ project_id: this.project_id }).then(({ courseware_list }) => {
        this.courseware_list = courseware_list;
      });
    },
    /**
     * 文本转换
     * @param {string} text - 要转换的文本
     * @returns {string} - 转换后的文本
     */
    convertText(text) {
      if (this.chinese === 'zh-Hant' && this.opencc) {
        return this.opencc(text);
      }
      return text;
    },
    /**
     * 使用模板
     */
    useTemplate() {
      this.visibleTemplate = true;
    },
    /**
     * 处理使用模板事件
     * @param {Object} param
     * @param {Object} param.data - 模板数据
     * @param {Array} param.content_group_row_list - 内容分组行列表
     * @param {string} param.temporaryCoursewareID - 临时课件ID
     */
    handleUseTemplate({ data, content_group_row_list, temporaryCoursewareID }) {
      this.$refs.create.loadTemplateData_Create({ data, content_group_row_list });
      this.temporaryCoursewareID = temporaryCoursewareID;
      this.visibleTemplate = false;
    },
    goBackTemplateList() {
      if (this.type === 'personal') {
        this.$router.push({ path: '/personal_workbench/template_list' });
      } else if (this.type === 'org') {
        this.$router.push({ path: '/personal_workbench/template_list_org' });
      } else {
        this.$router.push({ path: '/personal_workbench/template_list_manager' });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@use '@/styles/mixin.scss' as *;

.edit-task {
  height: calc(100% - 52px);
  min-height: calc(100% - 52px) !important;

  @include page-content(true);

  &__header {
    display: flex;
    align-items: center;
    border-top: $border;
    border-bottom: $border;

    .menu {
      .name {
        max-width: 260px;
        font-size: 16px;
        font-weight: bold;
      }
    }

    .courseware {
      .name-path {
        font-size: 14px;
      }

      .switch {
        padding: 4px 16px 4px 0;
        margin-right: 300px;
        border-right: $border;

        .link {
          padding: 4px;
          border-radius: 4px;

          &.active {
            background-color: $main-active-color;
          }
        }
      }

      .operator {
        .lang-select {
          :deep .el-input {
            width: 100px;
          }

          :deep .el-input__inner {
            height: 24px;
            line-height: 24px;
            background-color: #fff;
          }

          :deep .el-input__icon {
            line-height: 24px;
          }
        }
      }
    }
  }

  &__content {
    flex: 1;
    flex-direction: row !important;
  }

  &_template {
    main {
      min-height: 100%;
    }
  }
}
</style>

<style lang="scss">
.el-popover.el-popper {
  min-width: 100px;
}
</style>
