<template>
  <el-dialog
    class="finish-courseware"
    :visible="dialogVisible"
    width="860px"
    title="完成课件"
    :close-on-click-modal="false"
    @close="dialogClose"
  >
    <bookquestion
      ref="courseware"
      :context="context"
      @handleBookUserAnswer="handleBookUserAnswer"
    />

    <div slot="footer">
      <el-button type="primary" @click="finishTaskMaterial">完成</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { GetCoursewareContent_View, FinishMyTaskMaterial_Student } from '@/api/course';

export default {
  props: {
    dialogVisible: {
      default: false,
      type: Boolean
    },
    id: {
      default: '',
      type: String
    },
    coursewareId: {
      default: '',
      type: String
    }
  },
  data() {
    return {
      context: null,
      exam_answer: ''
    };
  },
  watch: {
    coursewareId(val) {
      if (!val) {
        this.context = null;
        this.exam_answer = '';
        return;
      }

      GetCoursewareContent_View({ id: this.coursewareId }).then(({ content }) => {
        if (content) {
          this.context = {
            id: this.coursewareId,
            ui_type: JSON.parse(content).question.ui_type,
            content: JSON.parse(content)
          };
          this.$nextTick(() => {
            this.$refs.courseware.handleAnswerTimeStart();
          });
        } else {
          this.context = null;
        }
      });
    }
  },
  methods: {
    finishTaskMaterial() {
      FinishMyTaskMaterial_Student({
        task_id: this.id,
        material_type: 'COURSEWARE',
        material_id: this.coursewareId,
        exam_answer: this.exam_answer
      }).then(() => {
        this.$message.success('完成课件成功');
        this.dialogClose();
      });
    },

    handleBookUserAnswer(data) {
      this.exam_answer = data;
    },

    dialogClose() {
      this.$emit('dialogClose');
    }
  }
};
</script>

<style lang="scss">
@import '~@/styles/mixin.scss';

.finish-courseware {
  @include dialog;
}
</style>
