<template>
    <div v-if="data.voteMembers.some(item => item.MEMBERSEQ === userStore.user.id)"
        class="card mb-6"  :class="{ 'disabled-class': data.localVote.LOCVOTDDT  && (topVoters.length == 1 || data.localVote.LOCVOTRES || voteResult == 0)}">
        <div  class="card-body" v-if="!data.localVote.LOCVOTDEL" >
            <h5 class="card-title mb-1">
                <div class="list-unstyled users-list d-flex align-items-center gap-1">
                    <img
                    class="rounded-circle user-avatar border border-3 w-px-40 h-px-40"
                    :src="`${baseUrl}upload/img/profile/${data.localVote.MEMBERPRF}`"
                    :style="`border-color: ${data.localVote.usercolor} !important;`"
                    @error="$event.target.src = '/img/icons/icon.png'"
                    alt="user"
                    />
                    <div class="w-100">
                        <div class="d-flex justify-content-between">
                            <div class="user-info">
                                <h6 class="mb-1">{{ data.localVote.MEMBERNAM }}</h6>
                                <!-- 투표완료시  -->
                            </div>
                            <div class="add-btn d-flex align-items-center">
                                <!-- 투표작성자만 수정/삭제/종료 가능  -->
                                <div v-if="userStore.user.id === data.localVote.LOCVOTREG">
                                    <button
                                    v-if="!data.localVote.LOCVOTDDT"
                                    type="button"
                                    class="btn btn-label-danger btn-icon m-1"
                                    @click="endBtn(data.localVote.LOCVOTSEQ)"
                                    ><i class="bx bx-power-off"></i>
                                    </button>
                                    <DeleteBtn v-if="!data.localVote.LOCVOTDDT" @click="voteDelete(data.localVote.LOCVOTSEQ)" />
                                </div>
                                <p v-if="data.localVote.LOCVOTDDT" class="btn-icon btn-danger rounded-2"><i class="bx bx-power-off"></i></p>
                            </div>
                        </div>
                    </div>
                </div>
            </h5>
            <h5 class="mb-1">{{ data.localVote.LOCVOTTTL }}
                <i v-if="yesVotetotal != '0'" class="bx bxs-check-circle link-success"></i>
            </h5>
            <small >{{ data.localVote.formatted_LOCVOTRDT }} ~ {{ data.localVote.formatted_LOCVOTEDT }}</small>
            <!-- 투표안했을시-->
            <div v-if="data.localVote.LOCVOTDDT && voteResult == 0">
                <small class="text-primary text-uppercase">투표 결과없음 (😂아무도 투표하지 않았습니다)</small>
            </div>
            <div v-else>
                <vote-card-check
                v-if="yesVotetotal == 0 && !data.localVote.LOCVOTDDT"
                @addContents="addContents"
                @checkedNames="checkedNames"
                :data="data.voteDetails"
                :voteInfo="data.localVote"
                :total="data.voteDetails.length "/>
                <small v-if="yesVotetotal != 0 && !data.localVote.LOCVOTDDT">투표 완료 : 종료시 투표 결과가 나타납니다.</small>
                <!-- 투표 결과 -->
                <div v-if="data.localVote.LOCVOTDDT" class="mt-3">
                    <vote-result-list  :data="topVoters"  @randomList="randomList" :randomResultNum="data.localVote.LOCVOTRES" :locvotreg="data.localVote.LOCVOTREG"/>
                </div>
                <!-- 투표완/미완 인원 -->
                <vote-user-list
                :data="data.voteMembers"/>
            </div>
        </div>
        <div v-else  class="card-body">
            <h5>{{ data.localVote.LOCVOTTTL }}</h5>
            삭제된 투표입니다.
        </div>
    </div>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue'
import EditBtn from '@c/button/EditBtn.vue';
import DeleteBtn from '@c/button/DeleteBtn.vue';
import voteUserList from '@c/voteboard/voteUserList.vue';
import voteResultList from '@c/voteboard/voteResultList.vue';
import voteCardCheck from '@c/voteboard/voteCardCheck.vue';
import { useUserInfoStore } from '@s/useUserInfoStore';
import $api from '@api';

const props = defineProps({
    data: {
        type: Object,
        required: true,
    },
    randomresult: {
        type: Boolean,
        required: false,
    },
});
const voteResult = computed(() => {
    return props.data.voteDetails.reduce((sum, item) => sum + item.VOTE_COUNT, 0);
});
const yesVotetotal = computed(() => {
    return props.data.voteDetails.reduce((sum, item) => sum + item.yesvote, 0);
});


 // 가장 많은 투표를 받은 항목들 (1위)
const topVoters = computed(() => {
    // 가장 높은 VOTE_COUNT 찾기
    const maxVoteCount = Math.max(...props.data.voteDetails.map(item => item.VOTE_COUNT));
    // VOTE_COUNT가 가장 높은 항목들 필터링
    return props.data.voteDetails.filter(item => item.VOTE_COUNT === maxVoteCount);
});

const baseUrl = $api.defaults.baseURL.replace(/api\/$/, '');
const userStore = useUserInfoStore();
const currentDate = new Date();
const voteEndDate = new Date(props.data.localVote.formatted_LOCVOTEDT.replace(' ', 'T'));
voteEndDate.setDate(voteEndDate.getDate() + 1);
// 종료 여부 계산
const isVoteEnded = computed(() => {
    return currentDate > voteEndDate;
});
const emit = defineEmits(['addContents','checkedNames','endVoteId','voteEnded','randomList','voteDelete','updateVote']);
onMounted(() => {
    if (isVoteEnded.value && !props.data.localVote.LOCVOTDDT) {
    emit('voteEnded', { id: props.data.localVote.LOCVOTSEQ });
    }
});
const addContents = (itemList, voteId) =>{
    emit('addContents',itemList,voteId)
}
const checkedNames = (numList) =>{
    emit('checkedNames',numList);
}
const endBtn = (voteid) =>{
    voteEndDate.setTime(currentDate.getTime()); // 현재 날짜로 설정
    emit('endVoteId',voteid);
}
const voteDelete = (voteid) =>{
    emit('voteDelete',voteid);
}
const randomList = (random) =>{
    emit('randomList',random,props.data.localVote.LOCVOTSEQ);
}
const updateVote = (voteid) =>{
    emit('updateVote',voteid);
}
</script>

<style scoped>
.disabled-class {
    pointer-events: none; /* 클릭 방지 */
    opacity: 0.5; /* 흐리게 표시 */
}
</style>
