<template>
    <div class="container-xxl flex-grow-1 container-p-y">

        <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"
        />
    </ul>

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

</div>

    </div>

</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';

    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 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;
            }
        })
    }
    //용어 등록
    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();
            }
        })
    };

</script>

<style scoped>

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

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