// 组件混入 import Vue from 'vue'; import ModuleBase from './ModuleBase.vue'; import RichText from '@/components/RichText.vue'; import MultilingualFill from '@/views/book/components/MultilingualFill.vue'; import AnswerAnalysisList from '@/views/book/courseware/create/components/common/AnswerAnalysisList.vue'; import { displayList, viewMethodList, isEnable, analysisData, answerData } from '@/views/book/courseware/data/common'; import { ContentSaveCoursewareComponentContent, ContentGetCoursewareComponentContent, GetCoursewareComponentBackground, SaveCoursewareComponentBackground, PinyinBuild_OldFormat, } from '@/api/book'; const isPlainObject = (value) => Object.prototype.toString.call(value) === '[object Object]'; /** * 将已保存的组件内容合并到组件默认内容上 * 组件内容可能是空对象(如 "{}")、旧版本结构或部分字段缺失,直接覆盖会让模板读取 undefined 报错, * 表现为整个组件渲染失败、变成空白,因此缺失(或为 null)的字段都回退到默认值 * @param {object} defaults 组件默认内容 * @param {object} data 已保存的组件内容 * @returns {object} 合并后的内容 */ function mergeComponentData(defaults, data) { if (!isPlainObject(defaults)) return data; if (!isPlainObject(data)) return defaults; const result = { ...defaults }; Object.keys(data).forEach((key) => { const defaultValue = defaults[key]; const value = data[key]; // 空值回退到默认值,避免覆盖掉模板依赖的字段 if (value === undefined || value === null) return; if (Array.isArray(defaultValue)) { result[key] = Array.isArray(value) ? value : defaultValue; return; } const isObjectValue = isPlainObject(defaultValue) && isPlainObject(value); result[key] = isObjectValue ? mergeComponentData(defaultValue, value) : value; }); return result; } const mixin = { data() { return { displayList, viewMethodList, typeList: ['interaction'], isEnable, property: { isGetContent: false, // 是否已获取内容 isSilentPropertyWatch: false, // 初始化组件内容时,临时静默 property 监听 isDataPreset: false, // 组件内容是否已由外部预设(粘贴组件),预设后不再用初始化数据覆盖 }, borderColorObj: Vue.observable({ value: this.borderColor }), // 边框颜色 multilingualVisible: false, // 多语言弹窗 idNameOrder: [ 'answer_audio_id_list', 'answer_image_id_list', 'answer_video_id_list', 'analysis_audio_id_list', 'analysis_image_id_list', 'analysis_video_id_list', ], fileNameOrder: [ 'answer_audio_list', 'answer_image_list', 'answer_video_list', 'analysis_audio_list', 'analysis_image_list', 'analysis_video_list', ], background: '', // 组件背景 }; }, props: { id: { type: String, required: true, }, oldId: { type: String, default: '', }, componentMove: { type: Function, required: true, }, borderColor: { type: String, required: true, }, content: { type: String, default: '{}', }, type: { type: String, default: '', }, }, components: { ModuleBase, RichText, MultilingualFill, AnswerAnalysisList, }, provide() { return { showSetting: this.showSetting, copyComponent: this.copyComponent, id: this.id, deleteComponent: this.deleteComponent, handleComponentMove: this.handleComponentMove, property: this.property, borderColor: this.borderColorObj, }; }, watch: { borderColor(newVal) { this.borderColorObj.value = newVal; }, content: { handler(newVal) { if (this.type !== 'interaction') return; if (newVal) this.data = JSON.parse(newVal); }, immediate: true, }, }, inject: ['courseware_id', 'project_id', 'getBookUnifiedAttr', 'getTemporaryCoursewareID'], created() { if (this.type === 'interaction') { this.$emit('contentLoading', !this.property.isGetContent); } else { this.GetCoursewareComponentContent(); } // 初始化 mind_map.node_list[0].id if (!this.data?.mind_map?.node_list?.[0]?.id) { this.data.mind_map = this.data.mind_map ?? {}; this.data.mind_map.node_list = this.data.mind_map.node_list ?? [{}]; if (this.data.mind_map.node_list.length > 0) { this.data.mind_map.node_list[0].id = this.id; } } }, methods: { GetCoursewareComponentContent() { if (this.courseware_id === '' || this.id === '') return; this.$emit('contentLoading', true); this.property.isSilentPropertyWatch = true; let temporaryCoursewareID = this.getTemporaryCoursewareID(); let coursewareID = temporaryCoursewareID || this.courseware_id; let component_id = temporaryCoursewareID.length > 0 ? this.oldId || this.id : this.id; ContentGetCoursewareComponentContent({ courseware_id: coursewareID, component_id }) .then(({ content }) => { // 粘贴组件时内容已由源组件预设,接口返回的初始内容(通常为空)不能覆盖粘贴过来的设置 if (!this.property.isDataPreset) { if (content) { let oldData = {}; try { oldData = JSON.parse(content) ?? {}; } catch (error) { // 内容不是合法 JSON 时不能让组件停留在空数据上 console.error('组件内容解析失败,已使用默认内容', error); } if (oldData.type === 'audio') { let p = oldData.property || {}; if (!p.file_name_display_mode) p.file_name_display_mode = 'true'; if (p.view_method === 'independent' && !p.style_mode) { p.style_mode = 'middle'; } if (!p.style_mode) p.style_mode = 'big'; if (p.view_method === 'icon') { p.file_name_display_mode = 'false'; p.view_method = 'independent'; p.style_mode = 'small'; } } this.data = mergeComponentData(this.data, oldData); } else { const bookUnifiedAttr = this.getBookUnifiedAttr(); this.$set(this.data, 'unified_attrib', bookUnifiedAttr); // 初始化时,如果有 view_pinyin 则根据全教材设置配置设 view_pinyin 和 pinyin_position if ('view_pinyin' in this.data.property) { this.data.property.view_pinyin = bookUnifiedAttr?.view_pinyin ?? 'false'; this.data.property.pinyin_position = bookUnifiedAttr?.pinyin_position ?? 'top'; } if ('frame_color' in this.data.property) { // 框颜色初始化为主题色 this.data.property.frame_color = bookUnifiedAttr?.topic_color ?? '#F13232'; } if ('sn_background_color' in this.data.property) { // 序号背景色 this.data.property.sn_background_color = bookUnifiedAttr?.topic_color ?? '#EA3232'; } } } this.property.isGetContent = true; this.$emit('contentLoading', false); this.$watch( 'data', () => { this.$emit('changeData'); }, { deep: true }, ); }) .catch((error) => { // 请求失败时保持未加载状态(避免用空内容覆盖已保存内容),但把错误暴露出来便于排查 console.error('组件内容获取失败', component_id, error); }) .finally(() => { this.$nextTick(() => { this.property.isSilentPropertyWatch = false; }); }); }, /** * @description 复制组件(组件数据 + 组件背景) */ async copyComponent() { // 编辑器内容可能还未同步到 data,先同步再复制,避免复制到旧内容 this.syncRichTextContent(); const background = await this.getComponentBackground(); this.$emit('copyComponent', { data: JSON.parse(JSON.stringify(this.data)), background, }); }, /** * @description 获取组件背景(已加载过则直接复用,否则从服务端获取) * @returns {Promise} 组件背景 JSON 字符串 */ async getComponentBackground() { const normalize = (background) => background ? (typeof background === 'string' ? background : JSON.stringify(background)) : ''; if (this.background) return normalize(this.background); if (this.courseware_id === '' || this.id === '') return ''; // 与组件内容保持一致:从模板课件取内容时,背景也按模板组件的 id 取 const temporaryCoursewareID = this.getTemporaryCoursewareID(); const courseware_id = temporaryCoursewareID || this.courseware_id; const component_id = temporaryCoursewareID.length > 0 ? this.oldId || this.id : this.id; try { const { background } = await GetCoursewareComponentBackground({ courseware_id, component_id }); return normalize(background); } catch (error) { console.error('组件背景获取失败', component_id, error); return ''; } }, /** * @description 设置组件数据(用于粘贴组件) * @param {Object} data 组件数据 * @param {String} background 组件背景 JSON 字符串 */ setData(data, background = '') { // 标记内容已预设,避免初始化接口返回后再把粘贴过来的设置重置为默认值 this.property.isDataPreset = true; this.property.isSilentPropertyWatch = true; // 先卸载内容区,让依赖 isGetContent 渲染的编辑器(如富文本)用新内容重新初始化 this.property.isGetContent = false; this.$emit('contentLoading', true); this.data = data; this.background = background; this.$nextTick(() => { this.property.isGetContent = true; this.$emit('contentLoading', false); this.$nextTick(() => { this.property.isSilentPropertyWatch = false; }); }); // 背景由独立接口保存,粘贴后立即把源组件的背景写到新组件上 this.saveCoursewareComponentBackground(); }, /** * @description 显示设置 */ showSetting() { this.$emit('showSetting', this.data.property, this.data.type, this.id); }, /** * @description 删除组件 */ deleteComponent() { this.$emit('deleteComponent', this.id); }, /** * @description 更新property属性 * @param {String} type 类型 * @param {Object} attr 属性 */ updateProperty(type, attr) { this.$set(this.data.property, type, attr); }, /** * 批量设置富文本样式 * @param {string} type 类型 * @param {Object} attr 属性 */ updateRichTextProperty(type, attr) { let richTextRefs = this.$refs.richText; if (!richTextRefs) return; if (!Array.isArray(richTextRefs)) { richTextRefs = [richTextRefs]; } richTextRefs?.forEach((richText) => { richText.setRichFormat(type, attr); }); }, /** * 批量设置整体富文本格式 * @param {Array<{type: string, val: string}>} formats 格式数组,每个元素是一个对象,包含 type 和 val */ patchSetRichFormat(formats) { let richTextRefs = this.$refs.richText; if (!richTextRefs) return; if (!Array.isArray(richTextRefs)) { richTextRefs = [richTextRefs]; } richTextRefs?.forEach((richText) => { richText.patchSetRichFormat(formats); }); }, /** * @description 设置 unified_attrib 属性 * @param {object} data unified_attrib数据 */ setUnifiedAttr(data) { if (!data) return; this.data.unified_attrib = data; }, /** * @description 设置单个教材属性 * @param {string} attr 字段名 * @param {any} value 属性值 */ setSingleUnifiedAttr(attr, value) { if (!attr) return; this.$set(this.data.unified_attrib, attr, value); }, handleComponentMove(data) { this.componentMove({ ...data, id: this.id }); }, /** * 保存课件组件内容 * @returns {Promise} 返回 Promise,便于父组件 await */ saveCoursewareComponentContent() { this.syncRichTextContent(); return ContentSaveCoursewareComponentContent({ courseware_id: this.courseware_id, component_id: this.id, component_type: this.data.type, content: JSON.stringify(this.data), background: this.background, }); }, /** * @description 保存组件背景 * @param {String} background 组件背景 JSON 字符串 * @returns {Promise} 返回 Promise,便于父组件 await */ saveCoursewareComponentBackground(background = this.background) { if (!background || this.courseware_id === '' || this.id === '') return Promise.resolve(); return SaveCoursewareComponentBackground({ courseware_id: this.courseware_id, component_id: this.id, background: typeof background === 'string' ? background : JSON.stringify(background), }).catch((error) => { console.error('组件背景保存失败', this.id, error); }); }, syncRichTextContent() { const syncEditors = (children) => { children.forEach((child) => { if (child.$options.name === 'RichText' && typeof child.syncContent === 'function') { child.syncContent(); } syncEditors(child.$children || []); }); }; syncEditors(this.$children || []); }, /** * @description 获取组件请求内容 @returns {Object} 组件请求内容 */ getComponentRequestContent() { this.syncRichTextContent(); return { courseware_id: this.courseware_id, component_id: this.id, component_type: this.data.type, content: JSON.stringify(this.data), background: this.background, }; }, findComponentWithRefAndMethod(children, refName, methodName) { for (const child of children) { // 检查当前组件是否符合条件 if (child.$refs[refName] && typeof child[methodName] === 'function') { return child; } // 递归检查子组件 if (child.$children?.length) { const found = this.findComponentWithRefAndMethod(child.$children, refName, methodName); if (found) return found; } } return null; }, openMultilingual() { this.multilingualVisible = true; }, /** * @description 提交多语言翻译 * @param {Array} multilingual */ handleMultilingualTranslation(multilingual) { this.$set(this.data, 'multilingual', multilingual); }, /** * 获取并设置拼音解析文本 * @param {String} text 文本 * @param {Number} i 行索引 * @param {Number} j 列索引 * @param {String} attr 属性名 */ createParsedTextInfoPinyin(text, i = -1, j = -1, attr = 'option_list', fc_list = []) { let data = null; if (i === -1) { data = this.data; } else if (i >= 0 && j === -1) { data = this.data[attr][i]; } else if (i >= 0 && j >= 0) { data = this.data[attr][i][j]; } if (text === '') { data.pinyin_proofread_word_list = []; return Promise.resolve({ parsed_text: null, rich_text: null }); } data.paragraph_list_parameter.text = text; return PinyinBuild_OldFormat({ ...data.paragraph_list_parameter, is_first_sentence_first_hz_pinyin_first_char_upper_case: this.data.property.is_first_sentence_first_hz_pinyin_first_char_upper_case, is_fill_space: 'true', is_rich_text: 'true', is_custom_fc: fc_list.length > 0, fc_paragraph_list: fc_list, }).then(({ parsed_text, rich_text }) => { if (parsed_text) { // 合并 activeTextStyle const mergedData = parsed_text.paragraph_list.map((outerArr, i) => outerArr.map((innerArr, j) => innerArr.map((newItem, k) => { if (!newItem.pinyin) newItem.pinyin = newItem.text; return { ...newItem, // 如果 originalItem 有 activeTextStyle,就合并到 newItem ...(data.paragraph_list?.[i]?.[j]?.[k]?.activeTextStyle && { activeTextStyle: data.paragraph_list[i][j][k].activeTextStyle, }), }; }), ), ); data.paragraph_list = mergedData; } if (rich_text) { data.rich_text_list = rich_text.text_list; } return { parsed_text, rich_text }; }); }, /** * 填充校对后的拼音 * @param {Object} param0 拼音参数 * @param {Number} row 行索引 * @param {Number} col 列索引 * @param {String} attr 属性名 */ fillCorrectPinyin( { selectContent: { text, pinyin, activeTextStyle, note, showPinyin }, i, j, k, newVersion }, row = -1, col = -1, attr = 'option_list', ) { if (newVersion) { let richTextList = null; if (row === -1) { richTextList = this.data.rich_text_list; } else if (row >= 0 && col === -1) { richTextList = this.data[attr]?.[row]?.rich_text_list; } else if (row >= 0 && col >= 0) { richTextList = this.data[attr]?.[row]?.[col]?.rich_text_list; } if (!richTextList) return; const targetBlock = richTextList[j]; if (!targetBlock || !targetBlock.word_list) { return; } const targetWord = targetBlock.word_list[k]; if (!targetWord) { return; } if (pinyin) { targetWord.pinyin = pinyin; targetWord.pinyin_list = pinyin.split(/\s+/); } if (showPinyin !== undefined && showPinyin !== null) { targetWord.showPinyin = showPinyin; } if (note !== null && note !== undefined) { targetWord.note = note; } if (activeTextStyle && Object.keys(activeTextStyle).length > 0) { targetWord.activeTextStyle = { ...targetWord.activeTextStyle, ...activeTextStyle }; } return; } // 兼容旧版逻辑 let data = null; if (row === -1) { data = this.data.paragraph_list_parameter; } else if (row >= 0 && col === -1) { data = this.data[attr][row].paragraph_list_parameter; } else if (row >= 0 && col >= 0) { data = this.data[attr][row][col].paragraph_list_parameter; } if (!Array.isArray(data.pinyin_proofread_word_list)) { data.pinyin_proofread_word_list = []; } data.pinyin_proofread_word_list.push({ paragraph_index: i, sentence_index: j, word_index: k, word: text, pinyin, showPinyin, }); let listItem = null; if (row === -1) { listItem = this.data.paragraph_list?.[i]?.[j]?.[k]; } else if (row >= 0 && col === -1) { listItem = this.data[attr]?.[row]?.paragraph_list?.[i]?.[j]?.[k]; } else if (row >= 0 && col >= 0) { listItem = this.data[attr]?.[row]?.[col]?.paragraph_list?.[i]?.[j]?.[k]; } if (listItem) { if (pinyin) listItem.pinyin = pinyin; if (activeTextStyle) listItem.activeTextStyle = activeTextStyle; if (note !== null) listItem.note = note; listItem.showPinyin = showPinyin; } }, /** * 组件中添加答案与解析 * @param {'answer'|'analysis'} type 类型 answer 答案 analysis 解析 */ addAnswerAndAnalysis(type) { // 确保 answer_list 和 analysis_list 已初始化 ['answer_list', 'analysis_list'].forEach((key) => { if (!this.data[key]) { this.$set(this.data, key, []); } }); if (type === 'answer') { this.data.answer_list.push(structuredClone(answerData)); } else if (type === 'analysis') { this.data.analysis_list.push(structuredClone(analysisData)); } }, /** * 更新答案或解析的文件列表 * @param {Array} file_list 文件列表 * @param {Array} file_id_list 文件ID列表 * @param {Number} index 答案解析索引 * @param {Number} indexs 文件类型索引 0-答案音频 1-答案图片 2-答案视频 3-解析音频 4-解析图片 5-解析视频 * @param {String} type 类型 answer 答案 analysis 解析 */ updateAnswerAnalysisFileList({ file_list, file_id_list, index, indexs, type }) { if (type === 'answer') { this.data.answer_list[index][this.idNameOrder[indexs]] = file_id_list; this.data.answer_list[index][this.fileNameOrder[indexs]] = file_list; } else if (type === 'analysis') { this.data.analysis_list[index][this.idNameOrder[indexs]] = file_id_list; this.data.analysis_list[index][this.fileNameOrder[indexs]] = file_list; } }, /** * 删除答案或解析项 * @param {Object} param 参数对象 * @param {number} param.index 索引 * @param {'answer'|'analysis'} param.type 类型 */ deleteAnswerAnalysis({ index, type }) { if (type === 'answer') { this.data.answer_list.splice(index, 1); } else if (type === 'analysis') { this.data.analysis_list.splice(index, 1); } }, }, }; export default mixin;