<template>
    <NLayout class="h-full">
        <NLayoutHeader class="flex items-center px-8" style="height: 64px">
            <span class="text-lg flex-1">论文助手</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 size="small" @click="logout" text>退出登录</n-button>
                </n-popover>
            </template>

            <template v-else>
                <n-button round @click="showLogin = true" type="primary" size="small">登录</n-button>
            </template>
        </NLayoutHeader>
        <NLayoutContent
            position="absolute"
            style="top: 64px; bottom: 0"
            class="px-8 py-4"
            content-style="display:flex !important;flex-direction:column"
        >
            <NSpace class="pb-4">
                <n-input-group @keyup.enter="getData">
                    <n-input clearable v-model:value="search" />
                    <n-button type="primary" ghost @click="getData(true)"> 搜索 </n-button>
                </n-input-group>
                <NButton type="primary" @click="onCreate">创建</NButton>
                <NButton type="primary" @click="$router.push('/refSearch')">参考文献</NButton>
            </NSpace>
            <n-data-table
                remote
                :columns="columns"
                :data="tableData"
                :pagination="paginationReactive"
                :bordered="false"
                @update:page="getData(false)"
                @update:page-size="getData(true)"
                v-bind:flex-height="true"
                class="flex-1"
            />
        </NLayoutContent>
    </NLayout>
    <n-modal v-model:show="showModal">
        <n-card style="width: 800px" :bordered="false" role="dialog" aria-modal="true">
            <NSpace class="mb-4 flex items-center">
                <n-radio-group v-model:value="showResultType" name="radiobuttongroup2" size="small">
                    <n-radio-button value="doc"> 生成结果 </n-radio-button>
                    <n-radio-button value="attachment"> 附件 </n-radio-button>
                </n-radio-group>
                <NUpload :action="uploadUrl" :headers="uploadHeaders" :show-file-list="false" @finish="onUploaded">
                    <NButton size="small" type="primary">上传附件</NButton>
                </NUpload>
            </NSpace>
            <n-data-table
                v-if="showResultType === 'doc'"
                remote
                :columns="resultColumns"
                :data="resultData"
                :pagination="resultsPagination"
                :bordered="false"
                @update:page="getResults"
                @update:page-size="getResults"
            />
            <n-data-table
                v-else
                remote
                :columns="attachmentColumns"
                :data="attachmentData"
                :pagination="attachmentsPagination"
                :bordered="false"
                @update:page="getAttachments"
                @update:page-size="getAttachments"
            />
        </n-card>
    </n-modal>
    <n-modal v-model:show="showForm" :mask-closable="false">
        <n-card
            style="width: 800px"
            :title="orderId ? '编辑' : '创建'"
            :bordered="false"
            size="huge"
            role="dialog"
            aria-modal="true"
        >
            <NForm class="edit-form" ref="form" :model="model" :rules="rules" inline>
                <!-- 订单号	总价	定金	定金交付	尾款	尾款交付	交稿状态	接单渠道	学历	专业	题目	字数(k)	查重要求	截稿日期	稿费结款方式	是否结稿费	备注 -->

                <NFormItem label="订单号" path="orderNumber">
                    <NInput v-model:value="model.orderNumber" />
                </NFormItem>
                <NFormItem label="总价" path="totalPrice">
                    <NInput v-model:value="model.totalPrice" />
                </NFormItem>
                <NFormItem label="定金" path="deposit">
                    <NInput v-model:value="model.deposit" />
                </NFormItem>
                <NFormItem label="定金交付" path="depositPaid">
                    <NCheckbox v-model:checked="model.depositPaid">已交</NCheckbox>
                </NFormItem>
                <NFormItem label="尾款" path="finalPayment">
                    <NInput v-model:value="model.finalPayment" />
                </NFormItem>
                <NFormItem label="尾款交付" path="finalPaymentPaid">
                    <NCheckbox v-model:checked="model.finalPaymentPaid">已交</NCheckbox>
                </NFormItem>
                <NFormItem label="交稿状态" path="deliveryStatus">
                    <NSelect v-model:value="model.deliveryStatus" :options="deliveryStatusOptions" filterable />
                </NFormItem>
                <NFormItem label="接单渠道" path="orderChannel">
                    <NInput v-model:value="model.orderChannel" />
                </NFormItem>
                <NFormItem label="学历" path="education">
                    <NSelect v-model:value="model.education" :options="educationOptions" filterable />
                </NFormItem>
                <NFormItem label="专业" path="major">
                    <NInput v-model:value="model.major" />
                </NFormItem>
                <NFormItem label="标题" path="title">
                    <NInput v-model:value="model.title" />
                </NFormItem>
                <NFormItem label="字数" path="wordCount">
                    <NInput v-model:value="model.wordCount" />
                </NFormItem>
                <NFormItem label="查重要求" path="plagiarismCheck">
                    <NInput v-model:value="model.plagiarismCheck" />
                </NFormItem>
                <NFormItem label="截稿日期" path="deadline">
                    <NDatePicker
                        v-model:formatted-value="model.deadline"
                        value-format="yyyy-MM-dd"
                        type="date"
                        clearable
                    />
                </NFormItem>
                <NFormItem label="稿费结款方式" path="paymentMethod">
                    <NInput v-model:value="model.paymentMethod" />
                </NFormItem>
                <NFormItem label="是否结稿费" path="paymentStatus">
                    <NCheckbox v-model:checked="model.paymentStatus">已结</NCheckbox>
                </NFormItem>
                <div class="w-3/4"></div>
                <NFormItem style="width: calc(100% - 18px)" label="备注" path="remark">
                    <NInput type="textarea" :resizable="false" :rows="3" v-model:value="model.remark" />
                </NFormItem>
            </NForm>
            <NSpace class="text-right" justify="end">
                <NButton @click="() => (showForm = false)">取消</NButton>
                <NButton type="primary" @click="submit(false)" :loading="loading">{{
                    orderId ? '保存' : '创建'
                }}</NButton>
            </NSpace>
        </n-card>
    </n-modal>
    <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>

    <n-drawer v-model:show="showEditor" width="100%" height="100%" placement="bottom" @afterEnter="onEditorShow">
        <n-drawer-content body-content-style="padding:0">
            <div class="h-full">
                <div id="editor"></div>
            </div>
        </n-drawer-content>
    </n-drawer>

    <n-modal v-model:show="showGenDialog" :mask-closable="false">
        <n-card style="width: 800px" title="生成" :bordered="false" size="huge" role="dialog" aria-modal="true">
            <NForm ref="genForm" :model="model" :rules="rules">
                <NFormItem label="描述" path="description">
                    <NInput type="textarea" v-model:value="model.description" :resizable="false" :rows="3" />
                </NFormItem>
                <NFormItem label="大纲" path="chapters">
                    <div class="w-full">
                        <OutlineEditor v-model="model.chapters" />
                        <div class="flex mt-1 items-center">
                            <NButton
                                size="small"
                                quaternary
                                type="primary"
                                :loading="genChaptering"
                                @click="genChapters"
                            >
                                生成大纲
                            </NButton>
                            <div class="flex-1 text-sm text-right">Tab / Shift + Tab 切换级别</div>
                        </div>
                    </div>
                </NFormItem>
            </NForm>
            <NSpace class="text-right" justify="end">
                <NButton @click="() => (showGenDialog = false)">取消</NButton>
                <NButton type="primary" @click="gen" :loading="loading">确认生成</NButton>
            </NSpace>
        </n-card>
    </n-modal>
    <n-modal v-model:show="showReferenceDialog">
        <n-card style="width: 800px" title="参考文献" :bordered="false" size="huge" role="dialog" aria-modal="true">
            <div class="flex" @keyup.enter="searchReference">
                <NInput
                    class="mr-4"
                    v-model:value="referenceKeywords"
                    placeholder="请输入关键词"
                    clearable
                    onClearClick="() => (referenceKeywords = '')"
                />
                <NButton type="primary" @click="searchReference" :loading="searchingReference"> 搜索 </NButton>
            </div>
            <div class="p-4 overflow-auto" style="height: calc(80vh - 300px)">
                <div class="mt-4" v-for="(item, i) in referenceData" :key="i">{{ item.reference[0].value[0] }}</div>
            </div>
            <NButton @click="copyReference" v-if="referenceData.length > 0">复制</NButton>
        </n-card>
    </n-modal>
</template>
<script lang="ts" setup>
import { h, defineComponent, ref, reactive, onMounted, Ref, computed, VNode } from 'vue'
import {
    NButton,
    NDataTable,
    NTag,
    NSpace,
    useMessage,
    type DataTableColumn,
    useDialog,
    NModal,
    NCard,
    NForm,
    FormInst,
    NFormItem,
    NInput,
    NPageHeader,
    NLayout,
    NLayoutHeader,
    NLayoutContent,
    NAvatar,
    NPopover,
    NDropdown,
    NDrawer,
    NDrawerContent,
    NInputGroup,
    NSelect,
    NCheckbox,
    NRadio,
    NDatePicker,
    NRadioGroup,
    NRadioButton,
    NIcon,
    NUpload,
    UploadFileInfo,
    DropdownOption,
    DropdownGroupOption
} from 'naive-ui'
import {
    fetchPaperOrders,
    fetchGenPaper,
    fetchPaperResults,
    fetchPaperAttachments,
    fetchCreatePaperOrder,
    fetchUpdatePaperOrder,
    fetchGenChapters,
    fetchSearchReference
} from '@/api'
import { post, put, del } from '@/utils/request'
import { format, parseISO } from 'date-fns'
import { UserAvatar } from '@/components/common'
import { LoginForm } from '@/components/common'
import { useUserStore } from '@/store'
import { storeToRefs } from 'pinia'
import MarkdownIt from 'markdown-it'
import mdKatex from '@traptitech/markdown-it-katex'
import mila from 'markdown-it-link-attributes'
import hljs from 'highlight.js'
import { t } from '@/locales'
import Vditor from 'vditor'
import 'vditor/src/assets/less/index.less'
import OutlineEditor from '@/components/common/OutlineEditor.vue'
import { useRouter } from 'vue-router'
import { useClipboard } from '@vueuse/core'
import { copyText } from '@/utils/format'
import { Dots } from '@vicons/tabler'
import resolveUrl from 'resolve-url'
import { useAuthStore } from '@/store'
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 deliveryStatusOptions = [
    {
        label: '已交开题',
        value: '已交开题'
    },
    {
        label: '修改开题中',
        value: '修改开题中'
    },
    {
        label: '开题定稿',
        value: '开题定稿'
    },
    {
        label: '已交任务书',
        value: '已交任务书'
    },
    {
        label: '修改任务书中',
        value: '修改任务书中'
    },
    {
        label: '任务书定稿',
        value: '任务书定稿'
    },
    {
        label: '已交初稿',
        value: '已交初稿'
    },
    {
        label: '改稿中',
        value: '改稿中'
    },
    {
        label: '定稿',
        value: '定稿'
    }
]
const educationOptions = [
    {
        label: '专科',
        value: '专科'
    },
    {
        label: '本科',
        value: '本科'
    },
    {
        label: '专升本',
        value: '专升本'
    },
    {
        label: '成人本科',
        value: '成人本科'
    },
    {
        label: '硕士',
        value: '硕士'
    },
    {
        label: '在职硕士',
        value: '在职硕士'
    }
]
onMounted(() => {
    getData()
    if (!isLogin.value) {
        showLogin.value = true
    }
})
function logout() {
    dialog.create({
        title: '提示',
        content: '确认要退出登录吗？',
        positiveText: '退出登录',
        negativeText: '取消',
        maskClosable: false,
        onPositiveClick: () => {
            userStore.logout()
            message.success('退出登录成功')
            tableData.value = []
            resultData.value = []
        }
    })
}
function onLogin() {
    showLogin.value = false
    getData()
}
const tableData = ref([])
function timeFormatter(rowData: any, rowIndex: number) {
    return format(parseISO(rowData.createdAt), 'yyyy-MM-dd HH:mm:ss')
}
const columns: DataTableColumn[] = [
    {
        title: '#',
        key: 'id',
        width: 100
    },
    {
        title: '创建时间',
        key: 'createdAt',
        render: timeFormatter,
        width: 180
    },
    {
        title: '接单渠道',
        key: 'orderChannel'
    },
    {
        title: '订单号',
        key: 'orderNumber'
    },
    {
        title: '标题',
        key: 'title'
    },
    {
        title: '备注',
        key: 'remark'
    },
    {
        title: '状态',
        key: 'length',
        align: 'center',
        render(rowData: any, rowIndex: number) {
            switch (rowData.status) {
                case 'pending':
                    return h(NTag, null, { default: () => '待生成' })
                case 'generating':
                    return h(NTag, { type: 'info' }, { default: () => '生成中' })
                case 'complete':
                    return h(NTag, { type: 'success' }, { default: () => '已生成' })
                default:
                    return '未知'
            }
        }
    },
    {
        title: '操作',
        key: 'actions',
        align: 'center',
        width: '250px',
        render(row: any) {
            return h(NSpace, { justify: 'center' }, () => [
                roles.value.includes('paperGen')
                    ? h(
                          NButton,
                          {
                              type: 'primary',
                              size: 'small',
                              onClick: () => {
                                  model.value = {
                                      major: row.major,
                                      title: row.title,
                                      description: row.description,
                                      remark: row.remark,
                                      chapters: row.chapters || []
                                  }
                                  orderId.value = row.id
                                  showGenDialog.value = true
                              }
                          },
                          () => '生成'
                      )
                    : null,
                h(
                    NButton,
                    {
                        strong: true,
                        size: 'small',
                        onClick: () => showResults(row)
                    },
                    { default: () => '查看' }
                ),
                h(
                    NButton,
                    {
                        strong: true,
                        tertiary: true,
                        size: 'small',
                        onClick: () => editRow(row)
                    },
                    { default: () => '编辑' }
                )
            ])
        }
    }
]

const paginationReactive = reactive({
    page: 1,
    pageSize: 20,
    showSizePicker: true,
    pageSizes: [10, 20, 50, 100],
    pageCount: 1,
    onChange: (page: number) => {
        paginationReactive.page = page
    },
    onUpdatePageSize: (pageSize: number) => {
        paginationReactive.pageSize = pageSize
        paginationReactive.page = 1
    }
})
const search = ref('')
async function getData(reset = false) {
    if (reset) {
        paginationReactive.page = 1
    }
    if (roles.value.includes('paperGen') || roles.value.includes('paperOrder')) {
        const res: any = await fetchPaperOrders({
            page: {
                page: paginationReactive.page,
                limit: paginationReactive.pageSize
            },
            search: {
                where: {
                    title: search.value || undefined
                },
                order: {
                    createdAt: 'desc'
                }
            }
        })
        tableData.value = res.items
        paginationReactive.pageCount = res.meta.totalPages
    } else {
        tableData.value = []
        paginationReactive.pageCount = 1
    }
}

async function gen() {
    await genForm.value?.validate()
    const d = dialog.success({
        title: '生成',
        content: '确认开始生成吗？',
        positiveText: '确认',
        negativeText: '取消',
        onPositiveClick: async () => {
            d.loading = true
            await submit(true)
            return fetchGenPaper(orderId.value)
                .then(() => {
                    message.success('已开始生成')
                    showGenDialog.value = false
                    getData()
                })
                .catch((e: any) => {
                    message.error(e.message)
                })
                .finally(() => {
                    d.loading = false
                })
        }
    })
}

const orderId = ref<any>(null)
const showModal = ref(false)
const showResultType = ref('doc')
const resultData = ref([])
const attachmentData = ref([])
const resultsPagination = reactive({
    page: 1,
    pageSize: 10,
    showSizePicker: false,
    pageSizes: [10],
    pageCount: 1,
    onChange: (page: number) => {
        resultsPagination.page = page
    },
    onUpdatePageSize: (pageSize: number) => {
        resultsPagination.pageSize = pageSize
        resultsPagination.page = 1
    }
})
const attachmentsPagination = reactive({
    page: 1,
    pageSize: 10,
    showSizePicker: false,
    pageSizes: [10],
    pageCount: 1,
    onChange: (page: number) => {
        attachmentsPagination.page = page
    },
    onUpdatePageSize: (pageSize: number) => {
        attachmentsPagination.pageSize = pageSize
        attachmentsPagination.page = 1
    }
})
async function showResults(row: any) {
    orderId.value = row.id
    showModal.value = true
    resultData.value = []
    getResults()
    getAttachments()
}
function getResults() {
    fetchPaperResults({
        page: {
            page: resultsPagination.page,
            limit: resultsPagination.pageSize
        },
        search: {
            order: {
                createdAt: 'desc'
            },
            where: {
                orderId: orderId.value
            }
        }
    }).then((res: any) => {
        console.log(res)
        resultData.value = res.items
        resultsPagination.pageCount = res.meta.totalPages
    })
}
function getAttachments() {
    fetchPaperAttachments({
        page: {
            page: attachmentsPagination.page,
            limit: attachmentsPagination.pageSize
        },
        search: {
            order: {
                createdAt: 'desc'
            },
            where: {
                orderId: orderId.value
            }
        }
    }).then((res: any) => {
        console.log(res)
        attachmentData.value = res.items
        attachmentsPagination.pageCount = res.meta.totalPages
    })
}
const resultColumns: DataTableColumn[] = [
    { title: '#', key: 'id' },
    { title: '生成时间', key: 'createdAt', render: timeFormatter },
    { title: '耗时', key: 'duration', render: (row: any) => `${(row.duration / 60).toFixed(1)}分钟` },
    {
        title: 'Token消耗',
        key: 'tokenUsage',
        width: '250px',
        render: (row: any) =>
            `P:${(row.tokenUsage.promptTokens / 1000).toFixed(1)}K / C:${(
                row.tokenUsage.completionTokens / 1000
            ).toFixed(1)}K / T:${(row.tokenUsage.totalTokens / 1000).toFixed(1)}K`
    },
    {
        title: '操作',
        key: 'action',
        align: 'center',
        width: '150px',
        render(row: any) {
            return h(
                NDropdown,
                {
                    size: 'small',
                    options: [
                        {
                            label: 'Word',
                            key: 'word'
                        },
                        {
                            label: 'Markdown',
                            key: 'markdown'
                        }
                    ],
                    trigger: 'click',
                    onSelect(key: string | number) {
                        console.log(key)
                        if (key === 'word') {
                            window.open(row.fileUrl, '_blank')
                        } else {
                            // Create element with <a> tag
                            const link = document.createElement('a')

                            // Create a blog object with the file content which you want to add to the file
                            const file = new Blob([row.content], { type: 'text/plain' })

                            // Add file content in the object URL
                            link.href = URL.createObjectURL(file)

                            // Add file name
                            link.download = row.fileUrl
                                .split('/')
                                .pop()
                                .replace(/\.docx$/, '.md')

                            // Add click event to <a> tag to save file.
                            link.click()
                            URL.revokeObjectURL(link.href)
                        }
                    }
                },
                () => h(NButton, { size: 'small', type: 'primary' }, { default: () => '下载' })
            )
        }
    }
]
const attachmentColumns: DataTableColumn[] = [
    { title: '#', key: 'id' },
    { title: '上传时间', key: 'createdAt', render: timeFormatter },
    { title: '文件名', key: 'name' },
    {
        title: '操作',
        key: 'action',
        align: 'center',
        width: '150px',
        render(row: any) {
            return h(
                NDropdown,
                {
                    size: 'small',
                    options: [
                        {
                            label: '下载',
                            key: 'download'
                        },
                        {
                            label: '删除',
                            key: 'delete'
                        }
                    ],
                    trigger: 'click',
                    renderLabel: (option: DropdownOption) =>
                        option.key === 'delete'
                            ? h('span', { style: 'color: red' }, option.label as string)
                            : h('span', {}, option.label as string),
                    onSelect(key: string | number) {
                        console.log(key)
                        if (key === 'delete') {
                            dialog.warning({
                                title: 'Confirm',
                                content: '确认删除?',
                                positiveText: '确认',
                                negativeText: '取消',
                                onPositiveClick: async () => {
                                    await del({
                                        url: `/paper/attachments/${row.id}`
                                    })
                                    getAttachments()
                                },
                                onNegativeClick: () => {}
                            })
                        } else if (key === 'download') {
                            const link = document.createElement('a')
                            link.href = row.url
                            link.download = encodeURIComponent(row.name)
                            console.log(row.name)
                            link.click()
                        }
                    }
                },
                () =>
                    h(NButton, {
                        size: 'small',
                        renderIcon: () => h(NIcon, null, () => h(Dots))
                    })
            )
        }
    }
]

const showForm = ref(false)
const genForm: Ref<FormInst | null> = ref(null)
const form: Ref<FormInst | null> = ref(null)
const model: Ref<any> = ref({
    major: '',
    title: '',
    description: '',
    remark: '',
    chapters: []
})
const rules = {
    major: [{ required: true, message: '请输入专业' }],
    title: [{ required: true, message: '请输入标题' }],
    description: [{ required: true, message: '请输入描述' }]
}
const showGenDialog = ref(false)
const loading = ref(false)
function onCreate() {
    if (roles.value.includes('paperGen') || roles.value.includes('paperOrder')) {
        orderId.value = null
        model.value = {
            major: '',
            title: '',
            description: '',
            remark: '',
            chapters: []
        }
        form.value?.restoreValidation()
        showForm.value = true
    } else {
        dialog.error({
            title: '无权限',
            positiveText: '返回首页',
            closable: false,
            maskClosable: false,
            onPositiveClick: () => {
                router.replace('/home')
            }
        })
    }
}
async function submit(gen = false) {
    if (gen) {
        await genForm.value?.validate()
    } else {
        await form.value?.validate()
    }
    try {
        loading.value = true
        await (orderId.value
            ? fetchUpdatePaperOrder(orderId.value, { ...model.value })
            : fetchCreatePaperOrder({ ...model.value }))
        loading.value = false
        showForm.value = false
        getData()
    } catch (e: any) {
        message.error(e.message)
        loading.value = false
    }
}
function editRow(row: any) {
    model.value = {
        ...row,
        chapters: row.chapters || []
    }
    orderId.value = row.id
    form.value?.restoreValidation()
    showForm.value = true
}

const showEditor = ref(false)
function onEditorShow() {
    console.log('show')
    const vditor = new Vditor('editor', {
        height: '100%'
    })
}

const genChaptering = ref(false)
async function genChapters() {
    await form.value?.validate()
    try {
        genChaptering.value = true
        const chapters = await fetchGenChapters({
            id: orderId.value,
            major: model.value.major,
            title: model.value.title,
            description: model.value.description
        })
        // const chapters = [
        //     {
        //         chapterName: '引言',
        //         chapterDesc: '介绍论文的研究背景、动机和目的',
        //         sections: [
        //             {
        //                 sectionName: '研究背景',
        //                 sectionDesc: '阐述电器销售系统的重要性和发展现状'
        //             },
        //             {
        //                 sectionName: '研究动机',
        //                 sectionDesc: '说明为什么选择基于Java开发电器销售系统'
        //             },
        //             {
        //                 sectionName: '研究目的和意义',
        //                 sectionDesc: '明确研究目标和对电器销售领域的贡献'
        //             }
        //         ]
        //     },
        //     {
        //         chapterName: '文献综述',
        //         chapterDesc: '对电器销售系统及相关技术和工具进行综述',
        //         sections: [
        //             {
        //                 sectionName: '电器销售系统现状',
        //                 sectionDesc: '分析电器销售系统的发展趋势和市场需求'
        //             },
        //             {
        //                 sectionName: '相关技术和工具',
        //                 sectionDesc: '介绍与Java开发电器销售系统相关的技术和工具'
        //             }
        //         ]
        //     },
        //     {
        //         chapterName: '系统需求分析与设计',
        //         chapterDesc: '分析电器销售系统的功能和非功能需求，并进行系统架构设计',
        //         sections: [
        //             {
        //                 sectionName: '功能需求',
        //                 sectionDesc: '明确前台销售和后台管理的功能要求'
        //             },
        //             {
        //                 sectionName: '非功能需求',
        //                 sectionDesc: '阐述性能、安全、可维护性和用户界面设计的要求'
        //             },
        //             {
        //                 sectionName: '系统架构设计',
        //                 sectionDesc: '设计系统的前端、后端和数据库架构'
        //             }
        //         ]
        //     },
        //     {
        //         chapterName: '实现与测试',
        //         chapterDesc: '具体实现电器销售系统的功能模块，并进行系统测试',
        //         sections: [
        //             {
        //                 sectionName: '开发环境和工具选择',
        //                 sectionDesc: '选择合适的开发环境和工具进行系统实现'
        //             },
        //             {
        //                 sectionName: '功能模块实现和集成',
        //                 sectionDesc: '详细描述各个功能模块的实现，并进行集成测试'
        //             },
        //             {
        //                 sectionName: '系统测试策略和方法',
        //                 sectionDesc: '说明系统测试的策略和方法，确保系统质量'
        //             },
        //             {
        //                 sectionName: '测试结果分析和评估',
        //                 sectionDesc: '分析测试结果并评估系统的性能和功能完整性'
        //             }
        //         ]
        //     },
        //     {
        //         chapterName: '性能优化与安全保障',
        //         chapterDesc: '对电器销售系统进行性能优化和安全保障措施',
        //         sections: [
        //             {
        //                 sectionName: '性能评估和优化策略',
        //                 sectionDesc: '评估系统性能，并提出性能优化策略'
        //             },
        //             {
        //                 sectionName: '安全风险识别与防护技术',
        //                 sectionDesc: '分析系统的安全风险并提出相应的防护技术'
        //             }
        //         ]
        //     },
        //     {
        //         chapterName: '结果与讨论',
        //         chapterDesc: '分析系统实现的功能和性能结果，并讨论用户反馈与建议',
        //         sections: [
        //             {
        //                 sectionName: '系统功能与性能结果分析',
        //                 sectionDesc: '对系统实现的功能和性能进行详细分析'
        //             },
        //             {
        //                 sectionName: '用户反馈与建议',
        //                 sectionDesc: '收集用户的反馈和建议，并进行讨论和改进'
        //             }
        //         ]
        //     },
        //     {
        //         chapterName: '总结与展望',
        //         chapterDesc: '对论文进行总结，并展望未来的研究方向和改进建议',
        //         sections: [
        //             {
        //                 sectionName: '主要研究成果总结',
        //                 sectionDesc: '总结论文取得的主要研究成果'
        //             },
        //             {
        //                 sectionName: '存在的问题和不足',
        //                 sectionDesc: '概述论文中存在的问题和不足之处'
        //             },
        //             {
        //                 sectionName: '后续研究方向和改进建议',
        //                 sectionDesc: '提出未来的研究方向和改进建议'
        //             }
        //         ]
        //     }
        // ]
        model.value.chapters = chapters as any
    } catch (error: any) {
        message.error(error.message)
    }
    genChaptering.value = false
}

const showReferenceDialog = ref(false)
const referenceKeywords = ref('')
const referenceData: Ref<any[]> = ref([])
const searchingReference = ref(false)
async function searchReference() {
    if (!referenceKeywords.value) {
        message.error('请输入关键词')
        return
    }
    searchingReference.value = true
    referenceData.value = []
    try {
        const res: any = await fetchSearchReference(referenceKeywords.value)
        res.forEach((item: any, index: number) => {
            item.reference.forEach((r: any) => {
                for (let i = 0; i < r.value.length; i++) {
                    r.value[i] = r.value[i].replace(/^\[\d+\]/g, `[${index + 1}]`)
                }
            })
        })
        referenceData.value = res
    } catch (error: any) {
        message.error(error.message)
    }
    searchingReference.value = false
}
async function copyReference() {
    const text = referenceData.value
        .map((item: any) => {
            return item.reference[0].value[0]
        })
        .join('\n')
    console.log(text)
    const { copy } = useClipboard({ legacy: true })
    await copy(text)
}

const uploadUrl = resolveUrl(import.meta.env.VITE_APP_API_BASE_URL, '/api/file/upload')
const authStore = storeToRefs(useAuthStore())
const uploadHeaders = computed(() => {
    return {
        Authorization: `Bearer ${authStore.token.value}`
    }
})
function onUploaded(options: { file: UploadFileInfo; event?: ProgressEvent }) {
    const res = (event?.target as XMLHttpRequest).response
    console.log(JSON.parse(res).url)
    put({
        url: '/paper/attachments',
        data: {
            orderId: orderId.value,
            name: options.file.name,
            url: JSON.parse(res).url
        }
    }).then(() => {
        getAttachments()
    })
}
</script>
<style lang="less" scoped>
:deep(.edit-form) {
    flex-wrap: wrap;
    .n-form-item {
        width: calc(33.33% - 18px);
    }
}
</style>
