<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import CustomIcon from '@/components/custom-icon/custom-icon.vue'
import CustomPagination, { PaginationInfo } from '@/components/custom-pagination/custom-pagination.vue'
import { createPersonalAppColumn } from './columns.ts'
import useTableScrollY from '@/composables/useTableScrollY.ts'
import {
  fetchDeleteApplication,
  fetchGetDebugApplicationInfo,
  fetchGetApplicationList,
  fetchSaveAgentApplication,
} from '@/apis/agent-application.ts'
import { PersonalAppConfigState } from '@/store/types/personal-app-config.ts'
import { copyToClip } from '@/utils/copy.ts'

const router = useRouter()

const { pageContentWrapRef, tableContentY } = useTableScrollY(48 + 32 + 16 + 16 + 28)

const columns = createPersonalAppColumn(handleClickPersonalAppTableAction)

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

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

const agentSearchInputValue = ref('')
const agentAppListTableLoading = ref(false)

onMounted(async () => {
  await handleGetApplicationList()
})

async function handleGetApplicationList() {
  agentAppListTableLoading.value = true
  const res = await fetchGetApplicationList<PersonalAppConfigState[]>({
    query: agentSearchInputValue.value,
    pagingInfo: pagingInfo.value,
  }).finally(() => (agentAppListTableLoading.value = false))

  if (res.code === 0) {
    agentAppList.value = res.data
    pagingInfo.value = res.pagingInfo as PaginationInfo
  }
}

function handleClickPersonalAppTableAction(actionType: string, agentId: string) {
  switch (actionType) {
    case 'copyAgentId':
      handleCopyAgentId(agentId)
      break
    case 'openPublishDetail':
      handleOpenPublishDetail(agentId)
      break
    case 'edit':
      handleEditPersonalApp(agentId)
      break
    case 'copy':
      handleCopyPersonalApp(agentId)
      break
    case 'delete':
      handleDeletePersonalApp(agentId)
      break
  }
}

function handleCopyAgentId(agentId: string) {
  copyToClip(agentId)
  window.$message.success('复制成功')
}

function handleOpenPublishDetail(agentId: string) {
  router.push({
    name: 'PersonalAppSetting',
    query: {
      tabKey: 'publish',
    },
    params: {
      agentId,
    },
  })
}

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

async function handleCopyPersonalApp(agentId: string) {
  const res = await fetchGetDebugApplicationInfo<PersonalAppConfigState>(agentId)

  if (res.code === 0) {
    const payload = res.data

    payload.baseInfo.agentId = ''
    payload.baseInfo.agentTitle += '的副本'
    payload.baseInfo.agentPublishStatus = 'draft'

    await fetchSaveAgentApplication(payload)

    await handleGetApplicationList()
  }
}

function handleDeletePersonalApp(agentId: string) {
  window.$dialog.warning({
    title: '确定要删除选中的应用吗？',
    content: '删除后，如需再次使用，请重新创建',
    negativeText: '取消',
    positiveText: '确定',
    onPositiveClick: async () => {
      const res = await fetchDeleteApplication(agentId)
      if (res.code === 0) {
        window.$message.success('删除成功')
        await handleGetApplicationList()
      }
    },
  })
}

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

async function handleEnterKeypress(event: KeyboardEvent) {
  if (event.code === 'Enter' && !event.shiftKey) {
    event.preventDefault()

    await handleGetApplicationList()
  }
}

async function handleGetApplicationListUpdatePageNo(pageNo: number) {
  pagingInfo.value.pageNo = pageNo
  await handleGetApplicationList()
}

async function handleGetApplicationListUpdatePageSize(pageSize: number) {
  pagingInfo.value.pageNo = 1
  pagingInfo.value.pageSize = pageSize
  await handleGetApplicationList()
}
</script>

<template>
  <div ref="pageContentWrapRef" class="h-full">
    <div class="mb-4 flex justify-between">
      <NInput
        v-model:value="agentSearchInputValue"
        placeholder="请输入应用名称或描述"
        class="w-[256px]! h-[32px]! rounded-md!"
        @keypress="handleEnterKeypress"
      >
        <template #suffix>
          <CustomIcon
            icon="tdesign:search"
            class="cursor-pointer text-base text-[#999]"
            @click="handleGetApplicationList"
          />
        </template>
      </NInput>
      <NButton type="primary" class="h-[32px]! w-[100px]! rounded-md!" @click="handleToPersonAppSettingPage">
        创建应用
      </NButton>
    </div>

    <div class="mb-4" :style="{ height: tableContentY + 48 + 'px' }">
      <NDataTable
        :loading="agentAppListTableLoading"
        :bordered="true"
        :bottom-bordered="true"
        :single-line="false"
        :data="agentAppList"
        :columns="columns"
        :max-height="tableContentY"
        :scroll-x="1330"
      />
    </div>

    <footer class="flex justify-end">
      <CustomPagination
        :paging-info="pagingInfo"
        @update-page-no="handleGetApplicationListUpdatePageNo"
        @update-page-size="handleGetApplicationListUpdatePageSize"
      />
    </footer>
  </div>
</template>
