<template>
    <a-drawer :visible="props.visible" class="drawer" width="520px" v-if="status" @cancel="closeChangeBranch"
    placement="left" :footer="false">
    <template #title><icon-swap /> 切换分支</template>
    <a-list hoverable>
        <a-list-item v-for="(item, index) in props.status.branches" :key="index">
            <div class="branch-list">
                <div class="icon">
                    <icon-branch :size="25" />
                </div>
                <div class="info">
                    <span class="title">
                        {{ item.name }}
                    </span>
                    <span class="label">
                        <a-tag size="small">{{ item.commit }}</a-tag>
                        {{ item.label }}
                    </span>
                </div>
                <div class="button">
                    <a-button type="primary" size="small" v-if="item.name !== status.status.current"
                        @click="ChangeBranch(item.name)">切换</a-button>
                    <a-button type="text" size="small" v-else>当前</a-button>
                </div>
            </div>
        </a-list-item>
    </a-list>
</a-drawer>
</template>

<script setup>
import { Notification, Message } from '@arco-design/web-vue'
import { useRepoStore } from '@/store'
import { eventBus } from '@/utils/eventBus'

const repoStore = useRepoStore()
const props = defineProps({
    id: {
        type: Number
    },
    visible: {
        type: Boolean,
        default: false
    },
    status: {
        type: Object
    }
})

const emit = defineEmits(['changeBegin', 'changeFail', 'close'])

const ChangeBranch = async (branch) => {
    try {
        emit('changeBegin')
        emit('close')
        await repoStore.ChangeBranch(props.id, branch )
        Message.success(`已切换至分支 ${branch}`)
        eventBus.emit('changeOK')
    } catch (error) {
        console.error(error)
        Notification.error({
            title: '切换仓库分支失败！',
            content: error.message || '请稍后再试'
        })
        emit('changeFail')
    } 
}

const closeChangeBranch = () => {
    emit('close')
}

</script>

<style lang="less" scoped>
.branch-list {
    display: flex;
    min-height: 60px;
    align-items: center;

    .info {
        display: flex;
        flex-direction: column;
        margin-left: 15px;
        margin-right: 15px;


        .title {
            font-size: 1.3em;
        }
    }

    .button {
        margin-left: auto;
    }
}
</style>