<template>
  <div v-loading="loading" class="g-commit-list">
    <template v-for="(item, index) in commitList" :key="index">
      <Card simple class="g-commit-list-card overflow-hidden">
        <div class="g-commit-list-card-head flex items-center text-light px-20 gap-20">
          <Icon name="gt-commit" />{{ item.time }}
        </div>
        <CommitItem v-for="option in item.actions" :key="option.id" v-bind="option" :branch="props.branch" />
      </Card>
    </template>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue';
import dayjs from 'dayjs';
import type { Commit } from '@/components/CommitItem/type';

import CommitItem from '@/components/CommitItem/index.vue';

interface IProps {
  list: Array<Commit>;
  loadMore?: boolean;
  loadMoreText?: string;
  branch?: string;
  loading?:boolean;
}
const props = withDefaults(defineProps<IProps>(), {
  loadMoreText: ''
});

// @TODO
// 1. 前端将传入的commit数组，自动按照日期进行整合。如果后端能按日期提供数据，则需要调整代码逻辑
// 2. 此处暂未按照日期进行排序
const commitList = computed(() => {
  const timeMap = props.list.reduce((res: { [key: string]: any }, cur: Commit) => {
    const time = dayjs(cur.createTime || cur.created_at).format('YYYY-MM-DD');
    res[time] = res[time] || { time, actions: [] };
    const {
      id,
      title,
      message,
      id: repoId,
      authored_name: namespace,
      verification_status: statusText,
      committed_date: createTime,
      committer_avatar_url: userAvatar,
      author_name: username
    } = cur;
    const curItem = { ...cur, id, title, message, repoId, namespace, statusText, createTime, userAvatar, username };
    curItem.repoId = res[time]?.repoId;
    res[time].actions.push(curItem);
    return res;
  }, {});

  return Object.entries(timeMap).map(([, value]) => value);
});
</script>

<style lang="scss" scoped>
.g-commit-list {
  margin-bottom: 12px;
  :deep(.devui-icon__container) {
    vertical-align: middle;
  }
  &-card {
    margin-top: 12px;
    &:first-of-type {
      margin-top: 0;
    }
    &-head {
      height: 36px;
    }
  }
}
</style>
