<template>
  <qupu-map v-if="qupu?.resource_url" :video_id="video_id" :background-url="qupu?.resource_url" :marks="marks" :readonly="disabled || readonly"
            @pause="pause" @update="$emit('update', $event)"/>
  <van-empty v-else description="图片加载中..."></van-empty>
  <van-action-sheet :lock-scroll="false" v-model:show="state.replying" :title="'批注 ' + state.pausing"
                    @close="close" :close-on-click-overlay="false">
    <comments-sheet :disabled="disabled" :readonly="!replyable" :ref_id="mark_id" v-model:comment="state.comment" :qupu="qupu"
                    @reply="reply" @submit="submit" @remove="remove" ></comments-sheet>
  </van-action-sheet>
</template>

<script type="module" lang="ts">
import {computed, defineComponent, getCurrentInstance, reactive} from 'vue'
import {ActionSheet, Button, Dialog, Field, Form, Loading, Overlay, Empty} from 'vant'
import {Comment, CommentRefTypes, ResourceNote} from "~/types";
import QupuMap from "~/components/qupu-map.vue";
import AudioRecord from '~/components/audio-record.vue';
import CommentsSheet from '~/components/comments-sheet.vue';

export default defineComponent({
  name: "lianxi-pigai",
  props: ['qupu', 'marks', 'readonly', 'commentator', 'replyable', 'video_id', 'disabled'],
  emits: ['update', 'notify'],
  components: {
    [Dialog.name]: Dialog,
    [Form.name]: Form,
    [Field.name]: Field,
    [AudioRecord.name]: AudioRecord,
    [Button.name]: Button,
    [Overlay.name]: Overlay,
    [Loading.name]: Loading,
    [ActionSheet.name]: ActionSheet,
    [QupuMap.name]: QupuMap,
    [CommentsSheet.name]: CommentsSheet,
    [Empty.name]: Empty
  },
  setup(props) {

    const initComment = () =>  ({ref_type: CommentRefTypes.Piyue, content: {}} as Comment)
    let state = reactive({
      pausing: '',
      resizing: false,
      comment: null as (Comment | null),
      replying: false,
      buffer: [] as string[]
    });

    const cache: {[key: string] : Comment} = {}

    const instance = getCurrentInstance();

    const submit = async () => {
      let {comment, pausing} = state;
      comment = comment as Comment
      let mark = props.marks.find((x: ResourceNote) => x.serial_no === pausing);
      if (!mark.comments?.length) {
        mark.comment = comment;
        instance?.emit('update', props.marks)
        state.pausing = '';
        state.replying = false;
        state.comment = null;
        let el = document.getElementById(props.video_id) as HTMLVideoElement;
        if (el && el.currentTime > 0.01) {
          await el.play();
        }
        // push into buffer
        state.buffer.push(pausing)
      } else {
        comment.ref_id = mark.id;
        comment.ref_type = CommentRefTypes.ResourceNote;
        let created = await props.commentator(comment);
        if (created) {
          state.comment = null;
          instance?.emit("notify", {comment_id: created.id, serial: pausing})
        }
      }
      
    }

    const remove = () => {
      state.replying = false;
      if (state.pausing) {
        let index = props.marks.findIndex((x: ResourceNote) => x.serial_no === state.pausing);
        let mark = props.marks[index];
        state.comment = null;
        // remove buffer
        state.buffer = state.buffer.filter(x => x !== state.pausing)
        if (!mark?.comments?.length) {
          // 第一条批注，如果删除，则删除标记
          props.marks.splice(index, 1);
          instance?.emit('update', props.marks)
        }
        // remove cache
        cache[state.pausing] = undefined;
        // 后续的回复，如果删除，则仅删除当条回复，不删除标记
        state.pausing = '';
      }
    }

    const close = () => {
      let { pausing, buffer } = state;
      if (pausing) {
        if (!buffer.includes(pausing)) {
          remove();
        } else {
          // restore any changes
          let mark = props.marks.find((x: ResourceNote) => x.serial_no === pausing);
          if (cache[pausing]) {
            mark.comment = cache[pausing]
          }
        }
      } else {
        state.replying = false;
      }
    }

    const pause = (data: ResourceNote) => {
      state.pausing = data.serial_no;
      state.replying = true;
      if (data.comments?.length === 0) {
        state.comment = data.comment || {
          ref_type: CommentRefTypes.Piyue,
          content: {text: ''}
        }
        cache[data.serial_no] = JSON.parse(JSON.stringify(state.comment))
      }
    }

    const reply = (parent_id?: string) => {
      state.comment = {
        ...initComment(), parent_id
      }
    }

    const mark_id = computed(() => {
      return props.marks.find((x: ResourceNote) => x.serial_no === state.pausing)?.id;
    })

    return {state, submit, remove, close, reply, mark_id, pause}
  },
});
</script>

<style scoped lang="less">

</style>
