<template>
    <NLayout class="h-full bg" :style="{ backgroundImage: `url(${bg1})` }">
        <NLayoutHeader class="flex items-center px-12 !bg-black/20" style="height: 64px; backdrop-filter: blur(5px)">
            <span class="text-lg flex-1 text-white alimamaShuHeiTi">参考文献助手</span>
            <template v-if="isLogin">
                <n-popover placement="bottom" trigger="click">
                    <template #trigger>
                        <n-button text>
                            <user-avatar avatarType="medium" onlyAvatar />
                        </n-button>
                    </template>
                    <n-button class="alimamaShuHeiTi" size="small" @click="logout" text>退出登录</n-button>
                </n-popover>
            </template>

            <template v-else>
                <n-button class="alimamaShuHeiTi" round @click="showLogin = true" type="primary" size="small"
                    >登录</n-button
                >
            </template>
        </NLayoutHeader>
        <NLayoutContent
            position="absolute"
            :style="`top: 64px; bottom: 0; ;backgroundSize:cover`"
            class="px-12 py-4 !bg-transparent"
            content-class="bg-white"
            content-style="display:flex;flex-direction:column;border-radius:30px; background-color:rgba(0,0,0,0.8); backdrop-filter: blur(5px)"
        >
            <NConfigProvider :theme="darkTheme">
                <div class="flex p-6 max-w-[546px] m-auto relative" @keyup.enter="searchReference">
                    <n-input
                        size="large"
                        class="flex-1 !rounded-none !rounded-l-lg"
                        clearable
                        v-model:value="title"
                        placeholder="输入论文标题或关键词"
                    >
                        <template #suffix>
                            <!-- <Copy /> -->
                            <n-icon size="18" color="white" :component="Copy" @click="copyReference" />
                        </template>
                    </n-input>
                    <n-button
                        size="large"
                        class="!rounded-none alimamaShuHeiTi"
                        type="primary"
                        @click="searchReference"
                        :loading="searchingReference"
                    >
                        搜索一下
                    </n-button>
                    <n-button
                        size="large"
                        tertiary
                        class="!rounded-none !rounded-r-lg alimamaShuHeiTi"
                        type="primary"
                        @click="showGptModal = true"
                    >
                        更多服务
                    </n-button>
                    <!-- <img
                        class="absolute right-[-25px] top-[30px] w-[32px] cursor-pointer"
                        @click.stop="showGptModal = true"
                        src="@/assets/vip1.png"
                        alt=""
                    /> -->
                    <!-- <NButton class="!ml-4" type="primary" ghost @click="copyReference">复制</NButton> -->
                </div>

                <div class="flex-1 overflow-auto py-4 px-8 text-white">
                    <div v-for="(item, i) in referenceData.zh" :key="i">[{{ i + 1 }}]{{ item.ref[0] }}</div>
                    <div v-for="(item, i) in referenceData.en" :key="i">
                        [{{ referenceData.zh.length + i + 1 }}]{{ item.ref[0] }}
                    </div>
                </div>
                <div class="absolute right-16 bottom-4"></div>
            </NConfigProvider>
        </NLayoutContent>
    </NLayout>
    <NConfigProvider
        :theme="darkTheme"
        :theme-overrides="{
            Card: {
                colorModal: '#20223c'
            },
            Input: {
                border: '1px solid #2B3038'
            }
        }"
    >
        <n-modal v-model:show="showLogin" transform-origin="center">
            <n-card class="!max-w-xl !rounded-xl">
                <div class="text-white text-2xl text-center font-bold py-8">登录</div>
                <div class="max-w-sm my-5 mx-auto pb-16">
                    <login-form @success="onLogin" theme="dark"></login-form>
                </div>
            </n-card>
        </n-modal>
    </NConfigProvider>

    <NModal v-model:show="showGptModal">
        <NCard class="!max-w-xl !rounded-xl">
            <div class="text-center">
                <div class="text-base font-bold">非会员每天免费搜一次</div>
                <!-- <div class="text-xs text-slate-500">今日免费次数已用完，明天再来吧</div> -->
            </div>
            <div class="flex justify-around items-start py-9">
                <div class="flex flex-col items-center justify-center cursor-pointer" @click="goGpt">
                    <img class="h-[64px]" src="@/assets/vip.png" alt="" />
                    <div class="text-base pt-5 font-bold flex items-center">
                        购买走马AI会员 <NIcon><ChevronRight /></NIcon>
                    </div>
                    <div class="text-xs text-slate-500">解锁不限次搜索</div>
                </div>
                <div class="flex flex-col items-center justify-center cursor-pointer" @click="showQr = true">
                    <img class="h-[64px]" src="@/assets/teacher.png" alt="" />
                    <div class="text-base pt-5 font-bold flex items-center">
                        老师一对一论文辅导 <NIcon><ChevronRight /></NIcon>
                    </div>
                </div>
            </div>
            <!-- <NButton class="!mt-4" type="primary" strong secondary block size="large" @click="goGpt">
                购买走马AI会员解锁不限次搜索<NIcon> <ChevronRight /> </NIcon>
            </NButton>
            <NButton class="!mt-4" type="success" strong secondary block size="large" @click="showQr = true">
                老师一对一论文辅导 <NIcon> <ChevronRight /> </NIcon>
            </NButton> -->
        </NCard>
    </NModal>

    <NModal v-model:show="showQr">
        <NCard class="!w-auto overflow-hidden">
            <img class="w-[260px]" :src="qrCode" />
            <NAlert type="success" :show-icon="false"><div class="text-center">扫码添加老师微信</div></NAlert>
        </NCard>
    </NModal>
</template>
<script lang="ts" setup>
import { ref, onMounted, Ref, computed } from 'vue'
import {
    NConfigProvider,
    NButton,
    useMessage,
    useDialog,
    NModal,
    NCard,
    NInput,
    NLayout,
    NLayoutHeader,
    NLayoutContent,
    NPopover,
    darkTheme,
    NAlert,
    NIcon
} from 'naive-ui'
import { fetchSearchReference, fetchConfig } from '@/api'
import { UserAvatar } from '@/components/common'
import { LoginForm } from '@/components/common'
import { useUserStore } from '@/store'
import { storeToRefs } from 'pinia'
import 'vditor/src/assets/less/index.less'
import { useRouter } from 'vue-router'
import { useClipboard } from '@vueuse/core'
import { ChevronRight, Copy } from '@vicons/tabler'
import bg1 from '@/assets/searchBg1.jpg'

const router = useRouter()
const message = useMessage()
const showLogin = ref(false)
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
const dialog = useDialog()
const isLogin = computed(() => {
    return !!userInfo.value.id
})
const roles = computed(() => {
    return userInfo.value?.roles || []
})
const qrCode = ref('')
onMounted(() => {
    if (!isLogin.value) {
        showLogin.value = true
    }
    fetchConfig('paper_qr').then((res: any) => {
        qrCode.value = res.value
    })
})
function logout() {
    dialog.create({
        title: '提示',
        content: '确认要退出登录吗？',
        positiveText: '退出登录',
        negativeText: '取消',
        maskClosable: false,
        onPositiveClick: () => {
            userStore.logout()
            message.success('退出登录成功')
        }
    })
}
function onLogin() {
    showLogin.value = false
}
const showReferenceDialog = ref(false)
const title = ref('')
const referenceData: Ref<any> = ref({
    zh: [],
    en: []
})
const searchingReference = ref(false)
async function searchReference() {
    if (!isLogin.value) {
        showLogin.value = true
        return
    }
    if (!title.value) {
        message.error('请输入论文标题')
        return
    }
    searchingReference.value = true
    try {
        const res: any = await fetchSearchReference(title.value)
        referenceData.value = res
    } catch (error: any) {
        if (error.message === 'USAGE_LIMIT_EXCEEDED') {
            showGptModal.value = true
        } else {
            message.error(error.message)
        }
    }
    searchingReference.value = false
}
async function copyReference() {
    let i = 0
    const text = referenceData.value.zh
        .concat(referenceData.value.en)
        .map((item: any) => {
            return `[${++i}]` + item.ref[0]
        })
        .join('\n')
    console.log(text)
    const { copy } = useClipboard({ legacy: true })
    await copy(text)
    message.success('复制成功')
}

const showGptModal = ref(false)
const showQr = ref(false)
function goGpt() {
    window.open('https://gpt.izouma.com/ui/home')
}
</script>
<style lang="less" scoped>
:deep(.edit-form) {
    flex-wrap: wrap;
    .n-form-item {
        width: calc(33.33% - 18px);
    }
}
.bg {
    background-size: contain;
}
</style>
