// 组件混入
import ModuleBase from './ModuleBase.vue';
import RichText from '@/components/RichText.vue';

import { displayList, viewMethodList, isEnable } from '@/views/book/courseware/data/common';
import { SaveCoursewareComponentContent, GetCoursewareComponentContent } from '@/api/book';

const mixin = {
  data() {
    return {
      displayList,
      viewMethodList,
      isEnable,
      property: {
        isGetContent: false, // 是否已获取内容
      },
    };
  },
  props: {
    id: {
      type: String,
      required: true,
    },
    deleteComponent: {
      type: Function,
      required: true,
    },
    componentMove: {
      type: Function,
      required: true,
    },
  },
  components: {
    ModuleBase,
    RichText,
  },
  provide() {
    return {
      showSetting: this.showSetting,
      id: this.id,
      deleteComponent: this.deleteComponent,
      handleComponentMove: this.handleComponentMove,
      property: this.property,
    };
  },
  inject: ['courseware_id'],
  created() {
    GetCoursewareComponentContent({ courseware_id: this.courseware_id, component_id: this.id }).then(({ content }) => {
      if (content) {
        this.data = JSON.parse(content);
        this.property.isGetContent = true;
      }

      this.$watch(
        'data',
        () => {
          this.$emit('changeData');
        },
        { deep: true },
      );
    });
  },
  methods: {
    /**
     * @description 显示设置
     */
    showSetting() {
      this.$emit('showSetting', this.data.property, this.data.type, this.id);
    },
    /**
     * @description 更新属性
     * @param {object} setting 属性
     * @param {string} type 属性类型
     */
    updateSetting(property) {
      this.data.property = property;
    },
    handleComponentMove(data) {
      this.componentMove({ ...data, id: this.id });
    },
    saveCoursewareComponentContent() {
      SaveCoursewareComponentContent({
        courseware_id: this.courseware_id,
        component_id: this.id,
        component_type: this.data.type,
        content: JSON.stringify(this.data),
      });
    },
  },
};

export default mixin;
