<template>
  <div v-if="notes.length">
    <FileDiffDiscussionsItemNote
      v-for="(note, index) in notes"
      :key="note.id"
      :note="note"
      :discussion="props.discussion"
      :isFirstNote="index === 0"
      @onDelNote="onDelNote"
    />
    <!-- 回复 -->
    <div v-if="canComment && !showReplayMD" class="flex items-center py-4 pl-8">
      <GAvatar
        :src="accountInfo?.avatar"
        :name="accountInfo?.nickname"
        :width="20"
        :height="20"
      ></GAvatar>
      <Input
        class="ml-2 mr-4"
        @click="
          showReplayMD = true;
          replayText = '';
        "
        placeholder="回复..."
      ></Input>
    </div>
    <div v-if="canComment && showReplayMD" class="px-11 mt-4">
      <EditorMd v-model="replayText" class="mb-4"></EditorMd>
      <div class="flex justify-end">
        <Button
          @click="submitNote"
          :disabled="!replayText?.trim()"
          variant="solid"
          class="mb-4"
          color="primary"
          >确定</Button
        >
        <Button @click="showReplayMD = false" class="ml-2 mb-4" color="primary">取消</Button>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, reactive, toValue, inject, computed } from 'vue';
import { Button } from 'vue-devui/button';
import { Input } from 'vue-devui/input';
import GAvatar from '@/components/GAvatar/index.vue';
import { EditorMd } from 'vue-devui/editor-md';
import { postNote } from '@/api/merge/index';
import { repoInfoStore } from '@/stores/Repo';
import { escapeResData } from '@/utils';
import FileDiffDiscussionsItemNote from './FileDiffDiscussionsItemNote.vue';
const repoId = inject('repoId');
const iid = inject('iid');
const arts_id = inject('arts_id');
const accountInfo = inject('accountInfo');
const onMergeAble = inject('onMergeAble');
const onDelHeadNote = inject('onDelHeadNote');
const { isPrivate, isVisitor } = repoInfoStore();
const canComment = computed(() => {
  if (isPrivate) return isVisitor;
  else return !!arts_id;
});

const props = defineProps({
  discussion: {
    type: Object,
    default: () => ({})
  }
});

const onDelNote = (id) => {
  notes.value = notes.value.filter((m) => m.id !== id);
  if (!notes.value.length) {
    onMergeAble();
    onDelHeadNote(props.discussion.id);
  }
};

const showReplayMD = ref(false);
const replayText = ref('');
const notes = ref(props.discussion.notes);
const submitNote = () => {
  showReplayMD.value = false;
  postNote(
    reactive({
      repoId: repoId,
      iid: iid,
      disId: props.discussion.id,
      //
      body: replayText.value,
      severity: 'suggestion',
      assignee_id: arts_id
    })
  )
    .then((res) => {
      const data = escapeResData(res);
      if (data.id) {
        notes.value = [...notes.value, data];
      }
      //
    })
    .catch((error) => {});
};

onMounted(() => {});
</script>

<style scoped lang="scss">
@import 'devui-theme/styles-var/devui-var.scss';
</style>
