<template>
  <div class="user-follow-list">
      <user-item
        v-for="(item, index) in data"
        :key="`${item.id}_${index}`"
        :data="item"
        :loading="item.loading"
        :show-button="showButton"
        :is-first="index === 0"
        :is-last="index === data.length - 1"
        :keywords="keywords"
        @starred="onToggle($event, item)"
      />
  </div>
</template>

<script lang="ts">
export default {
  name: 'user-follow-list'
};
</script>

<script setup lang="ts">
import UserItem from '@/components/UserItem/index.vue';
import type { FollowUserData } from '@/views/User/components/types';
import { followUser, unfollowUser } from '@/api/user';
import { joinCommunity, unJoinCommunity } from '@/api/org/devIndex';
import { Message } from 'vue-devui/message';
import { useUserInfo } from '@/views/User/hooks/useUserInfo';

withDefaults(defineProps<{
  data: FollowUserData[];
  showButton?: boolean;
  keywords?: string
}>(), {
  data: () => ([]),
  showButton: true,
  keywords: ''
});

const emits = defineEmits<{(e: 'refresh'): void
}>();

const { namespace } = useUserInfo();
const username = useUserInfo().userInfo.username || '';
const onToggle = (follow: boolean, data: FollowUserData) => {
  if (data.loading) return false;
  data.loading = true;
  if (follow) {
    if (data.followType === 0) { // 关注用户
      followUser({ username: namespace || username, followedUsername: data.username, followType: data.followType || 0 })
        .then(() => {
          Message({ type: 'success', message: '关注成功' });
          emits('refresh');
        })
        .finally(() => {
          data.loading = false;
        });
    } else if (data.followType === 1) { // 关注组织
      joinCommunity({ followType: 1, followedUsername: data.username })
        .then(() => {
          emits('refresh');
        })
        .finally(() => {
          data.loading = false;
        });
    }
  } else {
    if (data.followType === 0) { // 取消关注用户
      unfollowUser({ username: namespace, unfollowUsername: data.username, followType: data.followType || 0 })
        .then(() => {
          Message({ type: 'success', message: '取消关注成功' });
          emits('refresh');
        })
        .finally(() => {
          data.loading = false;
        });
    } else if (data.followType === 1) { // 取消关注组织
      unJoinCommunity({ followType: 1, unfollowUsername: data.username })
        .then(() => {
          emits('refresh');
        })
        .finally(() => {
          data.loading = false;
        });
    }
  }
};

</script>

<style scoped lang="scss">
.user-follow-list {
  box-shadow: 0 0 5px 0 rgba(0,0,0,0.1);
  border-radius: 3px;
  overflow: hidden;
  background-color: #fff;
}
</style>
