<template>
  <DiscussionItem
    v-bind="$props"
    :eventIcon="eventIcon === undefined ? 'gt-comment' : eventIcon"
    :data="data"
    :origin="origin"
    :body="temp?.body"
    :repo-id="repoId"
    @save-content="saveDescription"
    :can-delete="author?.username === user?.username"
    :can-edit="author?.username === user?.username"
    :loading="loading"
    :targetId="temp?.iid"
    @on-remove="handleDelete"
    @quote-reply="$emit('quote-reply', temp?.body)"
    @reply-discussion="handleReply"
    :resolvable="temp.resolvable"
    :resolved="resolvable === false ? false : temp.resolved"
    @resolve-stat-change="resolveStatChange"
    :event-msg="hasDiff ? undefined : '评论：'"
    :diff="hasDiff ? temp.diff : ''"
    :diffFile="hasDiff ? temp.diff_file : ''"
    :addedLines="hasDiff ? origin.added_lines : undefined"
    :removedLines="hasDiff ? origin.removed_lines : undefined"
    :sourceBranch="sourceBranch"
    :formatIng="formatIng"
    @doFormat="doFormat"
    :hasDiff="hasDiff"
    :canResolve="canResolve"
    ref="RefDiscussion"
  >
    <slot></slot>
  </DiscussionItem>
</template>
<script lang="ts" setup>
defineOptions({ name: 'MrDiscussionItem' });
import { ref, computed, inject, type Ref } from 'vue';
import DiscussionItem from '@/views/Repo/components/DiscussionItem/index.vue';
import {
  updateMRDiscussion,
  delMRDiscussionsNote,
  replayDiscussionsNote,
  changes
} from '@/api/merge';
import { reqCatch } from '@/utils/catch';
import debounce from 'lodash/debounce';
import { repoInfoStore } from '@/stores/Repo';
const { isDeveloper } = repoInfoStore();
const isMrAuthor = inject('isMrAuthor') as Ref;
const mrInfo = inject('mrInfo') as Ref;
const repoId = inject('repoId') as Ref;
const iid = inject('iid') as number;
const mergeAbleChange = inject('mergeAbleChange') as Function;
const updatePage = inject('updatePage') as Function;
const props = defineProps<{
  data: any;
  origin: any;
  hasDiff?: boolean;
  eventIcon?: string;
  author: any;
  user: any;
  resolvable?: any;
}>();
const key = ref(0);
const RefDiscussion = ref();
const loading = ref(false);
const formatIng = ref(false);
const temp = ref(props.data);
const sourceBranch = computed(() => mrInfo.value?.source_branch);

/**
 * 1、建议级别：MR作者、评论者、开发者及以上权限可操作。
 * 2、一般及以上级别：评论者、开发者及以上权限可操作，MR作者不可操作，即使有以上权限也不行。
 */
const canResolve = computed(() => {
  if (mrInfo.value?.author?.username !== props.author?.username) {
    return false;
  } else if (isDeveloper) {
    return true;
  } else {
    return false;
  }
});

const emit = defineEmits<{
  'delete': [];
  'quote-reply': [value: string];
  'add-reply': [obj: object];
}>();

/**
 * 修改评论
 */
const saveDescription = async(str: string) => {
  loading.value = true;
  const res = await reqCatch(updateMRDiscussion, {
    project_id: repoId.value,
    merge_request_iid: iid,
    discussion_id: props.origin.id,
    body: str
  });
  loading.value = false;
  if (!res.error) {
    temp.value.body = str;
    key.value++;
    RefDiscussion.value.reset();
  }
};

/**
 * 修改问题解决状态
 */
const resolveStatChange = debounce(async(blod: boolean) => {
  const res = await reqCatch(updateMRDiscussion, {
    project_id: repoId.value,
    merge_request_iid: iid,
    discussion_id: props.origin.id,
    resolved: blod
  });

  if (!res.error) {
    temp.value = res.data.data.notes[0];
    mergeAbleChange();
    updatePage();
  }
}, 500);

/**
 * 删除评论
 */
const handleDelete = async() => {
  const res = await reqCatch(delMRDiscussionsNote, {
    project_id: repoId.value,
    merge_request_iid: iid,
    note_id: props.data.id
  });

  if (!res.error) {
    emit('delete');
  }
};

/**
 * 回复
 */
const handleReply = async(str: string) => {
  const res = await reqCatch(replayDiscussionsNote, {
    project_id: repoId.value,
    merge_request_iid: iid,
    discussion_id: props.origin.id,
    body: str
  });

  if (!res.error) {
    const msg = res.data.data;
    RefDiscussion.value.reset();
    key.value++;
    emit('add-reply', msg);
  }
};

/**
 * 转码
 */
const doFormat = async() => {
  formatIng.value = true;
  const res = changes({
    file_path: sourceBranch,
    ignore_whitespace_change: false,
    view: 'simple',
    force_encode: true,
    repoId: repoId.value,
    iid: iid
  });
  formatIng.value = false;
};
</script>
