<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 rounded-md border border-transparent bg-indigo-600 px-3 py-2 text-sm font-medium leading-4 text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"
                        @click="doHeadingAction(headingAction)"
                    >
                        {{ headingAction }}
                    </button>
                </div>
            </div>
        </div>
        <div class="max-w mx-auto px-3">
            <!-- Content goes here -->

            <BaseTable2
                :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 route = useRoute();

const listMode = ref(route.query.mode ? route.query.mode : '');

console.log('listMode.value=', listMode.value);

const pageTitle = ref(
    listMode.value == 'trashcan'
        ? '게시판 관리 - 삭제 게시판 리스트'
        : '게시판 관리 - 리스트'
);
const pageDescription = ref('게시판 관리 리스트 페이지 입니다.');

// 해당 페이지 우측 상단에 표시될 액션 버튼들
const headingActions = ['게시판 생성', '리스트 모드'];

// 리스트 쓰는 경에만 해당. 안되는 경우 모두 지울것.
const listSource = 'list';
const listTarget = ref('');
const listActions = ['보기', '수정'];
const actionKey = 'id';

const listHeadings = [
    {
        title: '아이디',
        widthRatio: '10',
        key: 'id',
    },

    {
        title: '제목',
        widthRatio: '25',
        key: 'title',
    },

    {
        title: '설명',
        widthRatio: '40',
        key: 'description',
    },

    {
        title: '권한',
        widthRatio: '10',
        key: 'level_min',
    },

    {
        title: '수정일',
        widthRatio: '15',
        key: 'updated',
    },
];

const listData = ref([]);

const totalPageCount = ref(1);
const currentPageNumber = ref(1);
const pageSize = ref(10);
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') {
        return $dayjs(val).format('YYYY/MM/DD  A h:mm:ss');
        // return $dayjs(val).format('YY/MM/DD');
    } else if (key == 'level_min')
        switch (val) {
            case -1:
                return '익명 사용자 이상';
                break;
            case 0:
                return '로그인 사용자 이상';
                break;
            case 4:
                return '확인 사용자 이상';
                break;
            case 5:
                return '관리자 이상';
                break;
            default:
                return val;
                break;
        }
    else {
        return val;
    }
}

const router = useRouter();

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

    switch (tag) {
        case '게시판 생성':
            navigateTo('/admin/board/new');
            break;
        case '리스트 모드':
            console.log('listMode.value=', '[' + listMode.value + ']');
            if (listMode.value == 'trashcan') {
                console.log('huk 1');
                pageTitle.value = '게시판 관리 - 리스트';
                await navigateTo('/admin/board/list', { replace: true });
                listMode.value = '';
            } else {
                console.log('huk 2');
                pageTitle.value = '게시판 관리 - 삭제 리스트';
                await navigateTo('/admin/board/list?mode=trashcan', {
                    replace: true,
                });
                listMode.value = 'trashcan';
            }
            pageMove(1);

            break;

        default:
            alert('unhandled heading action. tag = ' + tag);
    }

    // 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/' + target + '/list');
            break;
        case '수정':
            navigateTo('/admin/board/edit/' + target);

            break;
    }
}

function pageMove(targetPageIdex) {
    // console.log('on pageMove(), targetPageIdex=', targetPageIdex);
    currentPageNumber.value = targetPageIdex;
    refresh();
}

async function refresh() {
    const responseJson = await _crossCtl.doComm(
        listSource,
        listMode.value == 'trashcan'
            ? 'admin:board:info:deactivated'
            : 'admin:board:info:active',
        {
            start: (currentPageNumber.value - 1) * pageSize.value,
            length: pageSize.value,
        }
    );

    if (responseJson['responseCode'] != 200) {
        alert(responseJson['responseMessage']);
    } else {
        console.log('responseJson=', responseJson);
        currentPageNumber.value = responseJson['currentPageNumber'];
        totalPageCount.value = responseJson['totalPageCount'];
        pageSize.value = parseInt(responseJson['pageSize']);
        recordsTotal.value = responseJson['recordsTotal'];

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

refresh();
</script>
