<template>
  <div class="container" ref="container">
    <div class="comments" v-if="dataset.length || !disabled">
      <comment-block :qupu="qupu" @piyue="piyue" :author="comment.created_by" :disabled="disabled"
                     v-for="comment in dataset" :info="comment.info" :readonly="true"
                     v-model="comment.content"></comment-block>
      <template v-if="!!comment">
        <comment-block v-model="comment.content"></comment-block>
      </template>
      <div class="tool" v-if="!comment && !readonly && !disabled">
        <van-button block size="small" type="primary" @click="$emit('reply')">添加回复</van-button>
      </div>
    </div>
    <van-empty v-else description="暂无回复" />
    <div class="footer" v-if="!disabled && !readonly">
      <template v-if="!dataset.length || comment?.id">
        <van-button color="#ee0a24" size="small" @click="cancel">删除</van-button>
        <van-button color="#1989fa" size="small" :disabled="!can_save" @click="submit">确认</van-button>
      </template>
      <template v-else>
        <template v-if="!!comment">
          <van-button color="#ee0a24" size="small" @click="cancel">取消</van-button>
          <van-button color="#1989fa" :disabled="!can_save" size="small" @click="submit">提交</van-button>
        </template>
        <template v-else>
          <van-button size="small" @click="$emit('remove')">关闭</van-button>
        </template>
      </template>
    </div>
    <div class="footer" v-else>
      <van-button size="small" @click="$emit('remove')">关闭</van-button>
    </div>
  </div>
</template>

<script lang="ts">
import {defineComponent, computed, onMounted, ref, watch, getCurrentInstance} from 'vue'
import CommentBlock from '~/components/comment-block.vue';
import {Button, Empty} from 'vant'
import {Comment, RefResourceTypes, ResourceNoteGroup} from '~/types'
import useAudio from '~/store/audio';
import useComment from "~/store/comment";
import {get_search_params, MediaHelper} from "~/utils";

export default defineComponent({
    name: "comments-sheet",
    components: {
        [CommentBlock.name]: CommentBlock,
        [Button.name]: Button,
        [Empty.name]: Empty
    },
    props: ["comment", "qupu", "ref_id", "readonly", "disabled"],
    emits: ["remove", "submit", "reply"],
    setup(props, {emit}) {
        const usingAudio = useAudio();
        const { update_comment, get_comments, store } = useComment();
        const scrolled = ref(false);
        const container = ref<HTMLDivElement | null>(null)
        const instance = getCurrentInstance();
        const transfer = () => {
          let comments = get_comments(props.ref_id);
          return comments
              .filter(x => x.id !== props.comment?.id)
              .sort((a, b) => new Date(a.created_at).valueOf() - new Date(b.created_at).valueOf())
              .map(({content, ref_resources, ...rest}: Comment) => {
                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);
                return {content, info: rest, author: rest.created_by}
            });
        }
        const dataset = ref(transfer());

        watch(() => [store.comments, props.ref_id], () => {
          dataset.value = transfer();
        }, {deep: true})

        const contentInit = (comm: Comment) => {
          if (!comm) return;
          let {content, ref_resources} = comm;
          content = {...(content || {})};
          if (!content.audio) {
            content.audio = ref_resources?.find(r => r.resource_type === RefResourceTypes.Audio);
          }
          if (!content.video) {
            content.video = content.video || ref_resources?.find(r => r.resource_type === RefResourceTypes.Video);
          }
          if (!content.photos?.length) {
            content.photos = ref_resources?.filter(r => r.resource_type === RefResourceTypes.Picture);
          }
          comm.content = content
        }


        watch(() => props.comment, (cur, prev) => {
          // comment是单独的，它的内部字段变化不应该引起dataset的变化
          // 只有当comment本身发生变化（赋值/置空）才出发dataset变化
          // 否则在Android上输入文字时，会触发dataset变化，导致整个留言列表重新渲染，进而导致键盘消失
          dataset.value = transfer();
          if (cur && (!prev || cur !== prev)) {
            // 当初次赋值comment时，即弹出弹框时，如果是编辑之前已创建好的comment，需要初始化好媒体文件
            contentInit(cur)
          }
        })

        contentInit(props.comment)

        const cancel = async () => {
          let { photos, video } = props.comment.content
          let resources = (photos || []);
          if (video) {
            resources.push(video)
          }
          await MediaHelper.remove(resources)
          instance?.emit("remove")
        }

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

        const submit = async () => {
            await usingAudio.stopRecord();
            emit("submit")
        }

        const piyue = async (resource_note_group: ResourceNoteGroup) => {
          // update comment
          let comments = get_comments(props.ref_id);
          let index = comments.findIndex((c: Comment) => c.id === resource_note_group.ref_id);
          let comment = comments[index];
          comment.has_piyue = true;
          comment.resource_note_group = resource_note_group;
          await update_comment(comment)
        }

        onMounted(() => {
          let params = get_search_params();
          if (params) {
            let { comment_id, ref_id } = params;
            // if (comment_id || ref_id) {
            //   // scroll to specified comment when first auto popup from tongzhi
            //   if (!scrolled.value) {
            //
            //     let parent = container.value as HTMLDivElement;
            //     let child = document.getElementById(comment_id || ref_id);
            //     console.log(parent, child)
            //     if (child) {
            //       let distance = child.offsetTop - parent.offsetTop;
            //       parent.scroll(0, distance);
            //       console.log(distance)
            //     }
            //     scrolled.value = true;
            //   }
            // }
          }
        })

        return {
            can_save, submit, dataset, piyue, container, cancel
        }
    }
})

</script>

<style scoped lang="less">

    .container {
      //max-height: 100%;
      //height: 100%;
      //overflow-y: scroll;
    }

    .tool {
        padding: 0.16rem;
    }

    .footer {
        border-top: 1px solid #ddd;
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 100%;
        padding: 0.16rem 0.32rem;
    }
</style>
