<template>
<div class="qupu-map-editor">
  <div class="toolbar">
    <div class="toolbar-btn" v-if="state.allowMark">
      <van-button size="mini" :disabled="state.drawing || (!marks.length && !resource_note_group?.resource_notes?.length) || saving || !changed" type="primary" @click="save">保存标注</van-button>
    </div>
    <div class="toolbar-toggle" v-if="!disabled">
      <span class="action-label">{{state.allowMark ? '关闭': '打开'}}标注</span>
      <van-switch :disabled="state.drawing" v-model="state.allowMark" size="16" @change="closeMark()" />
    </div>
  </div>
  <div class="qupu-map-root" v-if="qupu">
    <qupu-map :background-url="qupu.resource_url" :marks="marks" :readonly="disabled || !state.allowMark"
              @pause="pause" @draw="state.drawing = $event" @update="update($event)" />
  </div>
</div>
<van-action-sheet :lock-scroll="false" v-model:show="state.replying" :title="'批注 ' + state.pausing"
                  @closeed="cancel" :close-on-click-overlay="false">
  <comments-sheet :disabled="disabled" :readonly="!state.allowMark" :ref_id="mark_id" v-model:comment="state.comment"
                  @submit="submit" @remove="remove">
  </comments-sheet>
</van-action-sheet>
</template>


<script lang="ts">
import {computed, defineComponent, getCurrentInstance, onBeforeMount, onBeforeUnmount, reactive, ref, watch} from 'vue';
import {ActionSheet, Switch, Button, showFailToast} from 'vant';
import QupuMap from "~/components/qupu-map.vue";
import CommentsSheet from "~/components/comments-sheet.vue";
import {Comment, CommentRefTypes, ResourceNote} from "~/types";
import {isQupuMarksChanged} from "~/utils";


export default defineComponent({
  name: "qupu-map-editor",
  components: {
    [QupuMap.name]: QupuMap,
    [CommentsSheet.name]: CommentsSheet,
    [ActionSheet.name]: ActionSheet,
    [Switch.name]: Switch,
    [Button.name]: Button
  },
  props: ["qupu", "ref_id", "resource_note_group", "disabled"],
  emits: ["submit"],
  setup(props) {
    const instance = getCurrentInstance();
    const marks = ref<ResourceNote[]>(JSON.parse(JSON.stringify(props.resource_note_group?.resource_notes || [])));

    const saving = ref(false);
    let state = reactive({
      pausing: '',
      resizing: false,
      comment: null as (Comment | null),
      replying: false,
      allowMark: false,
      drawing: false
    });

    let previous: string = JSON.stringify(marks.value);

    const changed = computed(() => {
      return isQupuMarksChanged(previous, JSON.stringify(marks.value), false);
    })

    watch(() => props.resource_note_group, cur => {
      state.allowMark = false;
      marks.value = JSON.parse(JSON.stringify(cur?.resource_notes || []));
      previous = JSON.stringify(marks.value);
    })


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

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

    const cancel = () => {
      state.pausing = '';
      state.replying = false;
      state.comment = null;
    }

    const submit = async () => {
      let {comment, pausing} = state;
      comment = comment as Comment
      let mark = marks.value.find((x: ResourceNote) => x.serial_no === pausing);
      if (mark) {
        mark.comment = comment;
        state.pausing = '';
        state.replying = false;
        state.comment = null;
      } else {
        console.log("mark undefined...", comment, pausing)
      }
    }

    const remove = () => {
      state.replying = false;
      state.comment = null;
      if (state.allowMark) {
        let index = marks.value.findIndex((x: ResourceNote) => x.serial_no === state.pausing);
        marks.value.splice(index, 1);
      }
      // 后续的回复，如果删除，则仅删除当条回复，不删除标记
      state.pausing = '';
    }

    const save = async () => {
      if (saving.value) return;
      saving.value = true;
      await instance?.emit("submit", {marks: marks.value, payload: {qupu: props.qupu}})
      saving.value = false;
    }

    const closeMark = () => {

      if (!state.allowMark && changed.value) {
        showFailToast("请先保存或还原所做更改！");
        state.allowMark = true;
      }

    }

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


    return {
      state, marks, mark_id, pause, update, remove, closeMark, save, submit, saving, changed, cancel
    }

  }
})
</script>



<style scoped lang="less">
.qupu-map-editor {
  padding: 0 0.32rem;

  .toolbar {
    margin-bottom: 0.24rem;
    font-size: 0.24rem;
    font-family: unset;
    display: inline-flex;
    align-items: center;

    .toolbar-toggle {
      display: inline-flex;
      margin-left: 10px;
    }
  }
  .qupu-map-root {
    height: 5rem;
  }
}
</style>
