<!--
  This example requires Tailwind CSS v2.0+

  This example requires some changes to your config:

  ```
  // tailwind.config.js
  module.exports = {
    // ...
    plugins: [
      // ...
      require('@tailwindcss/forms'),
    ],
  }
  ```
-->
<template>
    <form @submit.prevent="doCreate">
        <div class="sm:flex sm:items-center">
            <div class="sm:flex-auto">
                <h1 class="text-xl font-semibold text-gray-900">
                    {{ newTitle }}
                </h1>
                <p class="mt-2 text-sm text-gray-700">
                    {{ newDescription }}
                </p>
            </div>
            <div class="mt-4 sm:mt-0 sm:ml-16 sm:flex-none">
                <img
                    v-if="inPregressFlag"
                    width="32"
                    src="/loading-load-2.gif"
                />
            </div>
        </div>

        <div class="mt-2"></div>

        <TabGroup v-slot="{ selectedIndex }">
            <TabList class="flex items-center">
                <Tab v-slot="{ selected }" as="template">
                    <button
                        :class="[
                            selected
                                ? 'text-gray-900 bg-gray-100 hover:bg-gray-200'
                                : 'text-gray-500 hover:text-gray-900 bg-white hover:bg-gray-100',
                            'px-3 py-1.5 border border-transparent text-sm font-medium rounded-md',
                        ]"
                    >
                        입력
                    </button>
                </Tab>
                <Tab v-slot="{ selected }" as="template">
                    <button
                        :class="[
                            selected
                                ? 'text-gray-900 bg-gray-100 hover:bg-gray-200'
                                : 'text-gray-500 hover:text-gray-900 bg-white hover:bg-gray-100',
                            'ml-2 px-3 py-1.5 border border-transparent text-sm font-medium rounded-md',
                        ]"
                    >
                        미리보기
                    </button>
                </Tab>

                <!-- These buttons are here simply as examples and don't actually do anything. -->
                <div
                    v-if="selectedIndex === 0"
                    class="ml-auto flex items-center space-x-5"
                >
                    <div v-if="currentTarget == 'notice'">
                        <Listbox
                            v-model="labelled"
                            as="div"
                            class="flex-shrink-0"
                        >
                            <ListboxLabel class="sr-only">
                                Add a label
                            </ListboxLabel>
                            <div class="relative">
                                <ListboxButton
                                    class="relative inline-flex items-center rounded-full py-2 px-2 bg-gray-50 text-sm font-medium text-gray-500 whitespace-nowrap hover:bg-gray-100 sm:px-3"
                                >
                                    <TagIcon
                                        :class="[
                                            labelled.value === null
                                                ? 'text-gray-300'
                                                : 'text-gray-500',
                                            'flex-shrink-0 h-5 w-5 sm:-ml-1',
                                        ]"
                                        aria-hidden="true"
                                    />
                                    <span
                                        :class="[
                                            labelled.value === null
                                                ? ''
                                                : 'text-gray-900',
                                            'hidden truncate sm:ml-2 sm:block',
                                        ]"
                                        >{{
                                            labelled.value === null
                                                ? '라벨'
                                                : labelled.name
                                        }}</span
                                    >
                                </ListboxButton>

                                <transition
                                    leave-active-class="transition ease-in duration-100"
                                    leave-from-class="opacity-100"
                                    leave-to-class="opacity-0"
                                >
                                    <ListboxOptions
                                        class="absolute right-0 z-10 mt-1 w-52 bg-white shadow max-h-56 rounded-lg py-3 text-base ring-1 ring-black ring-opacity-5 overflow-auto focus:outline-none sm:text-sm"
                                    >
                                        <ListboxOption
                                            v-for="label in labels"
                                            :key="label.value"
                                            v-slot="{ active }"
                                            as="template"
                                            :value="label"
                                        >
                                            <li
                                                :class="[
                                                    active
                                                        ? 'bg-gray-100'
                                                        : 'bg-white',
                                                    'cursor-default select-none relative py-2 px-3',
                                                ]"
                                            >
                                                <div class="flex items-center">
                                                    <span
                                                        class="block font-medium truncate"
                                                    >
                                                        {{ label.name }}
                                                    </span>
                                                </div>
                                            </li>
                                        </ListboxOption>
                                    </ListboxOptions>
                                </transition>
                            </div>
                        </Listbox>
                    </div>
                </div>
            </TabList>
            <TabPanels class="mt-2">
                <TabPanel class="p-0.5 -m-0.5 rounded-lg">
                    <div
                        class="border border-gray-300 rounded-lg shadow-sm overflow-hidden focus-within:border-indigo-500 focus-within:ring-1 focus-within:ring-indigo-500"
                    >
                        <label for="title" class="sr-only">제목</label>
                        <input
                            id="title"
                            v-model="targetTitle"
                            type="text"
                            name="title"
                            class="block w-full border-0 pt-2.5 text-lg font-medium placeholder-gray-500 focus:ring-0"
                            placeholder="제목"
                        />
                        <label for="content" class="sr-only">내용</label>
                        <textarea
                            id="content"
                            v-model="targetContent"
                            rows="20"
                            name="content"
                            class="block w-full border-0 py-0 resize-none placeholder-gray-500 focus:ring-0 sm:text-sm"
                            placeholder="내용..."
                        />
                    </div>
                </TabPanel>
                <TabPanel class="p-0.5 -m-0.5 rounded-lg">
                    <div class="border-b">
                        <div
                            class="mx-px mt-px px-3 pt-2 pb-12 text-sm leading-5 text-gray-800"
                        >
                            <div v-if="currentTarget == 'notice'">
                                <BaseNoticeItem1 :item="previewItem" />
                            </div>
                            <div v-else>
                                <BaseFaqItem1 :item="previewItem" />
                            </div>
                        </div>
                    </div>
                </TabPanel>
            </TabPanels>
        </TabGroup>

        <div class="mt-2 flex justify-end">
            <button
                type="button"
                class="bg-white py-2 px-4 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                @click="doCancel"
            >
                취소
            </button>
            <button
                type="submit"
                class="ml-3 inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
            >
                저장
            </button>
        </div>
    </form>
</template>

<script setup>
import { Tab, TabGroup, TabList, TabPanel, TabPanels } from '@headlessui/vue';
import {
    Listbox,
    ListboxButton,
    ListboxLabel,
    ListboxOption,
    ListboxOptions,
} from '@headlessui/vue';
import { TagIcon } from '@heroicons/vue/24/solid';

const route = useRoute();

definePageMeta({
    middleware: 'check-auth-admin',
});

const labels = [
    { name: '라벨 없음', value: null },
    { name: '공지', value: 'notice' },
    { name: '이벤트', value: 'event' },
    // More items...
];
const labelled = ref(labels[0]);

const newTitle = ref('');
const newDescription = ref('');

const contentTitle = ref('');
const contentMessageGuide = ref('');

const currentTarget = ref('notice');

let actionTarget = 'notice';

const inPregressFlag = ref(false);

const targetTitle = ref('');
const targetContent = ref('');
const targetStatus = ref(0);

const today = new Date();
const targetCreated = today.toISOString();
// console.log('targetCreated=', targetCreated);

const previewItem = ref({ title: '', detail: '', created: targetCreated });

watch(targetTitle, (newValue, oldValue) => {
    previewItem.value =
        actionTarget == 'notice'
            ? {
                  hero: route.params.hero,
                  title: targetTitle.value,
                  detail: targetContent.value,
                  flags: labelled.value['value']
                      ? JSON.stringify([labelled.value['value']])
                      : JSON.stringify([]),
                  status: targetStatus.value,
                  created: targetCreated,
              }
            : {
                  hero: route.params.hero,
                  question: targetTitle.value,
                  answer: targetContent.value,
                  status: targetStatus.value,
                  created: targetCreated,
              };
});

watch(targetContent, (newValue, oldValue) => {
    previewItem.value =
        actionTarget == 'notice'
            ? {
                  hero: route.params.hero,
                  title: targetTitle.value,
                  detail: targetContent.value,
                  flags: labelled.value['value']
                      ? JSON.stringify([labelled.value['value']])
                      : JSON.stringify([]),
                  status: targetStatus.value,
                  created: targetCreated,
              }
            : {
                  hero: route.params.hero,
                  question: targetTitle.value,
                  answer: targetContent.value,
                  status: targetStatus.value,
                  created: targetCreated,
              };
});

watch(labelled, (newValue, oldValue) => {
    previewItem.value =
        actionTarget == 'notice'
            ? {
                  hero: route.params.hero,
                  title: targetTitle.value,
                  detail: targetContent.value,
                  flags: labelled.value['value']
                      ? JSON.stringify([labelled.value['value']])
                      : JSON.stringify([]),
                  status: targetStatus.value,
                  created: targetCreated,
              }
            : {
                  hero: route.params.hero,
                  question: targetTitle.value,
                  answer: targetContent.value,
                  status: targetStatus.value,
                  created: targetCreated,
              };
});

if (route.params.target instanceof Array) {
    if (route.params.target.length != 1) {
        throwError('$404');
    } else {
        if (
            route.params.target[0] != 'notice' &&
            route.params.target[0] != 'faq'
        ) {
            throwError('$404');
        } else {
            currentTarget.value = route.params.target[0];
            actionTarget = route.params.target[0];
            switch (route.params.target[0]) {
                case 'notice':
                    newTitle.value = '새 공지 작성';
                    newDescription.value =
                        '본문 중 html태그는 변환되어 저장되고 표시되므로 미리보기를 통해 의도한 대로 보여지는지 미리 확인해 주세요.';

                    contentTitle.value = '공지 제목';
                    contentMessageGuide.value = '공지 내용';

                    break;
                case 'faq':
                    newTitle.value = '새 FAQ 작성';
                    newDescription.value =
                        '본문 중 html태그는 변환되어 저장되고 표시되므로 미리보기를 통해 의도한 대로 보여지는지 미리 확인해 주세요.';

                    contentTitle.value = '질문';
                    contentMessageGuide.value = '답변';

                    break;
            }
        }
    }
} else {
    throwError('$404');
}
const router = useRouter();
async function doCancel() {
    if (inPregressFlag.value == true) {
        alert('이전 동작이 아직 진행중입니다.');
        return;
    }

    router.back();
}

async function doCreate() {
    if (inPregressFlag.value == true) {
        alert('이전 동작이 아직 진행중입니다.');
        return;
    }

    if (targetTitle.value == '' || targetContent.value == '') {
        alert('내용을 입력하셔야 합니다. ');
        return;
    }

    inPregressFlag.value = true;

    const responseJson = await _crossCtl.doComm(
        'insert',
        actionTarget,
        actionTarget == 'notice'
            ? {
                  hero: route.params.hero,
                  title: targetTitle.value,
                  detail: targetContent.value,
                  flags: labelled.value['value']
                      ? JSON.stringify([labelled.value['value']])
                      : JSON.stringify([]),
                  status: targetStatus.value,
                  created: targetCreated,
              }
            : {
                  hero: route.params.hero,
                  question: targetTitle.value,
                  answer: targetContent.value,
                  status: targetStatus.value,
                  created: targetCreated,
              }
    );
    inPregressFlag.value = false;
    if (responseJson['responseMessage'] == 'ok') {
        alert('ok');
    } else {
        alert('오류 : ' + responseJson['responseMessage']);
    }
}
</script>
