<script setup lang="ts">
import type { OptColumn, OptRowHeader } from 'tui-grid/types/options';
import { useContentStore } from '~/stores/contents';
import type { ContentType } from '~/types/contents';
import { useCommonCodeStore } from '~/stores';

const router = useRouter();

const instCodeList = await useCommonCodeStore().searchInstCodeList();
const contentStore = useContentStore();
const { contentsList, contentsQuery } = storeToRefs(contentStore);
const gridRef = ref();

const gridRowHeaders: OptRowHeader[] = ['checkbox', 'rowNum'];

const columns: OptColumn[] = [
  {
    name: 'contentId',
    hidden: true
  },
  {
    name: 'contentTitle',
    header: '콘텐츠제목'
  },
  {
    name: 'orgId',
    header: '관리기관',
    width: 100,
    disabled: true,
    formatter: 'listItemText',
    resizable: true,
    editor: {
      type: 'select',
      options: {
        listItems: instCodeList
      }
    }
  },
  {
    name: 'useYn',
    header: '사용여부',
    width: 80,
    align: 'center',
  },
  {
    name: 'frstRgtrId',
    header: '작성자',
    width: 100
  },
  {
    name: 'frstRegDt',
    header: '작성일',
    width: 130
  },
  {
    name: 'lastMdfrId',
    header: '수정자',
    width: 100
  },
  {
    name: 'lastMdfcnDt',
    header: '수정일',
    width: 130
  }
];

const contentType = [
  { label: '전체', value: 'TOTAL' },
  { label: '제목', value: 'TITLE' },
  { label: '내용', value: 'CONTENT' }
];

onBeforeMount(() => {
  contentStore.searchContentList();
});

onBeforeUnmount(() => {
  // contentStore.resetContentListQuery();
});

const search = () => {
  contentStore.searchContentList();
};

const list = computed(() => {
  return contentsList.value.content;
});

watch(list, (newValue) => {
  if (gridRef.value) {
    gridRef.value.off('dblclick');
    if (newValue.length > 0) {
      setTimeout(() => {
        gridRef.value.on('dblclick', ({ instance, rowKey }) => {
          const row = instance.getRow(rowKey);
          editPage(row.contentId);
        });
      }, 100);
    }
  }
});

const deleteContentList = async () => {
  const checkedRows = gridRef.value.getCheckedRows() as Array<ContentType>;

  if (!checkedRows.length) {
    message.warn('삭제할 콘텐츠가 없습니다.');
    return;
  }
  Modal.confirm({
    type: 'warning',
    okText: '예',
    cancelText: '아니오',
    title: '컨텐츠 삭제',
    content: '선택한 컨텐츠를 삭제하시겠습니까?',
    onOk: async () => {
      const createdRows = checkedRows.filter((row) => row.contentId);
      await contentStore.deleteContents(createdRows);
      await contentStore.searchContentList();
    }
  });
};

const movePage = (page: number) => {
  contentsQuery.value.page = page;
  search();
};

const editPage = (contentId: any) => {
  const query = typeof contentId === 'number' ? `?contentId=${contentId}` : '';
  router.push(`/admin/content${query}`);
};
</script>

<template>
  <client-only>
    <a-space direction="vertical" class="w-full">
      <a-card>
        <a-row :gutter="[16, 8]">
          <a-col>
            <a-space>
              <a-typography-text>관리기관</a-typography-text>
              <lazy-common-inst-code-select
                key="inst-code-select"
                v-model="contentsQuery.orgId"
                class-name="w-40"
                select-type="ALL"
              />
            </a-space>
          </a-col>

          <a-col>
            <a-space>
              <a-typography-text>검색어</a-typography-text>
              <a-select
                title="컨텐츠 구분"
                class="w-20"
                v-model:value="contentsQuery.type"
                :options="contentType"
              />
              <a-input title="검색어" placeholder="Search" class="w-60"
                       v-model:value="contentsQuery.keyword" allow-clear/>
            </a-space>
          </a-col>
          <a-col>
            <a-button type="primary" @click="search">검색</a-button>
          </a-col>
        </a-row>
      </a-card>

      <a-card>
        <a-space direction="vertical" class="w-full">
          <a-flex justify="space-between">
<!--            <common-permit-button api="/api/admin/contents/deleteContents">-->
<!--              <a-button type="primary" danger @click="deleteContentList"-->
<!--                >삭제-->
<!--              </a-button>-->
<!--            </common-permit-button>-->
<!--            <common-permit-button api="/api/admin/contents/updateContents">-->
<!--              <a-button type="primary" @click="editPage">추가</a-button>-->
<!--            </common-permit-button>-->
          </a-flex>
          <data-grid
            :key="`board-content-grid-${Math.random()}`"
            :row-headers="gridRowHeaders"
            :data="contentsList.content"
            :columns="columns"
            ref="gridRef"
          />
          <data-pagination
            :key="`pagination-${Math.random()}`"
            :total-elements="contentsList.totalElements"
            :show-pagination-count="10"
            :size="contentsQuery.size"
            :page="contentsQuery.page"
            @change="movePage"
          />
        </a-space>
      </a-card>
    </a-space>
  </client-only>
</template>
