<template>
    <div>
        <!-- Page head goes here -->
        <div class="px-3 py-5">
            <div
                class="-ml-4 -mt-4 flex justify-between items-center flex-wrap sm:flex-nowrap"
            >
                <div class="ml-4 mt-4">
                    <h3 class="text-lg leading-6 font-medium text-gray-900">
                        {{ pageTitle }}
                    </h3>
                    <p class="mt-1 text-sm text-gray-500">
                        {{ pageDescription }}
                    </p>
                </div>
                <div class="ml-4 mt-4 flex-shrink-0">
                    <button
                        v-for="(headingAction, index) in headingActions"
                        :key="headingAction"
                        type="button"
                        :class="index > 0 ? 'ml-3' : ''"
                        class="inline-flex items-center justify-center rounded-md border border-transparent bg-indigo-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 sm:w-auto"
                        @click="doHeadingAction(headingAction)"
                    >
                        {{ headingAction }}
                    </button>
                </div>
            </div>
        </div>
        <div class="max-w mx-auto px-3">
            <!-- Content goes here -->

            <BaseBoardList1
                :headings="listHeadings"
                :actions="listActions"
                :data="listData"
                :action-key="actionKey"
                :column-filter="columnFilter"
                :do-action="doAction"
            />

            <BasePagination1
                :total-page-count="totalPageCount"
                :current-page-number="currentPageNumber"
                :page-size="pageSize"
                :records-total="recordsTotal"
                :page-move="pageMove"
            />
        </div>
    </div>
</template>

<script setup lang="ts">
definePageMeta({
    // middleware: 'check-auth-user',
});

const pageTitle = ref('');
const pageDescription = ref('');

// 해당 페이지 우측 상단에 표시될 액션 버튼들
const headingActions = ['글쓰기'];

// 리스트 쓰는 경에만 해당. 안되는 경우 모두 지울것.
const listSource = 'list';
const listTarget = 'board';

const listActions = [];
const actionKey = 'cid';

const listHeadings = [
    {
        title: '제목',
        widthRatio: '100',
        key: 'title',
    },

    {
        title: '글쓴이',
        widthRatio: '0',
        key: 'name',
    },
    {
        title: '날짜',
        widthRatio: '0',
        key: 'created',
    },

    {
        title: '조회',
        widthRatio: '0',
        key: 'hit_count',
    },

    {
        title: '댓글',
        widthRatio: '0',
        key: 'comment_count',
    },
];

const listData = ref([]);

const boardMeta = ref({});

const totalPageCount = ref(1);
const route = useRoute();
const currentPageNumber = ref(route.query.page ? Number(route.query.page) : 1);
const pageSize = ref(3);
const recordsTotal = ref(0);
// const order = [{ column: 'serial', dir: 'desc' }];
// const columns = { serial: { data: 'serial' } };
const { $dayjs } = useNuxtApp();
function columnFilter(key, val) {
    // console.log("columnFilter(), key = ", key, ", val = ", val);

    if (key == 'updated' || key == 'created') {
        if (boardMeta.value['ago_enabled'] == 1) {
            return $dayjs(val).fromNow();
        } else {
            return $dayjs(val).format('YYYY/MM/DD  A h:mm:ss');
        }

        // return $dayjs(val).format('YY/MM/DD');
    } else {
        return val;
    }
}

const router = useRouter();

function doHeadingAction(tag) {
    // console.log('on doHeadingAction(), tag=', tag);

    switch (tag) {
        case '글쓰기':
            navigateTo('/board/' + currnetBoardId.value + '/new');

            break;
    }

    // alert('headingAction : ' + tag);
}

function doAction(tag, target) {
    console.log('on doAction(), tag=', tag, ', target=', target);

    // alert('doAction : ' + tag + ', target = ' + target);

    switch (tag) {
        case '보기':
            navigateTo('/board/' + currnetBoardId.value + '/view/' + target);

            break;
    }
}

function pageMove(targetPageIdex) {
    // console.log('on pageMove(), targetPageIdex=', targetPageIdex);
    currentPageNumber.value = targetPageIdex;
    navigateTo(
        '/board/' + currnetBoardId.value + '/list?page=' + targetPageIdex
    );
    refresh();
}

async function refresh() {
    const responseJson = await _crossCtl.doComm(listSource, listTarget, {
        hero: currnetBoardId.value,
        start: (currentPageNumber.value - 1) * pageSize.value,
        length: pageSize.value,
    });

    console.log('responseJson=', responseJson);
    if (responseJson['responseCode'] != 200) {
        if (responseJson['responseMessage'] == 'Unauthorized') {
            alert(
                '이 게시판을 볼 수 있는 권한이 없습니다. 확인을 누르면 서비스 메인 화면으로 이동합니다. '
            );
            navigateTo('/', { replace: true });
        } else {
            alert(responseJson['responseMessage']);
        }
    } else {
        boardMeta.value = responseJson['metaData'];
        pageTitle.value = responseJson['metaData']['title'];
        pageDescription.value = responseJson['metaData']['description'];

        currentPageNumber.value = responseJson['currentPageNumber'];
        totalPageCount.value = responseJson['totalPageCount'];
        pageSize.value = parseInt(responseJson['pageSize']);
        recordsTotal.value = responseJson['recordsTotal'];

        listData.value = responseJson['data'];
    }
}

// refresh();

console.log('huk params = ', route.params);

const currnetBoardId = ref('');

if (route.params.boardId instanceof Array) {
    if (route.params.boardId.length != 1) {
        throwError('$404');
    } else {
        console.log('huk 3');
        currnetBoardId.value = route.params.boardId[0];
    }
} else {
    throwError('$404');
}

refresh();
</script>
