<template>
  <div class="common-preview">
    <div class="common-preview__header">
      <div class="menu-container">
        <MenuPopover :id="id" :node-list="node_list" :book-name="courseware_info.book_name" @selectNode="selectNode" />
      </div>
      <div class="courseware">
        <span class="name-path">{{ courseware_info.name_path }}</span>
        <span class="flow-nodename">{{ courseware_info.cur_audit_flow_node_name }}</span>
        <slot name="middle" :courseware="courseware_info"></slot>
        <div class="operator">
          <slot name="operator" :courseware="courseware_info"></slot>
        </div>
      </div>
    </div>

    <div class="audit-content">
      <div class="main-container" ref="previewMain">
        <main :class="['preview-main', { 'no-audit': !isShowAudit }]">
          <span class="title">
            <SvgIcon icon-class="menu-2" size="24" />
            <span>{{ courseware_info.name_path }}</span>
          </span>
          <CoursewarePreview
            :data="data"
            :component-list="component_list"
            :background="background"
            :can-remark="isTrue(courseware_info.is_my_audit_task) && isTrue(courseware_info.is_can_add_audit_remark)"
            :show-remark="isShowAudit"
            :component-remark-obj="remark_list_obj"
            @computeScroll="computeScroll"
            @addRemark="addRemark"
            ref="courserware"
            v-if="courseware_info.book_name"
          />
        </main>
      </div>
      <div v-if="isShowAudit" class="remark-list">
        <h5>审校批注</h5>
        <ul v-if="remark_list.length > 0">
          <li v-for="{ id: remarkId, content, remark_person_name, remark_time } in remark_list" :key="remarkId">
            <!-- eslint-disable-next-line vue/no-v-html -->
            <p v-html="content"></p>
            <div v-if="isAudit" class="remark-bottom">
              <span>{{ remark_person_name + ':' + remark_time }}</span>
              <el-button type="text" class="delete-btn" @click="deleteRemarks(remarkId)">删除</el-button>
            </div>
          </li>
        </ul>
        <p v-else style="text-align: center">暂无批注</p>
      </div>
    </div>

    <el-dialog
      title="添加课件审校批注"
      :visible="visible"
      width="680px"
      :close-on-click-modal="false"
      class="audit-dialog"
      @close="dialogClose"
    >
      <RichText
        v-model="remark_content"
        toolbar="fontselect fontsizeselect forecolor backcolor | underline | bold italic strikethrough alignleft aligncenter alignright"
        :wordlimit-num="false"
        :height="240"
        page-from="audit"
      />
      <div slot="footer">
        <el-button @click="dialogClose">取消</el-button>
        <el-button type="primary" :loading="submit_loading" @click="addCoursewareAuditRemark(select_node)">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CoursewarePreview from '@/views/book/courseware/preview/CoursewarePreview.vue';
import MenuPopover from '@/views/personal_workbench/common/MenuPopover.vue';
import RichText from '@/components/RichText.vue';
import { isTrue } from '@/utils/common';

import {
  GetBookCoursewareInfo,
  GetProjectBaseInfo,
  GetCoursewareAuditRemarkList,
  AddCoursewareAuditRemark,
  DeleteCoursewareAuditRemarkList,
} from '@/api/project';
import { ContentGetCoursewareContent_View, ChapterGetBookChapterStructExpandList, GetBookBaseInfo } from '@/api/book';

export default {
  name: 'CommonPreview',
  components: {
    CoursewarePreview,
    MenuPopover,
    RichText,
  },
  props: {
    projectId: {
      type: String,
      required: true,
    },
    id: {
      type: String,
      default: '',
    },
    // 是否是审校页面
    isAudit: {
      type: Boolean,
      default: false,
    },
    isShowAudit: {
      type: Boolean,
      default: true,
    },
    isBook: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      select_node: this.id,
      courseware_info: {
        book_name: '',
        is_can_start_edit: 'false',
        is_can_submit_audit: 'false',
        is_can_audit_pass: 'false',
        is_can_audit_reject: 'false',
        is_can_add_audit_remark: 'false',
        is_can_finish_audit: 'false',
        is_can_request_shangjia_book: 'false',
        is_can_request_rollback_project: 'false',
        is_can_shangjia_book: 'false',
        is_can_rollback_project: 'false',
      },
      background: {
        background_image_url: '',
        background_position: {
          left: 0,
          top: 0,
        },
      },
      node_list: [],
      data: { row_list: [] },
      component_list: [],
      remark_list: [],
      remark_list_obj: {}, // 存放转为以组件为对象的数组
      visible: false,
      remark_content: '',
      submit_loading: false,
      isTrue,
      menuPosition: {
        x: -1,
        y: -1,
        componentId: 'WHOLE',
      },
    };
  },
  created() {
    if (this.id) {
      this.getBookCoursewareInfo(this.id);
      this.getCoursewareComponentContent_View(this.id);
      this.getCoursewareAuditRemarkList(this.id);
    } else {
      this.isBook ? this.getBookBaseInfo() : this.getProjectBaseInfo();
    }
    this.getBookChapterStructExpandList();
  },
  methods: {
    getProjectBaseInfo() {
      GetProjectBaseInfo({ id: this.projectId }).then(({ project_info }) => {
        this.courseware_info = { ...project_info, book_name: project_info.name };
      });
    },

    getBookBaseInfo() {
      GetBookBaseInfo({ id: this.projectId }).then(({ book_info }) => {
        this.courseware_info = { ...this.courseware_info, ...book_info, book_name: book_info.name };
      });
    },

    /**
     * 得到教材课件信息
     * @param {string} id - 课件ID
     */
    getBookCoursewareInfo(id) {
      GetBookCoursewareInfo({ id, is_contain_producer: 'true', is_contain_auditor: 'true' }).then(
        ({ courseware_info }) => {
          this.courseware_info = { ...this.courseware_info, ...courseware_info };
        },
      );
    },
    /**
     * 得到课件内容（展示内容）
     * @param {string} id - 课件ID
     */
    getCoursewareComponentContent_View(id) {
      ContentGetCoursewareContent_View({ id }).then(({ content, component_list }) => {
        if (content) {
          this.data = JSON.parse(content);
        } else {
          this.data = { row_list: [] };
        }

        if (component_list) this.component_list = component_list;
      });
    },
    /**
     * 得到教材章节结构展开列表
     */
    getBookChapterStructExpandList() {
      ChapterGetBookChapterStructExpandList({
        book_id: this.projectId,
        node_deep_mode: 0,
        is_contain_producer: 'true',
        is_contain_auditor: 'true',
      }).then(({ node_list }) => {
        this.node_list = node_list;
      });
    },
    /**
     * 选择节点
     * @param {string} nodeId - 节点ID
     */
    selectNode(nodeId) {
      this.getCoursewareComponentContent_View(nodeId);
      this.getBookCoursewareInfo(nodeId);
      this.getCoursewareAuditRemarkList(nodeId);
      this.select_node = nodeId;
    },
    // 审校批注列表
    getCoursewareAuditRemarkList(id) {
      this.remark_list = [];
      this.remark_list_obj = {};
      GetCoursewareAuditRemarkList({
        courseware_id: id,
      }).then(({ remark_list }) => {
        this.remark_list = remark_list;
        remark_list.forEach((item) => {
          // 组件的审批
          if (item.component_id !== 'WHOLE') {
            if (!this.remark_list_obj[item.component_id]) {
              this.remark_list_obj[item.component_id] = [];
            }
            this.remark_list_obj[item.component_id].push(item);
          }
        });
      });
    },
    addRemark(selectNode, x, y, componentId) {
      this.remark_content = '';
      this.visible = true;
      if (selectNode) {
        this.menuPosition = {
          x: x,
          y: y,
          componentId: componentId,
        };
      } else {
        this.menuPosition = {
          x: -1,
          y: -1,
          componentId: 'WHOLE',
        };
      }
    },
    dialogClose() {
      this.visible = false;
    },
    // 添加审校批注
    addCoursewareAuditRemark(id) {
      this.submit_loading = true;
      AddCoursewareAuditRemark({
        courseware_id: id || this.id,
        content: this.remark_content,
        component_id: this.menuPosition.componentId,
        position_x: this.menuPosition.x,
        position_y: this.menuPosition.y,
      })
        .then(() => {
          this.submit_loading = false;
          this.visible = false;
          this.getCoursewareAuditRemarkList(id || this.id);
        })
        .catch(() => {
          this.submit_loading = false;
        });
    },
    // 删除批注
    deleteRemarks(id) {
      this.$confirm('确定要删除此条批注吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          DeleteCoursewareAuditRemarkList({ id }).then(() => {
            this.getCoursewareAuditRemarkList(this.select_node ? this.select_node : this.id);
            this.$message.success('删除成功!');
          });
        })
        .catch(() => {});
    },
    // 计算previewMain滑动距离
    computeScroll() {
      this.$refs.courserware.handleResult(
        this.$refs.previewMain.scrollTop,
        this.$refs.previewMain.scrollLeft,
        this.select_node,
      );
    },
  },
};
</script>

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

.common-preview {
  &__header {
    position: sticky;
    top: 56px;
    left: 0;
    z-index: 9;
    display: flex;
    align-items: center;
    height: 40px;
    padding: 6px 4px;
    margin-bottom: 5px;
    background-color: #fff;
    border-top: $border;
    border-bottom: $border;

    > .menu-container {
      display: flex;
      justify-content: space-between;
      width: 360px;
      padding: 4px 8px;
      border-right: $border;
    }

    > .courseware {
      display: flex;
      flex-grow: 1;
      column-gap: 16px;
      align-items: center;
      justify-content: space-between;
      height: 40px;

      .name-path {
        min-width: 200px;
        height: 40px;
        padding: 4px 8px;
        font-size: 14px;
        line-height: 32px;
        border-right: $border;
      }

      .flow-nodename {
        flex: 1;
      }

      .operator {
        display: flex;
        column-gap: 8px;
        align-items: center;

        .link {
          + .link {
            margin-left: 0;

            &::before {
              margin-right: 8px;
              color: #999;
              content: '|';
            }
          }
        }
      }
    }
  }

  .main-container {
    flex: 1;
    min-width: 1110px;
    overflow: auto;
  }

  main.preview-main {
    display: flex;
    flex: 1;
    flex-direction: column;
    row-gap: 5px;
    width: 1100px;
    min-width: 1100px;
    min-height: 100%;
    padding: 5px;
    margin: 0 5px;
    background-color: #fff;
    border: 3px solid #f44444;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 10%);

    &.no-audit {
      margin: 0 auto;
    }

    .title {
      display: inline-flex;
      column-gap: 24px;
      align-items: center;
      width: 100%;
      min-width: 280px;
      height: 64px;
      padding: 18px 24px;
      font-size: 20px;
      color: #fff;
      background-color: #f44444;
      border-top-left-radius: 12px;
      border-bottom-right-radius: 16px;
    }
  }

  .audit-content {
    display: flex;
    column-gap: 20px;
    min-width: 1400px;
    height: calc(100vh - 175px);

    .remark-list {
      width: 300px;
      overflow: auto;
      border: 1px solid #e5e5e5;

      h5 {
        padding: 0 5px;
        margin: 0;
        font-size: 18px;
        line-height: 40px;
        background: #f2f3f5;
      }

      .delete-btn {
        padding-left: 10px;
        color: #f44444;
        border-left: 1px solid #e5e5e5;
      }

      ul {
        height: calc(100% - 40px);
        overflow: auto;

        li {
          border-bottom: 1px solid #e5e5e5;

          > p {
            padding: 5px;
          }

          :deep p {
            margin: 0;
          }

          .remark-bottom {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 5px;
            font-size: 14px;
            color: #555;
            border-top: 1px solid #e5e5e5;
          }
        }
      }
    }
  }
}

:deep .audit-dialog {
  .el-dialog__body {
    padding: 5px 20px;
  }
}
</style>

<style lang="scss">
.tox-tinymce-aux {
  z-index: 9999 !important;
}
</style>
