<template>
    <div class="d-flex">
        <FormSelect name="cate"
                    title="카테고리"
                    :data="formattedDataList"
                    :is-common="true"
                    @update:data="selectCategory = $event"
        />        <button @click="toggleInput">+</button>
        <div class="d-flex" v-if="showInput">
            <FormInput :isLabel="false" title="카테고리" name="카테고리"  @update:modelValue="addCategory = $event" :is-alert="addCategoryAlert"/>
            <button @click="saveInput">저장</button>
        </div>
    </div>
    <div>
        <FormInput
                title="용어"
                type="text"
                name="word"
                :is-essential="true"
                :is-alert="wordTitleAlert"
                @update:modelValue="wordTitle = $event"
            />    </div>
    <div>
        <QEditor @update:data="content = $event" @update:imageUrls="imageUrls = $event"  :is-alert="true" />
        <button @click="saveWord">저장</button>
        <button @click="$emit('close')">취소</button>
    </div>
</template>

<script setup>
import { defineProps, computed, ref, defineEmits } from 'vue';

import QEditor from '@/components/editor/QEditor.vue';
import FormInput from '@/components/input/FormInput.vue';
import FormSelect from '@/components/input/FormSelect.vue';

const emit = defineEmits(['close','addCategory','addWord']);

//용어제목
const wordTitle =ref('');
const addCategory =ref('');
const content = ref('');
const imageUrls = ref([]);

//용어 Vaildation용
const wordTitleAlert = ref(false);
const addcateAlert =ref(false);
const addCategoryAlert = ref(false);
//선택 카테고리
const selectCategory = ref('');

const props = defineProps({
    dataList: {
        type: Array,
        default: () => []
    }
});

// 데이터 포맷 수정
const formattedDataList = computed(() =>
    props.dataList.map(item => ({
        label: item.CMNCODNAM,
        value: item.CMNCODVAL
    }))
);

// 카테고리 입력 창
const showInput = ref(false);

// 카테고리 입력 토글
const toggleInput = () => {
    showInput.value = !showInput.value;
};

// 카테고리 저장
const saveInput = () => {
    if( addCategory.value == ''){
        addCategoryAlert.value = true;
        return;
    }
    console.log('입력값 저장됨!',addCategory.value);
    emit('addCategory', addCategory.value);
    showInput.value = false;
};

//용어 등록
const saveWord = () => {
    //validation 체크후 emit전송 수정해야함

    const wordData = {
        title: wordTitle.value,
        category: selectCategory.value,
        content: content.value,
    };
    emit('addWord', wordData);
};
</script>
