<script lang='ts' setup>
import { submitSubscribeApi } from '~/api/model/common'
import { PageSizeEnum } from '~/enums/sizeEnum'
import { Api } from '@/api/model/url'

const config = useRuntimeConfig()
const { apiBaseSiteUrl } = config.public
const list = ref<any>([])
const currentPage = ref(PageSizeEnum.PAGE)
const total = ref()
const page_size = ref(9)
const categories = ref(
  [
    {
      key: '',
      title: 'All',
      slug: 'all',
    },
  ],
)
const form = ref<any>({
  mail: '',
})
const params = ref({
  pageNo: currentPage.value,
  pageSize: page_size.value,
  orderBy: 'createTime',
  orderType: 'desc',
  categoryId: '',
})
const { data: res } = await useAsyncData(
  'blog-category-list-index',
  () => $fetch(`${apiBaseSiteUrl}${Api.BlogsCategoryList}`, { params: { all: true } }),
)
// Ensure we have a valid array before spreading
const arr = Array.isArray(res.value?.result) ? res.value.result : []
categories.value = [
  ...categories.value,
  ...arr,
]
params.value.categoryId = categories.value[0].key
const { data: res2, pending, error, refresh } = await useAsyncData(
  'blog-list-index',
  () => $fetch(`${apiBaseSiteUrl}${Api.BlogsList}`, { params: params.value }),
)
watch(() => res2.value, (newValue) => {
  if (newValue?.result) {
    total.value = newValue.result.total
    currentPage.value = newValue.result.current
    list.value = newValue.result.records
  }
}, { immediate: true })

async function submitSubscribe() {
  try {
    await submitSubscribeApi(form.value)
    ElMessage.success(`You've subscribed successfully.`)
    form.value.mail = ''
  }
  catch (error) {
    console.log(error)
  }
}
async function onSelectCategory(item: any) {
  params.value.categoryId = item.key
  currentPage.value = PageSizeEnum.PAGE
  params.value.pageNo = PageSizeEnum.PAGE
  await refresh()
}
async function changePage(current: number, _size: number) {
  params.value.pageNo = current
  currentPage.value = current
  await refresh()
}
const validateEmail = computed(() => {
  const emailReg = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/
  if (!form.value.mail)
    return true
  return emailReg.test(form.value.mail)
})
</script>

<template>
  <div>
    <div class="pt-184px pb-50px bg-#F3F4FB text-center">
      <h2 class="text-60px fw-800 ls-2 text-#333 inline-block pos-relative custom-title-font">
        EJET Spark  <span class="custom-title-bg03">Blog</span>
        <img src="@/assets/images/blog_icon05.png" class="w-90px h-90px pos-absolute top--10px left--120px" alt="" srcset="">
        <img src="@/assets/images/blog_icon06.png" class="w-70px h-70px pos-absolute top--20px right--100px" alt="" srcset="">
      </h2>
      <div class="pos-relative w-500px mx-auto mb-60px mt-40px">
        <el-input v-model.trim="form.mail" class="custom-input h-46px !b-rd-200px overflow-hidden" placeholder="Please enter your email address" />
        <el-button :disabled="!validateEmail || !form.mail" type="primary" class="!bg-#9B6CFF !disabled:bg-#9B6CFF/70 text-#fff pos-absolute !b-0px top-50% transform-translate-y--50% right-10px w-120px !text-16px !b-rd-150px" @click="submitSubscribe">
          Subscribe
        </el-button>
      </div>

      <div class="flex gap-30px justify-center">
        <div
          v-for="(item, index) in categories"
          :key="index"
          class="h-60px lh-60px px-30px b-rd-200px text-16px cursor-pointer hover:bg-#EAE5FA hover:text-#9B6CFF transition-all duration-300"
          :class="
            params.categoryId === item.key
              ? '!bg-#EAE5FA !text-#9B6CFF'
              : 'bg-#fff text-#333'
          "
          @click="onSelectCategory(item)"
        >
          {{ item.title }}
        </div>
      </div>
    </div>
    <div class="pt-120px w-1200-auto">
      <div class="grid grid-cols-3 gap-col-40px gap-row-60px ">
        <div v-for="item in list" :key="item.key">
          <common-blog-item :item="item" />
        </div>
      </div>
      <div class="mt-60px flex justify-center">
        <el-pagination
          v-model:current-page="currentPage" :page-size="page_size" :pager-count="10"
          layout="prev, pager, next" :total="total" @change="changePage"
        />
      </div>
    </div>
    <AppFooter />
  </div>
</template>

<style lang='less' scoped>
::v-deep(.custom-input){
  .el-input__wrapper{
    border-radius:4px!important;
    padding: 7px 10px!important;
    color: #999;
    font-size: 16px;
    box-shadow: unset!important;
  }
}
</style>