<script lang="ts" setup>
import { ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { createApiCallDetailColumns } from '../columns'
import { ApiCallDetailItem, ApiProfileInfo } from '../type'
import { usePersonalAppConfigStore } from '@/store/modules/personal-app-config'
import { copyToClip } from '@/utils/copy'
import { fetchGetAPIProfile, fetchResetAPIProfile } from '@/apis/agent-application'
import { fetchGetAPIChannelPointUsageCount, fetchReportAPIChannelPointUsage } from '@/apis/agent-analyze'

enum RangType {
  today = 'today',
  week = 'week',
  month = 'month',
  customize = 'customize',
}

const { t } = useI18n()

const personalAppConfigStore = usePersonalAppConfigStore()

const isShow = defineModel<boolean>('isShow', { required: true })

const apiProfileLoading = ref(false)
const apiCallDetailLoading = ref(false)
const reportAPIUsageDataLoading = ref(false)
const apiProfileInfo = ref<ApiProfileInfo>({
  apiKey: '',
  apiSecret: '',
})
const currentRangType = ref(RangType.today)
const selectDateRange = ref<[string, string]>(['', ''])
const rangTypeOptionList = [
  {
    label: t('common_module.today'),
    value: RangType.today,
  },
  {
    label: t('common_module.last_week'),
    value: RangType.week,
  },
  {
    label: t('common_module.last_month'),
    value: RangType.month,
  },
  {
    label: t('common_module.custom'),
    value: RangType.customize,
  },
]
const apiCallDetailColumns = createApiCallDetailColumns()
const apiCallDetailData = ref<ApiCallDetailItem[]>([])

const disableDateRange = (ts: number, type: 'start' | 'end', range: [number, number] | null) => {
  if (type === 'start' && range !== null) {
    return range[1] - ts >= 86400000 * 365 || ts > Date.now()
  }
  if (type === 'end' && range !== null) {
    return ts - range[0] >= 86400000 * 365 || ts > Date.now()
  }

  return ts > Date.now()
}

watch(
  () => isShow.value,
  async (newVal) => {
    if (newVal) {
      await handleGetAPIProfile()
      await handleGetAPIChannelPointUsageCount()
    }
  },
)

function handleTurnToInterfaceDocument() {
  window.open(
    'https://www.yuque.com/u21309325/qlruxb/vp47nefvokd23d58?singleDoc#%20%E3%80%8Amodel-link%20api%E6%96%87%E6%A1%A3%E3%80%8B',
    '_blank',
  )
}

async function handleGetAPIProfile() {
  apiProfileLoading.value = true

  const res = await fetchGetAPIProfile<ApiProfileInfo>()

  if (res.code === 0) {
    apiProfileInfo.value = res.data
    apiProfileLoading.value = false
  }
}

async function handleResetAPIProfile() {
  apiProfileLoading.value = true

  const res = await fetchResetAPIProfile<ApiProfileInfo>()

  if (res.code === 0) {
    apiProfileInfo.value = res.data
    apiProfileLoading.value = false
  }
}

async function handleGetAPIChannelPointUsageCount() {
  apiCallDetailLoading.value = true

  const res = await fetchGetAPIChannelPointUsageCount<ApiCallDetailItem[]>({
    agentId: personalAppConfigStore.baseInfo.agentId,
    timeRange: {
      rangType: currentRangType.value,
      startTime: selectDateRange.value[0],
      endTime: selectDateRange.value[1],
    },
  })

  if (res.code === 0) {
    apiCallDetailLoading.value = false
    apiCallDetailData.value = res.data
  }
}

function handleCopyText(text: string) {
  copyToClip(text)
  window.$message.success(t('common_module.copy_success_message'))
}

async function handleUpdateRangType(rangType: string) {
  if (rangType !== RangType.customize) {
    selectDateRange.value = ['', '']
    await handleGetAPIChannelPointUsageCount()
  }
}

async function handleUpdateDateRange(_value: [number, number], formattedValue: [string, string]) {
  if (formattedValue && formattedValue[0] && formattedValue[1]) {
    selectDateRange.value = formattedValue
    await handleGetAPIChannelPointUsageCount()
  }
}

async function handleExportAPIChannelPointUsageData() {
  reportAPIUsageDataLoading.value = true

  fetchReportAPIChannelPointUsage({
    reportRequestType: 'API_CHANNEL_POINT_USAGE',
    agentId: personalAppConfigStore.baseInfo.agentId,
    timeRange: {
      rangType: currentRangType.value,
      startTime: selectDateRange.value[0],
      endTime: selectDateRange.value[1],
    },
  })
    .then((data: any) => {
      const blob = new Blob([data], { type: 'application/vnd.ms-excel' })
      const link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      link.download = `${personalAppConfigStore.baseInfo.agentId}.xlsx`
      link.click()
      window.URL.revokeObjectURL(link.href)
      window.$message.success(t('common_module.export_successfully'))
    })
    .catch(() => {
      window.$message.error(t('common_module.export_failed'))
    })
    .finally(() => {
      reportAPIUsageDataLoading.value = false
    })
}
</script>

<template>
  <n-drawer
    v-model:show="isShow"
    :width="861"
    :show-mask="'transparent'"
    :trap-focus="false"
    :block-scroll="false"
    content-class="rounded-[10px]"
    class="shadow-none!"
    to="#drawer-target"
  >
    <n-drawer-content
      :title="t('personal_space_module.agent_module.agent_setting_module.agent_publish_module.api_call')"
      header-class="border-b-0! p-5! pt-6! text-[16px]! font-600!"
      body-content-class="px-5! py-0!"
      footer-class="border-t-0! py-2!"
      :native-scrollbar="false"
      closable
    >
      <div class="flex min-h-[calc(100vh-56px-62px-20px)] flex-col rounded-[10px] bg-[#fafbfc] p-5">
        <div class="mb-5 flex justify-end pr-5">
          <n-button type="primary" :bordered="false" @click="handleTurnToInterfaceDocument">
            {{ t('personal_space_module.agent_module.agent_setting_module.agent_publish_module.interface_document') }}
          </n-button>
        </div>
        <div class="text-font-color flex h-full flex-col gap-5 text-[14px]">
          <div class="rounded-[10px] border border-[#e7e7e7] bg-white p-5">
            <div class="mb-[7px] flex items-center justify-between">
              <p class="font-600">App Key</p>
              <span
                v-show="!apiProfileInfo.apiKey"
                class="text-theme-color cursor-pointer hover:opacity-80"
                @click="handleGetAPIProfile"
              >
                {{
                  t('personal_space_module.agent_module.agent_setting_module.agent_publish_module.click_to_generate')
                }}
              </span>
              <span
                v-show="apiProfileInfo.apiKey"
                class="text-theme-color cursor-pointer hover:opacity-80"
                @click="handleResetAPIProfile"
              >
                {{ t('common_module.regenerate') }}
              </span>
            </div>

            <div class="rounded-theme h-9 w-full cursor-default border px-3">
              <div v-show="!apiProfileLoading" class="flex h-full w-full items-center justify-between">
                <span>{{ apiProfileInfo.apiKey || t('common_module.not_generated') }}</span>

                <n-popover trigger="hover">
                  <template #trigger>
                    <i
                      v-show="apiProfileInfo.apiKey"
                      class="iconfont icon-copy text-gray-font-color hover:text-theme-color cursor-pointer leading-4"
                      @click="handleCopyText(apiProfileInfo.apiKey)"
                    />
                  </template>
                  <span>{{ t('common_module.data_table_module.copy') }}</span>
                </n-popover>
              </div>

              <div v-show="apiProfileLoading" class="flex h-full w-full items-center">
                <div class="bg-px-api_profile_loading-gif h-[10px] w-[54px] bg-contain bg-no-repeat" />
              </div>
            </div>

            <p class="font-600 mb-[7px] mt-[20px]">App Secret</p>
            <div class="rounded-theme h-9 w-full cursor-default border px-3">
              <div v-show="!apiProfileLoading" class="flex h-full w-full items-center justify-between">
                <span>{{ apiProfileInfo.apiSecret || t('common_module.not_generated') }}</span>

                <n-popover trigger="hover">
                  <template #trigger>
                    <i
                      v-show="apiProfileInfo.apiSecret"
                      class="iconfont icon-copy text-gray-font-color hover:text-theme-color cursor-pointer leading-4"
                      @click="handleCopyText(apiProfileInfo.apiSecret)"
                    />
                  </template>
                  <span>{{ t('common_module.data_table_module.copy') }}</span>
                </n-popover>
              </div>

              <div v-show="apiProfileLoading" class="flex h-full w-full items-center">
                <div class="bg-px-api_profile_loading-gif h-[10px] w-[54px] bg-contain bg-no-repeat" />
              </div>
            </div>
          </div>

          <div class="rounded-[10px] border border-[#e7e7e7] bg-white p-5">
            <p class="font-600 mb-2">
              {{ t('personal_space_module.agent_module.agent_setting_module.agent_publish_module.agentId') }}
            </p>
            <div class="rounded-theme flex h-9 w-full cursor-default items-center justify-between border px-3">
              <span>{{ personalAppConfigStore.baseInfo.agentId }}</span>

              <span
                class="text-theme-color border-inactive-border-color cursor-pointer border-l pl-3 hover:opacity-80"
                @click="handleCopyText(personalAppConfigStore.baseInfo.agentId)"
              >
                {{ t('common_module.copy_link') }}
              </span>
            </div>
          </div>

          <div class="flex h-[476px] flex-col rounded-[10px] border border-[#e7e7e7] bg-white p-5">
            <p class="font-600 mb-2">
              {{ t('personal_space_module.agent_module.agent_setting_module.agent_publish_module.api_call_details') }}
            </p>

            <div class="my-4.5 flex items-center justify-between">
              <div class="flex gap-3">
                <n-select
                  v-model:value="currentRangType"
                  :options="rangTypeOptionList"
                  class="w-[124px]! text-[#84868c]! time-range-select"
                  @update:value="handleUpdateRangType"
                />

                <n-date-picker
                  v-show="currentRangType === 'customize'"
                  :is-date-disabled="disableDateRange"
                  type="daterange"
                  clearable
                  class="w-[250px]! customize-date-picker"
                  @update:value="handleUpdateDateRange"
                />
              </div>

              <n-button
                type="primary"
                :bordered="false"
                :disabled="!apiCallDetailData.length"
                :loading="reportAPIUsageDataLoading"
                @click="handleExportAPIChannelPointUsageData"
              >
                {{ t('common_module.export_data') }}
              </n-button>
            </div>

            <n-data-table
              :columns="apiCallDetailColumns"
              :bordered="true"
              :bottom-bordered="true"
              :single-line="false"
              :max-height="283"
              :loading="apiCallDetailLoading"
              :data="apiCallDetailData"
              virtual-scroll
            >
              <template #empty>
                <div class="flex h-[283px] items-center justify-center">
                  <div class="flex flex-col items-center justify-center">
                    <div class="bg-px-empty_list-png mb-5 h-[68px] w-[68px]" />
                    <p class="select-none text-[#84868c]">{{ t('common_module.empty_data') }}</p>
                  </div>
                </div>
              </template>
            </n-data-table>
          </div>
        </div>
      </div>

      <template #footer></template>
    </n-drawer-content>
  </n-drawer>
</template>

<style lang="scss" scoped>
:deep(.time-range-select .n-base-selection),
:deep(.customize-date-picker.n-date-picker .n-input) {
  --n-height: 36px !important;
}

:deep(.n-input .n-input__input-el) {
  height: 36px !important;
}
</style>
