<script setup lang="ts">
import { computed, ref, useTemplateRef, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { Search, MoreOne, Star } from '@icon-park/vue-next'
import { PaginationInfo } from '@/components/custom-pagination/custom-pagination.vue'
import { formatDateTime } from '@/utils/date-formatter'
import {
  fetchApplicationsCollectionStatusChange,
  fetchDeleteApplication,
  fetchGetApplicationList,
  fetchRemoveSalePublishApplication,
} from '@/apis/agent-application.ts'
import { PersonalAppConfigState } from '@/store/types/personal-app-config.ts'
import { router } from '@/router/index.ts'
import SaleApplicationsConfigurationModal from './sale-applications-configuration-modal.vue'
import { defaultPersonalAppConfigState } from '@/store/modules/personal-app-config'
import searchEmptyImage from '@/assets/images/search-empty.png'
import applicationEmptyImage from '@/assets/images/application-empty.png'
import { debounce } from 'lodash-es'
import { useUserStore } from '@/store/modules/user'

const { t } = useI18n()

const cardContentWrapRef = useTemplateRef<HTMLDivElement>('cardContentWrapRef')
const userStore = useUserStore()

const selectedPublishStatusValue = ref('')
const isShowSaleApplicationsConfigurationModal = ref(false)
const saleApplicationsInfo = ref<PersonalAppConfigState>(defaultPersonalAppConfigState())

const publishStatusOptions = [
  {
    label: t('common_module.all'),
    value: '',
  },
  {
    label: t('common_module.published'),
    value: 'publish',
  },
  {
    label: t('common_module.collect'),
    value: 'Y',
  },
  {
    label: t('common_module.unpublished'),
    value: 'draft',
  },
]

const pagingInfo = ref<PaginationInfo>({
  pageNo: 1,
  pageSize: 16,
  totalPages: 0,
  totalRows: 0,
})

const agentAppList = ref<PersonalAppConfigState[]>([])

const agentSearchInputValue = ref('')
const agentAppListLoading = ref(true)
const agentAppListBottomLoadingMore = ref(false)

const emptyTableText = ref(t('personal_space_module.agent_module.agent_list_module.application_empty'))
const emptyTableImage = ref(applicationEmptyImage)
const isAgentAppListBottom = ref(false)
const isCollect = ref('')

const isShowAgentListBottomText = computed(
  () =>
    pagingInfo.value.pageNo === pagingInfo.value.totalPages &&
    agentAppList.value.length !== 0 &&
    pagingInfo.value.totalRows > 12 &&
    !agentAppListLoading.value &&
    !agentAppListBottomLoadingMore.value,
)

watch(
  () => isAgentAppListBottom.value,
  () => {
    if (isAgentAppListBottom.value) {
      if (pagingInfo.value.pageNo < pagingInfo.value.totalPages) {
        pagingInfo.value.pageNo += 1
        agentAppListBottomLoadingMore.value = true
        getApplicationList(true)
      }
    }
  },
)
;(function () {
  getApplicationList()
})()

function getApplicationList(isLoadMore = false, clear = false) {
  if (clear && agentSearchInputValue.value.trim() === '') {
    return
  } else {
    if (!agentAppListBottomLoadingMore.value) agentAppListLoading.value = true
  }
  if (!isLoadMore) {
    pagingInfo.value.pageNo = 1
    pagingInfo.value.totalPages = 0
    pagingInfo.value.totalRows = 0
  }
  let publishStatus = selectedPublishStatusValue.value
  isCollect.value = ''

  if (selectedPublishStatusValue.value === 'Y') {
    isCollect.value = 'Y'
    publishStatus = ''
  }
  const payload = {
    query: agentSearchInputValue.value,
    publishStatus: publishStatus,
    isCollect: isCollect.value,
    pagingInfo: pagingInfo.value,
  }
  fetchGetApplicationList<PersonalAppConfigState[]>(payload)
    .then((res) => {
      if (res.code !== 0) return
      agentAppList.value = isLoadMore ? [...agentAppList.value, ...res.data] : res.data
      pagingInfo.value = res.pagingInfo as PaginationInfo
      emptyTableText.value = agentSearchInputValue.value
        ? t('common_module.search_empty_data')
        : t('personal_space_module.agent_module.agent_list_module.application_empty')
      emptyTableImage.value =
        agentSearchInputValue.value && agentAppList.value.length === 0 ? searchEmptyImage : applicationEmptyImage
    })
    .finally(() => {
      agentAppListLoading.value = false
      agentAppListBottomLoadingMore.value = false
    })
}

function handleBasePublishingStatusGetAgentList() {
  agentAppListLoading.value = true
  getApplicationList()
}

function handleDeletePersonalApp(agentId: string) {
  window.$message
    .ctWarning(t('personal_space_module.agent_module.agent_list_module.delete_agent_dialog_title'))
    .then(() => {
      fetchDeleteApplication(agentId).then((res) => {
        if (res.code !== 0) return
        window.$message.success(t('common_module.delete_success_message'))
        agentAppList.value.length === 1 && (pagingInfo.value.pageNo = pagingInfo.value.pageNo - 1)
        getApplicationList()

        userStore.fetchUpdateEquityInfo()
      })
    })
}

function handleChangeApplicationsSaleStatus(personalApp: PersonalAppConfigState) {
  if (personalApp.isSale === 'N') {
    saleApplicationsInfo.value = personalApp
    isShowSaleApplicationsConfigurationModal.value = true
  } else {
    fetchRemoveSalePublishApplication(personalApp.agentPublishId)
      .then(() => {
        personalApp.isSale = 'N'
        window.$message.success(t('common_module.removal_successfully'))
      })
      .catch(() => {
        window.$message.success(t('common_module.removal_failed'))
      })
  }
}

function handleEditPersonalApp(agentId: string) {
  router.push({
    name: 'PersonalAppSetting',
    params: {
      agentId,
    },
  })
}

function handleApplicationsCollect(personalApp: PersonalAppConfigState) {
  fetchApplicationsCollectionStatusChange(personalApp.baseInfo.agentId).then(() => {
    if (personalApp.isCollect === 'Y') {
      personalApp.isCollect = 'N'
      window.$message.success(t('common_module.collect_unsubscribed'))
    } else {
      personalApp.isCollect = 'Y'
      window.$message.success(t('common_module.collect_successfully'))
    }
  })
}

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

function handleEnterKeypress(event: KeyboardEvent) {
  if (event.code === 'Enter' && !event.shiftKey) {
    event.preventDefault()
    if (agentSearchInputValue.value !== '') {
      getApplicationList(false, true)
    } else {
      getApplicationList()
    }
  }
}

const handleCardContentScrollDebounce = debounce(
  (event: { target: { scrollTop: number; clientHeight: number; scrollHeight: number } }) => {
    if (!cardContentWrapRef.value) return
    const scrollTop = event.target.scrollTop
    const clientHeight = event.target.clientHeight
    const scrollHeight = event.target.scrollHeight
    isAgentAppListBottom.value = scrollTop + clientHeight >= scrollHeight
  },
  200,
)

// function handleAnalysisPersonalApp(personalApp: PersonalAppConfigState) {
//   console.log('分析', personalApp)
// }
</script>

<template>
  <div class="h-full">
    <div class="mb-[13px] flex justify-between">
      <n-space vertical class="min-w-[140px]">
        <n-select
          v-model:value="selectedPublishStatusValue"
          :options="publishStatusOptions"
          @update:value="handleBasePublishingStatusGetAgentList"
        />
      </n-space>
      <NInput
        v-model:value="agentSearchInputValue"
        :placeholder="t('common_module.search')"
        class="w-[256px]! h-[32px]!"
        clearable
        @keypress="handleEnterKeypress"
      >
        <template #suffix>
          <Search
            theme="outline"
            size="16"
            fill="#999"
            :stroke-width="3"
            class="ml-[10px] cursor-pointer text-base"
            @click="() => getApplicationList(false, true)"
          />
        </template>
      </NInput>
    </div>
    <n-scrollbar style="max-height: 700px" @scroll="handleCardContentScrollDebounce">
      <div ref="cardContentWrapRef" class="pb-[50px]">
        <div v-show="agentAppListLoading" class="flex h-[700px] items-center justify-center">
          <n-spin size="large" />
        </div>
        <div v-show="!agentAppListLoading" class="mt-[5px]">
          <div v-if="agentAppList.length" class="grid-content grid grid-cols-4">
            <div
              v-for="agentAppItem in agentAppList"
              :key="agentAppItem.baseInfo.agentId"
              class="mb-[20px] mr-[15px] cursor-pointer"
              @click="handleEditPersonalApp(agentAppItem.baseInfo.agentId)"
            >
              <div
                class="rounded-[10px]! ml-[5px] max-w-[380px] pb-[19px] pl-[24px] pr-[27px] pt-[20px] shadow-[0_4px_10px_0px_rgba(103,103,103,.1)]"
              >
                <div class="flex cursor-pointer justify-between">
                  <div class="popover-trigger mb-[19px] mr-[15px] text-[14px]">
                    <div class="agent-desc mb-[58px] h-[23px] w-full max-w-[160px] font-semibold">
                      <n-ellipsis style="max-width: 180px" :line-clamp="1">
                        {{ agentAppItem.baseInfo.agentTitle }}

                        <template #tooltip>
                          <div style="max-width: 230px">
                            {{ agentAppItem.baseInfo.agentTitle }}
                          </div>
                        </template>
                      </n-ellipsis>
                    </div>
                    <n-button
                      :color="agentAppItem.baseInfo.agentPublishStatus === 'draft' ? '#CCCCCC' : '#000DFF'"
                      class="h-[27px]! min-w-[71px]! pl-[17px]! pr-[16px]! pt-[7px]! pb-[8px]! text-[13px]! rounded-[13px] border-[1px]"
                      round
                      ghost
                    >
                      {{
                        agentAppItem.baseInfo.agentPublishStatus === 'draft'
                          ? t('common_module.unpublished')
                          : t('common_module.published')
                      }}</n-button
                    >
                  </div>
                  <div class="h-[68px] w-[68px]">
                    <img :src="agentAppItem.baseInfo.agentAvatar" class="h-full w-full rounded-[10px] object-cover" />
                  </div>
                </div>
                <div>
                  <div class="flex items-center justify-between">
                    <div class="text-[12px] leading-[12px] text-[#999999]">
                      {{ t('personal_space_module.agent_module.agent_list_module.modified_time') }}
                      {{ formatDateTime(agentAppItem.modifiedTime) }}
                    </div>
                    <div class="flex">
                      <div
                        v-show="agentAppItem.baseInfo.agentPublishStatus !== 'draft'"
                        class="rounded-[25px] p-[5px] hover:bg-[rgb(243,243,245)]"
                        @click.stop="handleApplicationsCollect(agentAppItem)"
                      >
                        <Star
                          theme="two-tone"
                          size="18"
                          :fill="agentAppItem.isCollect === 'Y' ? ['#ffc06d', '#ffc06d'] : ['#333', '#fff']"
                          :stroke-width="3"
                          class="cursor-pointer transition-all delay-150 duration-300 ease-in-out"
                        />
                      </div>

                      <n-popover
                        placement="bottom-end"
                        trigger="hover"
                        :show-arrow="false"
                        class="rounded-[10px]! py-[1px]! mb-[0px]! shadow-[0_4px_10px_0px_rgba(103,103,103,.15)]! px-[12px]! cursor-pointer"
                      >
                        <template #trigger>
                          <div
                            class="ml-[5px] cursor-pointer rounded-[25px] p-[5px] hover:bg-[rgb(243,243,245)]"
                            @click.stop
                          >
                            <MoreOne size="18" fill="#333" :stroke-width="3" />
                          </div>
                        </template>
                        <!-- <div
                          v-show="agentAppItem.baseInfo.agentPublishStatus !== 'draft'"
                          class="hover:bg-active-color mb-[10px] mt-[8px] h-[24px] w-full rounded-[4px] p-[5px] text-[14px] leading-[14px] text-[#333333]"
                          @click="handleAnalysisPersonalApp(agentAppItem)"
                        >
                          {{ t('common_module.data_table_module.analysis') }}
                        </div> -->
                        <div v-show="agentAppItem.baseInfo.agentPublishStatus !== 'draft'">
                          <div v-show="agentAppItem.isSale === 'Y'">
                            <n-popconfirm
                              :show-icon="false"
                              class="w-[170px]"
                              :positive-text="t('common_module.confirm_btn_text')"
                              :negative-text="t('common_module.cancel_btn_text')"
                              @positive-click="handleChangeApplicationsSaleStatus(agentAppItem)"
                            >
                              <template #trigger>
                                <div
                                  class="hover:bg-active-color mb-[10px] mt-[8px] h-[24px] w-full rounded-[4px] p-[5px] text-[14px] leading-[14px] text-[#333333]"
                                >
                                  {{ t('common_module.data_table_module.remove_applications') }}
                                </div>
                              </template>
                              {{
                                t(
                                  'personal_space_module.agent_module.agent_list_module.remove_applications_dialog_title',
                                )
                              }}
                            </n-popconfirm>
                          </div>
                          <div v-show="agentAppItem.isSale === 'N'">
                            <div
                              class="hover:bg-active-color mb-[10px] mt-[8px] h-[24px] w-full rounded-[4px] p-[5px] text-[14px] leading-[14px] text-[#333333]"
                              @click="handleChangeApplicationsSaleStatus(agentAppItem)"
                            >
                              {{ t('common_module.data_table_module.listing_applications') }}
                            </div>
                          </div>
                        </div>

                        <div
                          class="hover:bg-active-color mb-[8px] mt-[8px] h-[24px] min-w-[72px] rounded-[4px] p-[5px] text-[14px] leading-[14px] text-[#F25744]"
                          @click="handleDeletePersonalApp(agentAppItem.baseInfo.agentId)"
                        >
                          {{ t('common_module.delete') }}
                        </div>
                      </n-popover>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div v-for="item in 4" :key="item" class="mr-[15px]">
              <div v-show="agentAppListBottomLoadingMore">
                <n-skeleton text :repeat="6" /> <n-skeleton text style="width: 60%" />
              </div>
            </div>
          </div>
          <div v-else>
            <div class="flex h-[650px] w-full items-center justify-center">
              <div class="flex flex-col items-center justify-center">
                <img :src="emptyTableImage" alt="empty" class="mb-[20px] h-[68px] w-[68px]" />
                <p class="mb-[14px] text-[14px] text-[#999999]">
                  {{ emptyTableText }}
                </p>
                <NButton
                  v-show="
                    emptyTableText === t('personal_space_module.agent_module.agent_list_module.application_empty')
                  "
                  type="primary"
                  :bordered="false"
                  :focusable="false"
                  @click="handleSelectAddType"
                >
                  <span class="text-center text-[14px]">{{ t('common_module.create_agent_btn_text') }}</span>
                </NButton>
              </div>
            </div>
          </div>
          <div
            v-show="isShowAgentListBottomText"
            class="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>

    <SaleApplicationsConfigurationModal
      v-model="isShowSaleApplicationsConfigurationModal"
      :sale-applications-data="saleApplicationsInfo"
      @update="(newValue: string) => (saleApplicationsInfo.isSale = newValue)"
    />
  </div>
</template>

<style lang="scss" scoped>
@media (width >= 1536px) and (width <= 1670px) {
  .popover-trigger,
  .agent-desc {
    width: 100%;
    max-width: 110px;
  }
}

@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;
  }
}
</style>
