<script setup lang="ts">
import { useI18n } from 'vue-i18n'
import { Star, PreviewOpen } from '@icon-park/vue-next'
import { computed, ref, useTemplateRef, watch } from 'vue'
import {
  fetchCollectOrCancelAgentApplication,
  fetchGetAgentApplicationList,
  fetchGetMallCategoryList,
} from '@/apis/application-square'
import type { PaginationInfo } from '@/components/custom-pagination/custom-pagination.vue'
import type { PersonalAppConfigState } from '@/store/types/personal-app-config'
import { useScroll } from '@vueuse/core'
import { router } from '@/router'
import searchEmptyImage from '@/assets/images/search-empty.png'
import applicationEmptyImage from '@/assets/images/application-empty.png'
import { ChannelType } from '@/enums/channel'

interface MallCategory {
  id: number
  categoryName: string
}

const { t } = useI18n()

const searchQuery = ref('')
const checkedClassifyValue = ref(0)
const agentApplicationList = ref<PersonalAppConfigState[]>([])

const pagingInfo = ref<PaginationInfo>({
  pageNo: 1,
  pageSize: 12,
  totalPages: 0,
  totalRows: 0,
})
const mallCategoryList = ref<MallCategory[]>([])
const cardContentWrapRef = useTemplateRef<HTMLDivElement>('cardContentWrapRef')
const isShowCarousel = ref(true)
const smooth = ref(false)
const agentApplicationBottomIsLoading = ref(false)
const agentApplicationClassifyIsLoading = ref(true)
const emptyTableText = ref(t('personal_space_module.agent_module.agent_list_module.empty_agent_list'))
const emptyTableImage = ref(applicationEmptyImage)

const behavior = computed(() => (smooth.value ? 'smooth' : 'auto'))
const isShowAgentListBottomText = computed(
  () =>
    agentApplicationList.value.length > 8 &&
    pagingInfo.value.pageNo === pagingInfo.value.totalPages &&
    !agentApplicationClassifyIsLoading.value &&
    !agentApplicationBottomIsLoading.value,
)
const { arrivedState } = useScroll(cardContentWrapRef, { behavior })

;(function () {
  handleGetMallCategoryList()
  handleGetAgentApplicationList()
})()

watch(checkedClassifyValue, () => {
  agentApplicationClassifyIsLoading.value = true
  if (searchQuery.value.length === 0) {
    handleGetAgentApplicationList(true)
  } else {
    handleGetAgentApplicationList(true, true)
  }
})

watch(
  () => arrivedState.bottom,
  () => {
    if (arrivedState.bottom) {
      if (pagingInfo.value.pageNo < pagingInfo.value.totalPages) {
        agentApplicationBottomIsLoading.value = true
        pagingInfo.value.pageNo += 1
        if (searchQuery.value.length === 0) {
          handleGetAgentApplicationList()
        } else {
          handleGetAgentApplicationList(false, true)
        }
      }
    }
  },
)

function handleGetAgentApplicationList(update = false, search = false, clear = false) {
  const agentTypeId = ref<number | null>(0)

  if (clear && searchQuery.value.trim() === '') return

  if (agentApplicationBottomIsLoading.value && agentApplicationClassifyIsLoading.value) return

  if (search && searchQuery.value.length !== 0) {
    isShowCarousel.value = false
  } else {
    isShowCarousel.value = true
  }

  if (search) agentApplicationClassifyIsLoading.value = true

  if (update) pagingInfo.value.pageNo = 1

  checkedClassifyValue.value === 0 ? (agentTypeId.value = null) : (agentTypeId.value = checkedClassifyValue.value)
  const payload = {
    search: searchQuery.value,
    pagingInfo: pagingInfo.value,
    categoryId: agentTypeId.value,
  }
  fetchGetAgentApplicationList<PersonalAppConfigState[]>(payload)
    .then((res) => {
      agentApplicationList.value = update ? res.data : [...agentApplicationList.value, ...res.data]

      pagingInfo.value = res.pagingInfo as PaginationInfo

      emptyTableText.value = searchQuery.value
        ? t('common_module.search_empty_data')
        : t('personal_space_module.agent_module.agent_list_module.empty_agent_list')
      emptyTableImage.value =
        searchQuery.value && agentApplicationList.value.length === 0 ? searchEmptyImage : applicationEmptyImage
    })
    .finally(() => {
      agentApplicationClassifyIsLoading.value = false
      agentApplicationBottomIsLoading.value = false
    })
}

function handleCollectOrCancelAgentApplication(agentApplicationItem: PersonalAppConfigState) {
  fetchCollectOrCancelAgentApplication(agentApplicationItem.id).then(() => {
    if (agentApplicationItem.isCollect === 'Y') {
      window.$message.success(t('common_module.collect_unsubscribed'))
      agentApplicationItem.isCollect = 'N'
      agentApplicationItem.collectNumber! -= 1
    } else {
      window.$message.success(t('common_module.collect_successfully'))
      agentApplicationItem.isCollect = 'Y'
      agentApplicationItem.collectNumber! += 1
    }
  })
}

function handleGetMallCategoryList() {
  mallCategoryList.value.unshift({ id: 0, categoryName: t('applications_square_module.all_application_btn_text') })
  fetchGetMallCategoryList<MallCategory[]>().then((res) => {
    if (res.code !== 0) return
    mallCategoryList.value = [...mallCategoryList.value, ...res.data]
  })
}

function handleToUseAgentApplication(agentId: string) {
  router.push({ name: 'ShareWebApplication', params: { agentId: agentId }, query: { channel: ChannelType.mall } })
}

function handleAddAgentApplications() {
  router.push({ name: 'PersonalAppSetting' })
}

function handleEnterKeypress(event: KeyboardEvent) {
  if (event.code === 'Enter' && !event.shiftKey) {
    event.preventDefault()
    if (searchQuery.value !== '') {
      handleGetAgentApplicationList(true, true, true)
    } else {
      handleGetAgentApplicationList(true, true)
    }
  }
}
</script>

<template>
  <div ref="cardContentWrapRef" class="flex h-full flex-col overflow-y-auto py-6" style="scrollbar-width: none">
    <div class="mb-[19px] flex items-center justify-between">
      <div class="flex flex-col">
        <div class="flex items-center">
          <img src="@/assets/images/applications-square-icon.png" />
          <p class="ml-[5px] text-lg">{{ t('router_title_module.application_square') }}</p>
        </div>
      </div>
      <div class="w-5/9">
        <n-input
          v-model:value="searchQuery"
          type="text"
          :placeholder="t('common_module.search')"
          class="search-input rounded-[26px]! text-[16px]! leading-[32px]! border-[#9ea3ff]! border-[1px] py-[6px] shadow-[0_4px_10px_0px_rgba(103,103,103,.1)]"
          clearable
          @keyup.enter="handleEnterKeypress"
        >
          <template #prefix>
            <div @click="() => handleGetAgentApplicationList(true, true, true)">
              <img src="@/assets/images/search.png" width="14" height="14" class="mr-[5px] cursor-pointer" />
            </div>
          </template>
        </n-input>
      </div>
      <div>
        <n-button
          type="primary"
          :bordered="false"
          :focusable="false"
          class="min-w-[86px]!"
          @click="handleAddAgentApplications"
        >
          <span class="text-sm text-[#fff]">{{ t('applications_square_module.create_application_btn_text') }}</span>
        </n-button>
      </div>
    </div>
    <div>
      <n-collapse-transition :show="isShowCarousel">
        <div class="mb-[20px]">
          <n-carousel autoplay class="h-[280px] w-full rounded-[20px] object-cover 2xl:object-fill">
            <img class="h-full w-full object-cover" src="@/assets/images/application-square-carousel.png" />
            <!-- <img class="h-[280px] w-full object-cover" src="@/assets/images/application-square-carousel.png" /> -->
          </n-carousel>
        </div>
      </n-collapse-transition>
      <div class="sticky top-[-24px] z-10">
        <n-scrollbar x-scrollable>
          <div class="flex items-center rounded-[5px] bg-white py-[9px] pl-[9px]">
            <button
              v-for="classify in mallCategoryList"
              :key="classify.id"
              :focusable="false"
              :class="['classify-radio-button', { active: checkedClassifyValue === classify.id }]"
              class="mr-[4px] cursor-pointer whitespace-nowrap rounded-[5px] border-[1px] border-[#fff] bg-transparent px-[5px] py-[5px] transition-colors duration-300 hover:bg-[#eeefff]"
              @click="checkedClassifyValue = classify.id"
            >
              {{ classify.categoryName }}
            </button>
          </div>
        </n-scrollbar>
      </div>
      <n-scrollbar style="max-height: 854px">
        <div>
          <div class="mt-[14px] min-h-[808px]">
            <div v-show="agentApplicationClassifyIsLoading" class="flex h-[500px] items-center justify-center">
              <n-spin size="large" />
            </div>
            <div
              v-show="!agentApplicationClassifyIsLoading && agentApplicationList.length !== 0"
              class="grid-content grid grid-cols-4 gap-4"
            >
              <div v-for="agentApplicationItem in agentApplicationList" :key="agentApplicationItem.id">
                <div
                  class="rounded-[10px]! max-w-[392px] bg-[#fff] px-[24px] pb-[20px] pt-[20px] shadow-[0_4px_10px_0px_rgba(103,103,103,.1)]"
                >
                  <div class="flex justify-between">
                    <div class="popover-trigger mr-[22px] text-[14px]">
                      <div class="agent-desc h-[23px] w-full max-w-[160px] font-semibold">
                        <n-ellipsis style="max-width: 180px" :line-clamp="1">
                          {{ agentApplicationItem.baseInfo.agentTitle }}

                          <template #tooltip>
                            <div style="max-width: 230px">
                              {{ agentApplicationItem.baseInfo.agentTitle }}
                            </div>
                          </template>
                        </n-ellipsis>
                      </div>

                      <div class="agent-desc mb-[15px] mt-[18px] h-[44px] w-full max-w-[228px] text-[#999999]">
                        <n-ellipsis style="max-width: 180px" :line-clamp="2">
                          {{ agentApplicationItem.baseInfo.agentDesc }}
                          <template #tooltip>
                            <div style="max-width: 230px">
                              {{ agentApplicationItem.baseInfo.agentDesc }}
                            </div>
                          </template>
                        </n-ellipsis>
                      </div>
                    </div>
                    <div class="h-[84px] w-[84px]">
                      <img
                        :src="agentApplicationItem.baseInfo.agentAvatar"
                        class="h-full w-full rounded-[10px] object-cover"
                      />
                    </div>
                  </div>
                  <n-divider class="mt-0! mb-[14px]!" />
                  <div>
                    <div class="flex justify-between">
                      <div class="flex">
                        <div class="flex items-center">
                          <Star
                            theme="two-tone"
                            size="18"
                            :fill="agentApplicationItem.isCollect === 'Y' ? ['#ffc06d', '#ffc06d'] : ['#333', '#fff']"
                            :stroke-width="3"
                            class="cursor-pointer transition-all delay-150 duration-300 ease-in-out"
                            @click="handleCollectOrCancelAgentApplication(agentApplicationItem)"
                          />
                          <span class="ml-[6px] text-[12px] text-[#333]">{{ agentApplicationItem.collectNumber }}</span>
                        </div>
                        <div class="flex items-center">
                          <PreviewOpen theme="outline" size="18" fill="#333" :stroke-width="3" class="ml-[12px]" />
                          <span class="ml-[6px] text-[12px] text-[#333]">{{ agentApplicationItem.clickNumber }}</span>
                        </div>
                      </div>
                      <button
                        class="hover:bg-theme-color text-theme-color border-[#eeefff]! rounded-[5px] border-[1px] bg-[#eeefff] bg-transparent px-[16px] py-[5px] text-[14px] transition-colors duration-300 hover:text-[#fff]"
                        @click="handleToUseAgentApplication(agentApplicationItem.baseInfo.agentId)"
                      >
                        {{ t('applications_square_module.immediate_use_btn_text') }}
                      </button>
                    </div>
                  </div>
                </div>
              </div>
              <div v-for="item in 4" :key="item" class="mr-[15px]">
                <div v-show="agentApplicationBottomIsLoading">
                  <n-skeleton text :repeat="6" /> <n-skeleton text style="width: 60%" />
                </div>
              </div>
            </div>
            <div v-show="agentApplicationList.length === 0">
              <div class="flex h-[500px] w-full items-center justify-center">
                <div class="flex flex-col items-center justify-center">
                  <img :src="emptyTableImage" class="mb-[20px] h-[68px] w-[68px]" />
                  <p class="mb-[14px] text-[14px] text-[#999999]">{{ emptyTableText }}</p>
                </div>
              </div>
            </div>
            <div
              v-show="isShowAgentListBottomText"
              class="mb-[50px] mt-[30px] flex justify-center text-center text-[14px] text-[#a9b4cc]"
            >
              <div class="relative top-[10px] h-[1px] w-[14px] bg-[#a9b4cc]"></div>
              <div class="mb-[8px] min-w-[80px]">
                {{ t('personal_space_module.agent_module.agent_list_module.already_bottom') }}
              </div>
              <div class="relative top-[10px] h-[1px] w-[14px] bg-[#a9b4cc]"></div>
            </div>
          </div>
        </div>
      </n-scrollbar>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.classify-radio-button.active {
  color: #000dff;
  background-color: #eeefff;
  border: 1px #000dff solid;
}

@media (width >= 1536px) and (width <= 1670px) {
  .popover-trigger,
  .agent-desc {
    width: 100%;
    max-width: 120px;
  }
}

@media (width >= 1371px) and (width <= 1535px) {
  .grid-content {
    grid-template-columns: repeat(3, minmax(0, 1fr));
  }

  .popover-trigger,
  .agent-desc {
    width: 100%;
    max-width: 160px;
  }
}

@media (width <= 1370px) {
  .grid-content {
    grid-template-columns: repeat(3, minmax(0, 1fr));
  }

  .popover-trigger,
  .agent-desc {
    width: 100%;
    max-width: 120px;
  }
}

.search-input:focus {
  .carousel-content {
    display: none;
  }
}
</style>
