<template>
  <div class="task-preview">
    <MenuPage only-key="/personal_workbench/edit_task" />

    <CommonPreview
      :id="id"
      ref="preview"
      :project-id="project_id"
      type="edit_preview"
      @updateBackground="background = $event"
      @selectedComponent="curComponentData = $event"
    >
      <template #operator="{ courseware }">
        <span class="link" @click="openCreateTemplateDialog">保存为个人模板</span>
        <template v-if="isTrue(courseware.is_can_start_edit)">
          <span class="link" @click="showSetBackground">背景设置</span>
          <span class="link" @click="showSetComponentBackground">组件背景设置</span>
          <span class="link" @click="editTask()">开始编辑</span>
        </template>
        <span v-if="isTrue(courseware.is_can_submit_audit)" class="link" @click="submitCoursewareToAuditFlow()">
          提交审核
        </span>
        <span class="link" @click="goBackBookList()">返回教材列表</span>
      </template>
    </CommonPreview>

    <CreateCoursewareAsTemplateVue :visible.sync="visibleTemplate" @confirm="saveCoursewareAsTemplate" />

    <SetBackground
      :visible.sync="visibleBackground"
      :url="background.background_image_url"
      :position="background.background_position"
      :background-data="background.background"
      @setBackground="setBackground"
    />

    <SetComponentBackground
      :visible.sync="visibleComponentBackground"
      :url="componentBackground.background_image_url"
      :position="componentBackground.background_position"
      :background-data="componentBackground.background"
      :component-data="curComponentData"
      @setComponentBackground="saveCoursewareComponentBackground"
    />
  </div>
</template>

<script>
import MenuPage from '@/views/personal_workbench/common/menu.vue';
import CommonPreview from '@/components/CommonPreview.vue';
import CreateCoursewareAsTemplateVue from '@/views/personal_workbench/edit_task/preview/CreateCoursewareAsTemplate.vue';
import SetBackground from '@/views/book/courseware/create/components/SetBackground.vue';
import SetComponentBackground from '@/views/book/courseware/create/components/SetComponentBackground.vue';

import { SubmitBookCoursewareToAuditFlow } from '@/api/project';
import { isTrue } from '@/utils/validate';
import { SaveCoursewareAsTemplatePersonal } from '@/api/template';
import {
  SaveCoursewareBackground,
  GetCoursewareBackground,
  GetCoursewareComponentBackground,
  SaveCoursewareComponentBackground,
} from '@/api/book';

export default {
  name: 'TaskPreviewPage',
  components: {
    MenuPage,
    CommonPreview,
    CreateCoursewareAsTemplateVue,
    SetBackground,
    SetComponentBackground,
  },
  data() {
    return {
      id: this.$route.params.id,
      project_id: this.$route.query.project_id,
      isTrue,
      visibleTemplate: false,
      background: {
        background_image_url: '',
        background_position: {},
        background: {},
      },
      visibleBackground: false,
      visibleComponentBackground: false,
      // 当前选中组件数据
      curComponentData: {
        courseware_id: '',
        component_id: '',
      },
      componentBackground: {
        background_image_url: '',
        background_position: {},
        background: {},
      },
    };
  },
  created() {
    GetCoursewareBackground({ id: this.id }).then(({ background }) => {
      if (background) this.background = JSON.parse(background);
    });
  },
  methods: {
    goBackBookList() {
      this.$router.push({ path: '/personal_workbench/edit_task' });
    },
    editTask() {
      this.$router.push({
        path: `/personal_workbench/edit_task/edit/${this.$refs.preview.select_node}`,
        query: { project_id: this.project_id },
      });
    },
    /**
     * 提交课件到审核流程
     */
    submitCoursewareToAuditFlow() {
      SubmitBookCoursewareToAuditFlow({ id: this.$refs.preview.select_node }).then(() => {
        this.$message.success('课件已提交审核');
        this.$refs.preview.getBookCoursewareInfo(this.$refs.preview.select_node);
      });
    },
    /**
     * 打开保存为个人模板的弹窗
     */
    openCreateTemplateDialog() {
      this.visibleTemplate = true;
    },
    /**
     * 保存为个人模板
     * @param {object} form 模板信息
     * @param {string} form.name 模板名称
     * @param {string[]} form.label_list 模板标签列表
     * @param {string} form.memo 模板备注
     * @param {number} form.scope 模板范围
     * @param {string} form.is_select_part_courseware_mode 是否选择部分课件模式
     * @param {number} form.content_type 模板内容类型 0: 内容模板，1: 样式模板
     */
    saveCoursewareAsTemplate(form) {
      this.$confirm('确定保存为个人模板吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.visibleTemplate = false;
          let courseware_info = {};
          if (form.is_select_part_courseware_mode === 'true') {
            courseware_info = this.$refs.preview.computedSelectedGroupCoursewareInfo();

            if (courseware_info?.component_id_list.length === 0) {
              this.$message.warning('请选择要保存的内容');
              return;
            }
          }
          SaveCoursewareAsTemplatePersonal({
            courseware_id: this.$refs.preview.select_node,
            courseware_info,
            ...form,
          })
            .then(({ courseware_id }) => {
              if (form.content_type === 0) {
                return this.$message.success('已保存为个人模板');
              }
              this.$refs.preview.saveCoursewareStyleTemplate({
                courseware_id,
                is_select_part_courseware_mode: form.is_select_part_courseware_mode,
                component_id_list: courseware_info?.component_id_list || [],
              });
            })
            .catch(() => {
              this.$message.error('保存个人模板失败');
            });
        })
        .catch(() => {});
    },
    /**
     * 显示背景设置弹窗
     */
    showSetBackground() {
      this.visibleBackground = true;
    },
    /**
     * 显示组件背景设置弹窗
     */
    async showSetComponentBackground() {
      if (this.curComponentData.component_id === '') {
        this.$message.warning('请先选择一个组件');
        return;
      }
      const loading = this.$loading('加载组件数据中...');
      await GetCoursewareComponentBackground(this.curComponentData).then(({ background }) => {
        if (background) {
          this.componentBackground = JSON.parse(background);
        } else {
          this.revertComponentBackground();
        }
      });
      loading.close();
      this.visibleComponentBackground = true;
    },
    /**
     * 设置组件背景
     * @param {string} url 背景图片地址
     * @param {string} position 背景图片位置
     * @param {string} background
     */
    saveCoursewareComponentBackground(url, position, background) {
      this.componentBackground = {
        background_image_url: url,
        background_position: position,
        background,
      };
      const backgroundStr = JSON.stringify(this.componentBackground);
      SaveCoursewareComponentBackground({
        ...this.curComponentData,
        background: backgroundStr,
      })
        .then(() => {
          this.$message.success('组件背景设置成功');
          this.$refs.preview.updateComponentBackground(this.curComponentData, backgroundStr);
        })
        .finally(() => {
          this.revertComponentBackground();
        });
    },
    /**
     * 还原组件背景数据
     */
    revertComponentBackground() {
      this.componentBackground = {
        background_image_url: '',
        background_position: {},
        background: {},
      };
    },
    /**
     * 设置背景
     * @param {string} url 背景图片地址
     * @param {string} position 背景图片位置
     * @param {string} background
     */
    setBackground(url, position, background) {
      this.background = {
        background_image_url: url,
        background_position: position,
        background,
      };
      SaveCoursewareBackground({ id: this.id, background: JSON.stringify(this.background) }).then(() => {
        this.$message.success('背景设置成功');
        this.$refs.preview.updateBackground(this.background);
      });
    },
  },
};
</script>

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

.task-preview {
  @include page-content(true);
}
</style>

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