<template>
    <div class="container-xxl flex-grow-1 container-p-y">
        <!-- {{ userStore.user.role  == 'ROLE_ADMIN' ? '관리자' : '일반인'}} -->
        <div class="card p-5">
            <!-- 타이틀, 검색 -->
            <div class="row">
                <div class="col-12 col-md-6">
                    <h5 class="mb-0 title">용어집</h5>
                </div>
                <div class="col-12 col-md-6">
                    <SearchBar @update:data="search"/>
                </div>
            </div>

            <!-- 단어 갯수, 작성하기 -->
            <div class="mt-4">
                단어 : {{ total }}
                <WriteButton @click="toggleWriteForm" />
            </div>

            <!-- ㄱ ㄴ ㄷ ㄹ -->
            <div>
                <DictAlphabetFilter @update:data="handleSelectedAlphabetChange" />
            </div>

            <!-- 카테고리 -->
            <div v-if="cateList.length" class="mt-5">
                <CategoryBtn :lists="cateList" @update:data="handleSelectedCategoryChange"/>
            </div>

            <!-- 작성 -->
            <div v-if="isWriteVisible" class="mt-5">
                <DictWrite @close="isWriteVisible = false" :dataList="cateList" @addCategory="addCategory" @addWord="addWord"/>
            </div>
        </div>

        <!-- 용어 리스트 -->
        <div class="mt-10">
            <!-- 로딩 중일 때 -->
            <div v-if="loading">로딩 중...</div>

            <!-- 에러 메시지 -->
            <div v-if="error" class="error">{{ error }}</div>

            <!-- 단어 목록 -->
            <ul v-if="total > 0" class="px-0 list-unstyled">
                <DictCard
                    v-for="item in wordList"
                    :key="item.WRDDICSEQ"
                    :item="item"
                    :cateList="cateList"
                    @refreshWordList="getwordList"
                    @updateChecked="updateCheckedItems"
                />
            </ul>

            <!-- 데이터가 없을 때 -->
            <div v-else-if="!loading && !error" class="card p-5 text-center">용어집의 용어가 없습니다.</div>

        </div>

    </div>

    <button v-if="isAnyChecked" class="btn btn-danger admin-del-btn">
        <i class="bx bx-trash"></i>
    </button>

</template>

<script setup>
    import { ref, watchEffect, computed, onMounted, getCurrentInstance, toRaw } from 'vue';
    import axios from '@api';
    import SearchBar from '@c/search/SearchBar.vue';
    import WriteButton from '@c/button/WriteBtn.vue';
    import CategoryBtn from '@/components/category/CategoryBtn.vue';
    import DictCard from '@/components/wordDict/DictCard.vue';
    import DictWrite from '@/components/wordDict/DictWrite.vue';
    import DictAlphabetFilter from '@/components/wordDict/DictAlphabetFilter.vue';
    import commonApi from '@/common/commonApi';
    import { useToastStore } from '@s/toastStore';
    import { useUserInfoStore } from '@s/useUserInfoStore';

    // 유저 구분
    const userStore = useUserInfoStore();

    const { appContext } = getCurrentInstance();
    const $common = appContext.config.globalProperties.$common;

    const toastStore = useToastStore();

    // 공통
    const loading = ref(false);
    const error = ref('');

    // 용어집
    const wordList = ref([]);

    //용어집 총개수
    const total = ref(0);

    // 카테고리
    const { cateList } = commonApi({
        loadCateList: true
    });
    
    const selectedCategory = ref('');
    const selectCategory = ref('');

    // 체크박스 체크된 갯수
    const checkedItems = ref([]);
    // 체크박스의 name
    const checkedNames = ref([]); 


    //선택된 알파벳
    const selectedAlphabet = ref('');

    // 검색
    const searchText = ref('');

    // 작성
    const isWriteVisible = ref(false);

    // 데이터 로드
    onMounted(() => {
        getwordList();
    });

    //용어 목록
    const getwordList = (searchKeyword='', indexKeyword='', category='') => {
        axios.get('worddict/getWordList',{
            //목록조회시 파라미터 전달
            params: {
                        searchKeyword : searchKeyword,
                        indexKeyword :indexKeyword,
                        category : category
                    }
            })
            .then(res => {
                 // 용어 목록 저장
                wordList.value = res.data.data.data;
                 // 총 개수 저장
                total.value = res.data.data.total;
                loading.value = false;
            })
            .catch(err => {
                console.error('데이터 로드 오류:', err);
                error.value = '데이터를 가져오는 중 문제가 발생했습니다.';
                loading.value = false;
            });
    };

    // 검색
    const search = (e) => {
        searchText.value = e.trim();
        getwordList(searchText.value, selectedAlphabet.value, selectedCategory.value);
    };

    // 알파벳 선택
    const handleSelectedAlphabetChange = (newAlphabet) => {
        selectedAlphabet.value = newAlphabet;
        getwordList(searchText.value, selectedAlphabet.value,  selectedCategory.value);
    };

    // 카테고리 선택
    const handleSelectedCategoryChange = (category) => {
        selectedCategory.value = category;
        getwordList(searchText.value, selectedAlphabet.value, selectedCategory.value)
    }

    // 작성 toggle
    const toggleWriteForm = () => {
        isWriteVisible.value = !isWriteVisible.value;
    };

    //카테고리 등록
    const addCategory = (data) =>{
        const lastCategory = cateList.value[cateList.value.length - 1];
        const newValue = lastCategory  ? lastCategory.value + 1 : 600101;
        axios.post('worddict/insertCategory',{
            CMNCODNAM: data
        }).then(res => {
            if(res.data.data == '1'){
                toastStore.onToast('카테고리가 추가 등록 되었습니다.', 's');
                const newCategory = { label: data, value: newValue };
                cateList.value = [newCategory, ...cateList.value];
                selectedCategory.value = newCategory.value;
            } else if(res.data.message == '이미 존재하는 카테고리명입니다.') {
                toastStore.onToast(res.data.message, 'e');
            }
        })
    }
    //용어 등록
    const addWord = (wordData) => {
        axios.post('worddict/insertWord',{
            WRDDICCAT : wordData.category,
            WRDDICTTL : wordData.title,
            WRDDICCON : $common.deltaAsJson(wordData.content),
        }).then(res => {
            if(res.data.data == '1'){
                toastStore.onToast('용어가 등록 되었습니다.', 's');
                isWriteVisible.value = false;
                getwordList();
            }
        })
    };

    // 체크 상태 업데이트
    const updateCheckedItems = (checked, id, name) => {
        if (checked) {
            checkedItems.value.push(id);
            checkedNames.value.push(name);
        } else {
            checkedItems.value = checkedItems.value.filter(item => item !== id);
            checkedNames.value = checkedNames.value.filter(item => item !== name);
        }

        // 콘솔에 현재 체크된 name 값 출력
        console.log("현재 체크된 name 값:", checkedNames.value);
    };

    const isAnyChecked = computed(() => checkedItems.value.length > 0);

</script>

<style scoped>

.admin-del-btn {
    position: fixed;
    right: 1.5rem;
    bottom: 1.5rem;
    width: 3rem;
    height: 3rem;
}

.error {
    color: red;
    font-weight: bold;
}

@media (max-width: 768px) {
    .title {
        margin-bottom: 0.5rem !important;
    }
}
</style>
