<template>
  <comment-editor :piyueable="piyueable" :readonly="readonly" :info="info" :model-value="modelValue" @update:model-value="$emit('update:modelValue', $event)">
    <template v-slot:video>
      <score-show v-if="piyueable && info.scores?.length > 0" :horizontal="true" :scores="info.scores"></score-show>
      <div :style="{height: info.scores?.length ? 'calc(100% - 16px)' : '100%'}">
        <hty-video :id="video_id" v-if="readonly && modelValue?.video" :downloadable="downloadable" :src="modelValue.video.resource_url"></hty-video>
      </div>
    </template>
    <template v-slot:qupu>
      <template v-if="show_qupu && (!disabled || info.has_piyue)">
        <div class="qupu-area">
          <qupu-map :video_id="video_id" v-if="qupu" :floating="true" :readonly="info.has_piyue || !is_teacher"
                    :backgroundUrl="qupu.resource_url" :marks="marks" @pause="mark($event)" @update="update($event)" />
        </div>
        <div class="piyue-btn" v-if="!info.has_piyue && is_teacher && info.id && piyueable">
          <van-button block size="mini" :disabled="!marks.length" @click="piyue" :type="marks.length > 0 ? 'success' : 'danger'">{{marks.length > 0 ? '提交批阅' : '点击图片进行批阅'}}</van-button>
        </div>
      </template>
    </template>
  </comment-editor>
  <van-dialog v-if="show_qupu && (!disabled || info.has_piyue)" v-model:show="pizhuing" :title="'批注' + state.pausing" :show-confirm-button="!info?.has_piyue"
              :cancel-button-text="info?.has_piyue ? '关闭' : '删除'" :confirmButtonDisabled="!pizhued"
              show-cancel-button @cancel="cancel" @confirm="save" teleport="body">
    <template v-if="!!state.note?.content">
      <comment-editor :readonly="info?.has_piyue" v-model="state.note.content">
        <template v-slot:video>
          <hty-video v-if="state.note?.content?.video" :downloadable="downloadable" :src="state.note?.content?.video.resource_url"></hty-video>
        </template>
      </comment-editor>
    </template>
  </van-dialog>
</template>

<script lang="ts">
import {computed, defineComponent, getCurrentInstance, reactive, ref, watch} from 'vue';
import {Button, Dialog, Field} from 'vant'
import AudioRecord from './audio-record.vue';
import UploadProgress from './upload-progress.vue';
import VideoUploader from './video-uploader.vue';
import PhotoUploader from './photo-uploader.vue';
import QupuMap from "./qupu-map.vue";
import {
  Comment,
  CommentRefTypes,
  HtyBaseRoles,
  NotifyParam,
  NotifyTypes,
  RefResourceTypes,
  ResourceNote
} from "~/types";
import useUser from "~/store/user";
import HtyVideo from "~/components/hty-video.vue";
import CommentEditor from "~/components/comment-editor.vue";
import usePiyue from "~/store/piyue";
import usePool from "~/store/pool";
import ScoreShow from '~/components/score-show.vue'
import {uuid} from "~/utils";

export default defineComponent({
  name: "comment-block",
  components: {
    CommentEditor,
    [AudioRecord.name]: AudioRecord,
    [Field.name]: Field,
    [QupuMap.name]: QupuMap,
    [UploadProgress.name]: UploadProgress,
    [VideoUploader.name]: VideoUploader,
    [PhotoUploader.name]: PhotoUploader,
    [Button.name]: Button,
    [HtyVideo.name]: HtyVideo,
    [Dialog.name]: Dialog,
    [CommentEditor.name]: CommentEditor,
    [ScoreShow.name]: ScoreShow
  },
  props: ['modelValue', 'readonly', 'info', 'author', 'qupu', 'disabled'],
  emits: ['update:modelValue', 'piyue'],
  setup(props) {
    const instance = getCurrentInstance();
    const usingUser = useUser()
    usingUser.loadMyTeachers();
    const {get} = usePool()
    const { add_resource_notes, notify } = usePiyue();
    const video_id = uuid();

    const state = reactive({note: null as (Comment | null), pausing: ''})
    const pizhuing = ref(false);
    const marks = ref<ResourceNote[]>(props.info?.resource_note_group?.resource_notes || []);

    watch(() => props.info, () => {
      marks.value = props.info?.resource_note_group?.resource_notes || []
    })

    const mark = (data: ResourceNote) => {
      state.pausing = data.serial_no;
      if (!data.comments?.length) {
        state.note = data.comment || {ref_type: CommentRefTypes.Piyue, content: {text: ''}}
      } else {
        let {content, ref_resources, ...rest} = data.comments[0]
        content = {...(content || {})};
        content.audio = ref_resources?.find(r => r.resource_type === RefResourceTypes.Audio);
        content.video = ref_resources?.find(r => r.resource_type === RefResourceTypes.Video);
        content.photos = ref_resources?.filter(r => r.resource_type === RefResourceTypes.Picture);
        state.note = {content, ...rest}
      }
      pizhuing.value = true;
    }

    const save = async () => {
      let el = document.getElementById(video_id) as HTMLVideoElement;
      if (el && el.currentTime > 0.01) {
        await el.play();
      }
      let {note, pausing} = state;
      note = note as Comment
      let mark = marks.value.find((x: ResourceNote) => x.serial_no === pausing);
      if (mark) {
        mark.comment = note;
        state.pausing = '';
        pizhuing.value = false;
        state.note = null;
      }
    }

    const cancel = () => {
      pizhuing.value = false;
      if (!props.info.has_piyue) {
        let index = marks.value.findIndex((x: ResourceNote) => x.serial_no === state.pausing);
        marks.value.splice(index, 1)
      }
      state.pausing = '';
      state.note = null;
    }

    const update = (data: ResourceNote[]) => {
      marks.value = data;
    }

    const piyue = async () => {
      let payload = {
        qupu: props.qupu,
        video: props.modelValue?.video
      }
      let created = await add_resource_notes(marks.value, payload, props.info.id, "Comment");
      if (created) {
        instance?.emit("piyue", created)
        // notify
        let { jihua_id, daka_id, piyue_id, lianxi_id, course_section } = get();
        let params: NotifyParam = {
          notify_type: NotifyTypes.ResourceNoteGroupCreate,
          hty_id: props.info.created_by,
          jihua_id, daka_id, lianxi_id, piyue_id,
          resource_note_group_id: created.id,
          ref_id: props.info.id,
          ref_type: "Comment",
          course_name: course_section?.course_name,
          course_section_name: course_section?.section_name
        }
        notify(params, HtyBaseRoles.STUDENT);
      }
    }

    const downloadable = computed(() => {
      if (!props.author) return true;
      const is_author = props.author === usingUser.store.current.hty_id;
      if (is_author) return true;
      return usingUser.store.teachers.mine.some(x => x.hty_id === props.author);
    })

    const is_teacher = computed(() => usingUser.store.currentRole === HtyBaseRoles.TEACHER);

    const pizhued = computed(() => {
      if (!state.note) return false;
      let { content } = state.note;
      return content?.text || content?.video?.resource_url || (content?.audio?.tasks?.vals && content.audio.tasks.vals[0]?.task_meta?.media_id);
    })

    const show_qupu = computed(() => {
      let { readonly, qupu, modelValue, info } = props;
      return readonly && qupu && modelValue?.video && info?.id && info.creator_role_key !== HtyBaseRoles.TEACHER && (info?.has_piyue || is_teacher.value)
    })

    const piyueable = computed(() => props.qupu && props.info.creator_role_key !== HtyBaseRoles.TEACHER)

    return {
      downloadable, marks, mark, update, piyue, state, save, cancel, pizhuing, pizhued, is_teacher, show_qupu, video_id, piyueable
    }
  }
});
</script>

<style scoped lang="less">

.qupu-area {
  height: 30vh;
  max-height: 30vh;
  padding: 0 0.16rem;
  width: 100%;
  margin-bottom: 0.16rem;
}
.piyue-btn {
  text-align: center;
  margin-bottom: 0.16rem;
}


  
</style>
