<template>
    <div class="m-0">
        <form
            class="space-y-8 divide-y divide-gray-200"
            @submit.prevent="doUpdate"
        >
            <div class="space-y-8 divide-y divide-gray-200 sm:space-y-5">
                <div
                    class="divide-y divide-gray-200 pt-0 space-y-6 sm:pt-0 sm:space-y-5"
                >
                    <div class="sm:flex sm:items-center">
                        <div class="sm:flex-auto">
                            <h1 class="text-xl font-semibold text-gray-900">
                                API 키 상세 보기
                            </h1>
                            <p class="mt-2 text-sm text-gray-700">
                                API키의 설정을 변경하거나 삭제할 수 있습니다.
                            </p>
                        </div>
                        <img
                            v-if="inPregressFlag"
                            width="32"
                            src="/loading-load-2.gif"
                        />
                        <div class="mt-4 sm:mt-0 sm:ml-16 sm:flex-none">
                            <button
                                type="button"
                                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"
                                @click="gotoStatistics()"
                            >
                                사용 통계
                            </button>
                            <button
                                type="button"
                                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"
                                @click="gotoWordStatistics()"
                            >
                                단어 통계
                            </button>
                        </div>
                    </div>

                    <div
                        class="sm:grid sm:grid-cols-3 sm:gap-4 sm:items-start sm:border-t sm:border-gray-200 sm:pt-5"
                    >
                        <label
                            for="name"
                            class="block text-sm font-medium text-gray-700 sm:mt-px sm:pt-2"
                        >
                            이름
                        </label>
                        <div class="mt-1 sm:mt-0 sm:col-span-2">
                            <input
                                id="name"
                                v-model="name"
                                type="text"
                                name="name"
                                autocomplete="name"
                                class="max-w-lg block w-full shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:max-w-xs sm:text-sm border-gray-300 rounded-md"
                            />
                        </div>
                    </div>
                    <div
                        class="sm:grid sm:grid-cols-3 sm:gap-4 sm:items-start sm:border-t sm:border-gray-200 sm:pt-5"
                    >
                        <label
                            for="api-key"
                            class="block text-sm font-medium text-gray-700 sm:mt-px sm:pt-2"
                        >
                            API 키
                        </label>
                        <div class="mt-1 sm:mt-0 sm:col-span-2">
                            <input
                                id="api-key"
                                v-model="apiKey"
                                type="text"
                                name="api-key"
                                autocomplete="api-key"
                                disabled
                                class="max-w-lg block w-full shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:max-w-xs sm:text-sm border-gray-300 rounded-md"
                            />
                        </div>
                    </div>

                    <div
                        class="space-y-6 sm:space-y-5 divide-y divide-gray-200"
                    >
                        <div class="pt-6 sm:pt-5">
                            <div
                                role="group"
                                aria-labelledby="label-notifications"
                            >
                                <div
                                    class="sm:grid sm:grid-cols-3 sm:gap-4 sm:items-baseline"
                                >
                                    <div>
                                        <div
                                            id="label-notifications"
                                            class="text-base font-medium text-gray-900 sm:text-sm sm:text-gray-700"
                                        >
                                            필터 단계
                                        </div>
                                    </div>
                                    <div class="sm:col-span-2">
                                        <div class="max-w-lg">
                                            <p class="text-sm text-gray-500">
                                                필터 대상이 되는 단계를
                                                선택합니다. (현재는 최대 필터만
                                                동작)
                                            </p>
                                            <div class="mt-4 space-y-4">
                                                <div class="flex items-center">
                                                    <input
                                                        id="filter-high"
                                                        v-model="level"
                                                        value="high"
                                                        name="filter-level"
                                                        type="radio"
                                                        class="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300"
                                                    />
                                                    <label
                                                        for="filter-high"
                                                        class="ml-3 block text-sm font-medium text-gray-700"
                                                    >
                                                        최대 필터
                                                    </label>
                                                </div>
                                                <div class="flex items-center">
                                                    <input
                                                        id="filter-mid"
                                                        v-model="level"
                                                        value="mid"
                                                        name="filter-level"
                                                        type="radio"
                                                        disabled
                                                        class="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300"
                                                    />
                                                    <label
                                                        for="filter-mid"
                                                        class="ml-3 block text-sm font-medium text-gray-700"
                                                    >
                                                        중간 필터
                                                    </label>
                                                </div>
                                                <div class="flex items-center">
                                                    <input
                                                        id="filter-low"
                                                        v-model="level"
                                                        value="low"
                                                        name="filter-level"
                                                        type="radio"
                                                        disabled
                                                        class="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300"
                                                    />
                                                    <label
                                                        for="filter-low"
                                                        class="ml-3 block text-sm font-medium text-gray-700"
                                                    >
                                                        가장 가벼운 필터
                                                    </label>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pt-5">
                <div class="flex justify-between">
                    <div>
                        <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="doDelete"
                        >
                            {{ status == 0 ? '삭제' : '복구' }}
                        </button>
                    </div>
                    <div>
                        <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
                            v-if="status == 0"
                            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>
                </div>
            </div>
            <div class="divide-y divide-gray-200 space-x-8"></div>
        </form>

        <form
            class="space-y-6 pt-8 sm:pt-10 divide-y divide-gray-200"
            @submit.prevent="doFilter"
        >
            <div class="space-y-8 divide-y divide-gray-200 sm:space-y-5">
                <div>
                    <div class="sm:flex sm:items-center">
                        <div class="sm:flex-auto">
                            <h1 class="text-xl font-semibold text-gray-900">
                                필터 테스트
                            </h1>
                            <p class="mt-2 text-sm text-gray-700">
                                입력된 문장을 api를 이용해 검사하고 그 결과를
                                표시합니다.
                            </p>
                        </div>
                        <img
                            v-if="inPregressFlag"
                            width="32"
                            src="/loading-load-2.gif"
                        />
                        <div class="mt-4 sm:mt-0 sm:ml-16 sm:flex-none">
                            <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>
                    </div>

                    <div class="mt-6 sm:mt-5 space-y-6 sm:space-y-5">
                        <div>
                            <fieldset class="mt-4">
                                <legend class="sr-only">Filter Mode</legend>
                                <div class="space-y-4">
                                    <div
                                        v-for="notificationMethod in notificationMethods"
                                        :key="notificationMethod.id"
                                        class="flex items-center"
                                    >
                                        <input
                                            :id="notificationMethod.id"
                                            v-model="filterMode"
                                            :value="notificationMethod.id"
                                            name="notification-method"
                                            type="radio"
                                            class="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300"
                                        />
                                        <label
                                            :for="notificationMethod.id"
                                            class="ml-3 block text-sm font-medium text-gray-700"
                                        >
                                            {{ notificationMethod.title }}
                                        </label>
                                    </div>
                                </div>
                            </fieldset>
                        </div>

                        <div
                            class="sm:grid sm:grid-cols-3 sm:gap-4 sm:items-start sm:border-t sm:border-gray-200 sm:pt-5"
                        >
                            <label
                                for="filterText"
                                class="block text-sm font-medium text-gray-700 sm:mt-px sm:pt-2"
                            >
                                검사할 문장 입력
                            </label>
                            <div class="mt-1 sm:mt-0 sm:col-span-2">
                                <textarea
                                    id="filterText"
                                    v-model="filterText"
                                    name="filterText"
                                    rows="3"
                                    class="max-w-lg shadow-sm block w-full focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm border border-gray-300 rounded-md"
                                />
                                <p class="mt-2 text-sm text-gray-500">
                                    필터 테스트를 위한 문장을 입력하고 아래
                                    검사하기 버튼을 누르세요. <br />
                                    (마지막 실행시간
                                    {{ elispe.toFixed(2) }} 밀리초)
                                </p>
                                <pre>{{ resultJson }}</pre>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pt-5">
                <div class="flex justify-end"></div>
            </div>
        </form>
    </div>
</template>
<script setup lang="ts">
const route = useRoute();
const router = useRouter();
definePageMeta({
    middleware: 'check-auth-op',
});

const hero = route.params.hero;

console.log('hero=', hero);

const apiKey = ref('');
const name = ref('');
const level = ref('');
const status = ref(0);

const notificationMethods = [
    {
        id: 'quick',
        title: 'mode = quick. 첫번째 매칭이 발견되면 더 이상 검사하지 않고 바로 결과를 리턴',
    },
    { id: 'normal', title: 'mode = normal. 전체를 검사하여 모든 매칭을 리턴' },
    {
        id: 'filter',
        title: 'mode = filter. 전체를 검사하며 모든 매칭을 마스크로 치환한 결과까지 리턴',
    },
];

const filterText = ref('테스트할 문장을 여기에 입력해 주세요.');

const filterMode = ref('filter');

const filterCallback = ref('');

const resultJson = ref({});

const elispe = ref(0);

const inPregressFlag = ref(false);

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

    const startTime = performance.now();

    const responseJson = await _crossCtl.doFilterRaw(apiKey.value, {
        text: filterText.value,
        mode: filterMode.value,
    });

    const endTime = performance.now();

    inPregressFlag.value = false;

    elispe.value = endTime - startTime;

    // console.log('responseJson=', responseJson);
    const result = responseJson;
    resultJson.value = result;

    if (responseJson['Status']['Code'] == 2000) {
        // alert(result.length + ' match found');
    } else {
        alert(responseJson['Status']['Message']);
    }
}

function gotoStatistics() {
    navigateTo('/key/' + hero + '/statistics');
}

function gotoWordStatistics() {
    navigateTo('/word/' + hero + '/statistics');
}

const responseJson = await _crossCtl.doComm('local/select', 'key', {
    hero: hero,
});

if (responseJson['data'].length == 0) {
    _crossCtl.openModal(
        'error',
        '잘못된 파라메타',
        '키 정보를 읽어올 수 없습니다.\n확인 버튼을 누르면 메인 화면으로 돌아갑니다.',
        ['확인'],
        (btnIdx) => {
            navigateTo('/');
        }
    );
} else {
    const keyInfo = responseJson['data'][0];

    apiKey.value = keyInfo['api_key'];
    name.value = keyInfo['name'];
    level.value = keyInfo['level'];
    status.value = keyInfo['status'];
}

async function doUpdate() {
    const responseJson = await _crossCtl.doComm('local/update', 'key', {
        hero: hero,
        name: name.value,
        level: level.value,
        status: status.value,
    });
    console.log('responseJson=', responseJson);
    if (responseJson['responseMessage'] == 'ok') {
        alert('ok');
    } else {
        alert(responseJson['responseMessage']);
    }
}

async function doDelete() {
    if (status.value == 0) {
        const responseJson = await _crossCtl.doComm('local/delete', 'key', {
            hero: hero,
        });
        console.log('responseJson=', responseJson);
        if (responseJson['responseMessage'] == 'ok') {
            status.value = 4;
            alert('ok');
        } else {
            alert(responseJson['responseMessage']);
        }
    } else {
        const responseJson = await _crossCtl.doComm('local/update', 'key', {
            hero: hero,
            name: name.value,
            level: level.value,
            revive: true,
            status: 0,
        });
        console.log('responseJson=', responseJson);
        if (responseJson['responseMessage'] == 'ok') {
            status.value = 0;

            alert('ok');
        } else {
            alert(responseJson['responseMessage']);
        }
    }
}

async function doCancel() {
    router.back();
}
</script>
