<template>
    <div class="send-email flex" v-loading="dataLoadng" v-if="sendSuccess == 'default'">
        <div class="header flex-center">
            <div class="header-btn">
                <el-button type="primary" :loading="loading" :disabled="form.recipientls.length == 0 || fileLoading" @click="send()">发送</el-button>
                <el-button :loading="loading" @click="send('draft')">保存草稿</el-button>
                <el-button @click="preview">预览</el-button>
            </div>
            <el-select v-model="selectedEmail" @change="changeUserEmail">
                <el-option v-for="item in emailsData" :label="item.mailAccount" :value="item.id"></el-option>
            </el-select>
        </div>
        <div class="content flex">
            <div class="send-content">
                <div class="send-input flex-center">
                    <span class="send-label">收件人</span>
                    <SendInput
                        :ref="($event: any) => setItemRef($event, 'recipientls')"
                        v-model="form.recipientls"
                        @inputFocus="inputFocus('recipientls')"
                    />
                </div>
                <div class="send-input flex-center">
                    <span class="send-label">
                        <span style="vertical-align: middle;" @click="copyFlag = !copyFlag">
                            <i-ep-CaretBottom v-if="copyFlag"  />
                            <i-ep-CaretRight v-else />
                        </span>
                        抄送
                    </span>
                    <SendInput
                        :ref="($event: any) => setItemRef($event, 'recipientCcls')"
                        v-model="form.recipientCcls"
                        @inputFocus="inputFocus('recipientCcls')"
                    />
                </div>
                <div class="send-input flex-center" v-show="copyFlag">
                    <span class="send-label">密件抄送</span>
                    <SendInput
                        :ref="($event: any) => setItemRef($event, 'recipientBccls')"
                        v-model="form.recipientBccls"
                        @inputFocus="inputFocus('recipientBccls')"
                    />
                </div>
                <div class="send-input flex-center">
                    <span class="send-label">
                        <!-- <span style="vertical-align: middle;" @click="themeFlag = !themeFlag">
                            <i-ep-CaretBottom v-if="themeFlag"  />
                            <i-ep-CaretRight v-else />
                        </span> -->
                        主题
                    </span>
                    <el-autocomplete
                        style="width: 100%;"
                        v-model="form.subject"
                        :fetch-suggestions="querySearch"
                        @select="subjectSelect"
                    >
                    </el-autocomplete>
                </div>
                <!-- <div class="send-input flex-center" v-show="themeFlag">
                    <span class="send-label">备注</span>
                    <el-input />
                </div> -->
                <div class="search-item flex">
                    <el-select placeholder="选择邮件模版" @change="selectTemplate">
                        <el-option v-for="item in templateData['1']" :label="item.templateTitle" :value="item.id"></el-option>
                    </el-select>
                    <el-select placeholder="选择常用语" @change="selectCommonPhrases">
                        <el-option v-for="item in templateData['0']" :label="item.templateTitle" :value="item.id"></el-option>
                    </el-select>
                    <!-- <el-select placeholder="选择分类"></el-select>
                    <el-select placeholder="选择标记"></el-select> -->
                    <el-checkbox label="已读回执" v-model="form.isReceipt" :true-value="1" :false-value="0" style="margin-left: 15px"></el-checkbox>
                    <!-- <el-checkbox label="阅读跟踪" v-model="form.isTrack" :true-value="1" :false-value="0"></el-checkbox>
                    <el-checkbox label="阅读后消息提醒" v-model="form.readRemind" :true-value="1" :false-value="0"></el-checkbox> -->
                    <el-checkbox label="定时发信" v-model="isDelaySend" @change="changeDelaySend"></el-checkbox>
                    <el-date-picker
                        v-if="isDelaySend"
                        type="datetime"
                        placeholder="请选择时间"
                        format="YYYY-MM-DD HH:mm"
                        time-format="HH:mm"
                        value-format="YYYY-MM-DD HH:mm"
                        v-model="form.delaySendTime"
                        :clearable="false"
                    />
                </div>
                <div class="msg-item flex">
                    <div class="flex" style="flex-direction:column; flex: 1">
                        <ckeditor
                            class="send-ckeditor"
                            placeholder="智能写信新体验，试试AI润色让文字焕发活力"
                            @sendContnet="getContent"
                            :content="form.content"
                            ref="ckeditorRef"
                        ></ckeditor>
                        <div class="ai-button" v-if="aiShow">
                            <el-button v-for="item in aiButton" @click="aiButtonClick(item)">
                                <SvgIcon :iconClass="`ai-${ item.value }`" />
                                {{ item.label }}
                            </el-button>
                        </div>
                        <div class="ai-div">
                            <p>智能写信新体验，试试AI润色让文字焕发活力</p>
                            <el-button type="primary" @click="aiShow = !aiShow">AI润色</el-button>
                        </div>
                    </div>
                    <div class="file-div" v-loading="fileLoading">
                        <div class="file-header flex-center">
                            <span>附件列表</span>
                            <span>{{ (form.fileIds.length || 0) + (form.oldfileIds?.length || 0)}}个文件 已上传{{ fileSize }}K</span>
                        </div>
                        <el-upload
                            class="file-upload"
                            ref="uploadRef"
                            multiple
                            :file-list="fileList"
                            action=""
                            :http-request="uploadFile"
                            :on-change="changeFiles"
                            :on-remove="removeFile"
                            :auto-upload="false"
                            drag
                        >
                            <p style="margin-top: 50px" v-if="(form.fileIds.length + form.oldfileIds?.length) == 0">点击上传</p>
                        </el-upload>
                    </div>
                </div>
            </div>
            <div class="mailList">
                <el-radio-group v-model="listType" size="large">
                    <el-radio-button label="客户" value="1" />
                    <el-radio-button label="同事" value="2" />
                </el-radio-group>
                <div class="search" style="display:flex;" v-if="listType == '1'">
                    <el-input
                        v-model='custParam.blurry'
                        placeholder="搜索"
                        clearable
                    />
                    <el-button style="margin-left: 5px" type="primary" @click="serachCustomer">搜索</el-button>
                </div>
                <div class="person-list" style="height: 750px; overflow: auto"  v-loading="loadingData" >
                    <template v-if="listType == '1'">
                        <ul
                            v-infinite-scroll="getUser"
                            style=" padding: 0;margin: 0;list-style: none;"
                            :infinite-scroll-delay="1000"
                            infinite-scroll-distance="10"
                            :infinite-scroll-disabled="isLoadAll"
                        >
                            <li  style="height: 32px;" v-for="(item, i ) in personList" :key="i" class="list-item">
                                <p
                                    :title="`${ item.liaisonName } ${ item.country || '' } ${ item.customerName ? '（' + item.customerName + '）' : '' }<${ item.email }>`"
                                    @click="addMail(item.email, item)"
                                >
                                    {{ item.liaisonName }} {{ item.country }}
                                    {{ item.customerName ? '（' + item.customerName + '）' : '' }}<{{ item.email }}>
                                </p>
                            </li>
                        </ul>

                        <p v-if="isLoadAll"  style="text-align: center">没有更多数据了~~</p>
                    </template>
                    <template v-else>
                        <div v-for="item in colleagueList">
                            <p @click="item.show = !item.show">
                                <span style="vertical-align: middle;">
                                    <i-ep-CaretBottom v-if="item.show"  />
                                    <i-ep-CaretRight v-else />
                                </span>
                                {{ item.userName }}
                            </p>
                            <div v-if="item.show" style="margin-left: 22px">
                                <p v-for="email in item.mailAccounts" :title="email" @click="addMail(email)">{{ email }}</p>
                            </div>
                        </div>
                    </template>
                </div>
            </div>
        </div>
    </div>
    <div class="success-div" v-if="sendSuccess == 'success'">
        <p class="flex-center">
            <el-icon :size="30" color="#67c23a"><SuccessFilled /></el-icon>
            <h1 style="margin-left: 10px">邮件发送成功</h1>
        </p>
        <div class="flex-center">
            <el-button link @click="goEmail('inbox')">返回收件箱</el-button>
            <el-divider direction="vertical" />
            <el-button link @click="goEmail('sent')">前往已发送</el-button>
            <el-divider direction="vertical" />
            <el-button link @click="continueSend">继续写信</el-button>
        </div>
    </div>
    <!-- <div class="success-div" v-if="sendSuccess == 'error'">
        <p class="flex-center">
            <el-icon :size="30" color="#f56c6c"><CircleCloseFilled /></el-icon>
            <h1 style="margin-left: 10px">邮件发送失败,邮件已存入发件箱</h1>
        </p>
        <div class="flex-center">
            <el-button link @click="sendSuccess = 'default'">返回重发</el-button>
            <el-divider direction="vertical" />
            <el-button link @click="goEmail('senting')">前往发件箱</el-button>
            <el-divider direction="vertical" />
            <el-button link @click="continueSend">写新邮件</el-button>
        </div>
    </div> -->
    <el-dialog title="发送失败" v-model="errorVisible" width="380px" append-to-body>
        <p>排查方法：</p>
        <p>1、邮件收件人邮箱是否正确，可尝试切换收件人</p>
        <p>2、发件邮箱状态是否正常，可尝试切换发件人</p>
        <p>以上均无异常联系平台部</p>
        <template #footer>
			<div class="dialog-footer">
                <el-button @click="errorCancel">取 消</el-button>
				<el-button :loading="errorLoading" type="primary" @click="retransmission">重 发</el-button>
			</div>
		</template>
    </el-dialog>

    <el-dialog title="AI润色" v-model="aiVisible" width="780px" append-to-body>
        <div
            v-loading="aiLoading"
            element-loading-text="生成中..."
            style="min-height: 100px;"
        >
            <p v-html="aiMsg"></p>
        </div>
        <template #footer>
            <el-button v-if="!aiDone" @click="aiCancel">停止生成</el-button>
            <div v-else style="display: flex;justify-content: space-between;">
                <div>
                    <el-button @click="setAIContent('replace')">替换现有内容</el-button>
                    <el-button @click="setAIContent('insert')">插入到正文</el-button>
                    <el-button @click="sendSocketMessage(aiPrompt)">重新生成</el-button>
                </div>
                <div>
                    <el-button @click="copyText">复制</el-button>
                    <el-button @click="aiCancel">关闭</el-button>
                </div>
            </div>
            <p v-if="aiDone" class="ai-tips">AI产出内容仅供参考，请详细阅读后使用</p>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
    import {
        sendEmails,
        getEmailDetailContent,
        getUserEmails,
        getCustomerEmails,
        getColleagueEmails,
        saveDraft,
        setDefault,
        getEmailTemplateList,
        subjectRecordList,
        subjectRecordClick
    } from '@/api/emails'
    import SendInput from './components/sendInput.vue'
    import { getPrompt } from '@/api/system/messageTemplate'
    import { getToken } from '@/utils/auth';
    import type { UploadProps, UploadRawFile } from 'element-plus'
    import request from '@/utils/request';
    import ckeditor from '@/components/ckeditor/index.vue'
    import moment from 'moment';
    import SvgIcon from '@/components/SvgIcon/index.vue'

    const getContent = (val: string) => {
        form.value.content = val
    }

    const listType = ref('1')
    const copyFlag = ref(true)
    const themeFlag = ref(true)
    const loading = ref(false)
    const dataLoadng = ref(false)

    const router = useRouter();
    let queryData: { id?: string, type?: string, email?: string } = router.currentRoute.value.query

    const emailsData = ref([])
    const selectedEmail = ref('')
    const copySelectedEmail = ref('')
    const fileList = ref([])
    const editContent = ref('')
    const getUserEmail = () => {
        getUserEmails().then(res => {
            if(res.success) {
                if(res.result.length != 0) {
                    emailsData.value = res.result
                    selectedEmail.value = res.result.filter(item => item.useDefault == 1)[0].id || ''
                    copySelectedEmail.value = selectedEmail.value
                    if(queryData.id) {
                        dataLoadng.value = true
                        getEmailDetailContent({ mailId: queryData.id }).then(res => {
                            if(res.success) {
                                let result = res.result
                                let recipient = queryData.type == 'edit' ? result.recipient : result.from
                                if(queryData.type != 'forward') inputRef.value.recipientls.addMail(recipient)
                                // 回复全部的话，把原邮件收件人跟发件人都作为这封邮件的收件人
                                if(queryData.type == 'replyAll') inputRef.value.recipientls.addMail(result.recipient)
                                if(queryData.type == 'edit') {
                                    editContent.value += result.content
                                    form.value.subject = result.subject
                                    inputRef.value.recipientCcls.addMail(result.recipientCc)
                                    inputRef.value.recipientBccls.addMail(result.recipientBcc)
                                    fileList.value = (result.attachments || []).map(item => {
                                        let obj = {
                                            name: item.fileName + '.' + item.fileExt,
                                            url: item.filePath,
                                            id: item.id,
                                            fileSize: item.fileSize,
                                            type: 'old'
                                        }
                                        return obj
                                    })
                                    changeFile(fileList.value)
                                    if(result.folder != 'SENT') {
										form.value.id = result.id
									}
                                }else{
                                    editContent.value = `
                                        <p>--------------Original Message--------------</p>
                                        <p>From：${ recipient }</p>
                                        <p>To：${ result.recipient }</p>
                                        <p>Cc：${ result.recipientCc || '' }</p>
                                        <p>Subject：${ result.subject }</p>
                                        <p>Date：${ result.recipientDate }</p>
                                    `
                                    if(queryData.type == 'forward') { // 转发
                                        fileList.value = (result.attachments || []).map(item => {
                                            let obj = {
                                                name: item.fileName + '.' + item.fileExt,
                                                url: item.filePath,
                                                id: item.id,
                                                fileSize: item.fileSize,
                                                type: 'old'
                                            }
                                            return obj
                                        })
                                        changeFile(fileList.value)
                                        form.value.subject = 'Fw：' + result.subject
                                        editContent.value += ('<br />' + result.content)
                                    }else{
                                        form.value.replyMsgId = queryData.id
                                        form.value.subject = 'Re：' + result.subject
                                        if(queryData.type == 'reply' || queryData.type == 'replyAll'){ // 回复带上内容
                                            editContent.value += ('<br />' + result.content)
                                        }
                                        if(queryData.type == 'replyAll'){ // 回复全部带上抄送人
                                            inputRef.value.recipientCcls.addMail(result.recipientCc)
                                        }
                                    }
                                }
                                previewFileList.value = fileList.value
                                form.value.fileIds = []
                                form.value.oldfileIds = fileList.value.map(item => item.id)
                                setTimeout(() => {
                                    form.value.content = editContent.value
                                }, 500)
                            }
                        }).finally(() => {
                            dataLoadng.value = false
                        })
                    }
                    if(queryData.email) {
                        addMail(queryData.email)
                    }
                }else {
                    ElMessage.error('请先前往配置邮箱')
                }
            }
        })
    }

    const templateData = ref({
        '0': [],
        '1': []
    })
    const getTemplateData = (templateType: string) => {
        getEmailTemplateList({ pageIndex: 1, pageSize: 999999, templateType }).then(res => {
            if(res.success) {
                templateData.value[templateType] = res.result.records
            }
        })
    }

    const querySearch = (queryString, cb) => {
        subjectRecordList({ clickType: 1, title: queryString }).then(res => {
            if(res.success) {
                let subjectList = res.result.map(item => {
                    return { value: item.title, dataId: item.dataId }
                })
                cb(subjectList);
            }
        })
    }
    const subjectSelect = (item) => {
        subjectRecordClick({ clickType: 1, dataId: item.dataId })
    }

    const selectTemplate = (val: string) => {
        let content = templateData.value['1'].find(item => item.id == val).templateContent
        form.value.content = content + '<br />' + editContent.value
    }

    const ckeditorRef = ref()
    const selectCommonPhrases = (val: string) => {
        let content = templateData.value['0'].find(item => item.id == val).templateContent
        ckeditorRef.value?.ckeditor.insertHtml(content)
    }

    // 切换邮箱
    const changeUserEmail = (val: string) => {
        ElMessageBox.confirm(
            '切换操作会将选定的邮箱设置为默认邮箱，确定切换邮箱吗',
            '确认提示',
            { type: 'warning', confirmButtonText: '提交' }
        ).then(() => {
            copySelectedEmail.value = val
            setDefault(val)
            emailsData.value.map(item => {
                item.useDefault = item.id == val ? 1 : 0
            })
        }).catch(() => {
            selectedEmail.value = copySelectedEmail.value
        })
    }

    const personList = ref([])
    const personListData = ref([])
    const colleagueList = ref([])
    const isLoadAll = ref(false)
    const loadingData = ref(false)
    const custParam = reactive({
        scopeMenuId: null,
        pageSize: 50,
        pageIndex: 1,
        blurry: ''
    })
    const getUser = () => {
        if(loadingData.value) {
            return;
        }
        loadingData.value = true
        getCustomerEmails(custParam).then(res => {
            if(res.success) {
                res.result.records.map(item => {
                    personList.value.push(item)
                    for(let i = 1; i < 4; i++){
                        if(item['email' + i]){
                            personList.value.push({
                                liaisonName: item.liaisonName + '（备用' + i + '）',
                                email: item['email' + i],
                                customerName: item.customerName,
                                country: item.country
                            })
                        }
                    }
                })
                if(custParam.pageIndex >= res.result.pages){
                    isLoadAll.value = true
                }
                custParam.pageIndex ++
            }
            loadingData.value = false
        })
        getColleagueEmails().then(res => {
            if(res.success) {
                colleagueList.value = res.result.map(item => {
                    item.show = false
                    return item
                })
            }
        })
    }

    const customerName = ref()
    const serachCustomer = (val) =>{
        custParam.pageIndex = 1
        personList.value= []
        isLoadAll.value = false
        getUser()
        // getUser(val)
        // if(!val) {
        //     personList.value = personListData.value
        //     return
        // }
        // personList.value = personList.value.filter(function(item){
        //     return item.customerName.includes(val)||item.email.includes(val)||item.liaisonName.includes(val)
        // })
    }

    const isDelaySend = ref(0)
    const form = ref({
        content: '',
        recipientls: [],
        recipientCcls: [],
        recipientBccls: [],
        subject: '',
        fileIds: [],
        replyMsgId: '',
        id: undefined,
        isReceipt: 0,
        isTrack: 0,
        readRemind: 0,
        delaySendTime: '',
        oldfileIds: undefined
    })

    const changeDelaySend = (val) => {
        if(val) {
            form.value.delaySendTime = moment().format('YYYY-MM-DD HH:mm')
        }else {
            form.value.delaySendTime = ''
        }
    }

    const activeInput = ref('')
    const inputFocus = (type: string) => {
        activeInput.value = type
    }

    const inputRef = ref<any>({})
    const setItemRef = (el: any, type: string) => {
        if (el) {
            inputRef.value[type] = el
        }
    }

    const addMail = (mail, item?: any) => {
        inputRef.value[activeInput.value || 'recipientls'].addMail(mail)
        if(item && item.customerId) {
            customerParams.customerId.push(item.customerId)
            customerParams.customerName.push(item.customerName)
            customerParams.liaisonName.push(item.liaisonName)
        }
    }

    // 上传附件部分
    const token = getToken()
    const uploadRef = ref()
    const timer = ref<number>()
    const files = ref<UploadRawFile[]>([])
    const fileLoading = ref(false)
    const previewFileList = ref([])
    const changeFiles: UploadProps['onChange'] = (file) => {
        if(file.raw) {
            files.value.push(file.raw)
            previewFileList.value.push(file.raw)
        }
        clearTimeout(timer.value)
        timer.value = setTimeout(() => {
            uploadFile()
        }, 500)
    }
    const uploadFile = () => {
        fileLoading.value = true
        let formData = new FormData()
        files.value.map(item => {
            formData.append('files', item)
        })
        request({
            url: '/mail/file/cache_mail_file',
            method: 'post',
            data: formData,
            headers: {
                "Content-Type": "multipart/form-data",
                token
            }
        }).then(res => {
            if(res.success) {
                changeFile(res.result)
            }
        }).catch(() => {
            fileList.value = []
            ElMessage.error('上传失败，请稍后再试')
        }).finally(() => {
            fileLoading.value = false
            files.value = []
        })
    }

    const fileSize = ref(0)
    const changeFile = (files) => {
        files.map(item => {
            form.value.fileIds.push(item.id)
            fileSize.value = Number((fileSize.value + Number((Number(item.fileSize) / 1024))).toFixed(2))
        })
    }

    const removeFile = (file) => {
        fileSize.value = Number((fileSize.value - Number(((file.fileSize || file.size) / 1024).toFixed(2))).toFixed(2))
        if(file.type == 'old') {
            form.value.oldfileIds.splice(form.value.oldfileIds.findIndex(item => item == file.id), 1)
        }else {
            form.value.fileIds.splice(form.value.fileIds.findIndex(item => item == file.id), 1)
            previewFileList.value.splice(previewFileList.value.findIndex(item => item.id == file.id), 1)
        }
    }

    const sendSuccess = ref('default')
    const send = (type?: string) => {
        loading.value = true
        if(form.value.content.indexOf('<') == -1 && form.value.content.indexOf('</') == -1) {
            form.value.content = '<p>' + form.value.content + '</p>'
        }
        if(type == 'draft') {
            saveDraft(form.value).then(res => {
                if(res.success) {
                    ElMessage.success("保存草稿成功")
                    setTimeout(() => {
                        goEmail('draft')
                    }, 1000)
                }
            }).finally(() => {
                loading.value = false
            })
        }else {
            sendEmails(form.value).then(res => {
                if(res.success) {
                    sendSuccess.value = 'success'
                }else{
                    // sendSuccess.value = 'error'
                    errorVisible.value = true
                }
            }).finally(() => {
                loading.value = false
            })
        }
    }

    const errorVisible = ref(false)
    const errorLoading = ref(false)
    const retransmission = () => {
        errorLoading.value = true
        sendEmails(form.value).then(res => {
            if(res.success) {
                errorCancel()
                sendSuccess.value = 'success'
            }else{
                errorLoading.value = false
            }
        })
    }
    const errorCancel = () => {
        errorVisible.value = false
    }

    const goEmail = (type: string) => {
        router.replace('/email?type=' + type)
    }

    const continueSend = () => {
        window.location.reload()
    }

    const preview = () => {
        let params = JSON.parse(JSON.stringify(form.value))
        params.from = emailsData.value.filter(item => item.useDefault == 1)[0].mailAccount
        params.nowDate = moment().format('YYYY-MM-DD HH:mm:ss')
        params.fileList = previewFileList.value.map(item => {
            return { name: item.name || item.fileShowName }
        })
        let previewData = JSON.stringify(params)
        sessionStorage.setItem('previewData', previewData)
        const { href } = router.resolve({
            path: '/email/preview'
        })
        window.open(href, '_blank')
    }

    const aiButton = ref([
        { label: '润色', value: 'polish' },
        { label: '续写', value: 'rewrite' },
        { label: '内容纠错', value: 'error' },
        // { label: '格式优化', value: 'format' },
        { label: '关闭润色', value: 'close' }
    ])
    const aiShow = ref(false)
    const getImgUrl = (val: string) => {
        const str = 'ai-' + val + '.png'
        return new URL(`../../assets/icons/svg/` + str, import.meta.url).href
    }

    const aiButtonClick = (item) => {
        switch(item.value) {
            case 'close':
                aiShow.value = false
                break;
            default:
                if(!form.value.content){
                    ElMessage.error('请输入邮件内容')
                    return false
                }
                getPromptText(item)
                break;
        }
    }

    const aiPrompt = ref('')
    let customerParams = {
        customerId: [],
        customerName: [],
        liaisonName: []
    }
    const getPromptText = (item) => {
        let selectionText = ckeditorRef.value?.ckeditor.getSelection().getSelectedText()
        let templateCode = {
            'polish': 'EMAIL_POLISHING',
            'rewrite': 'EMAIL_CONTINUATION',
            'error': 'EMAIL_CORRECTION'
        }
        let content = selectionText || form.value.content
        let mailParams = {
            content: content,
            subject: form.value.subject,
            templateCode: templateCode[item.value]
        }
        let params: any = { ...mailParams }
        if(customerParams.customerId.length > 0) {
            params.customerId = customerParams.customerId.join(",")
            params.customerName = customerParams.customerName.join(",")
            params.liaisonName = customerParams.liaisonName.join(",")
        }
        getPrompt(params).then(res => {
            if(res.success) {
                aiVisible.value = true
                sendSocketMessage(res.result)
                aiPrompt.value = res.result
            }
        })
    }

    const aiVisible = ref(false)
    const aiLoading = ref(false)

    const ws = ref(null)
    const socketOpen = ref(false)
    const aiMsg = ref('')
    const aiDone = ref(false)
    const initWebSocket = (msg) => {
        aiLoading.value = true
        let tokenConfig = localStorage.getItem('Admin-Token')
        ws.value = new WebSocket(import.meta.env.VITE_APP_WS_HOST, [tokenConfig])
        //监听是否连接成功
        ws.value.onopen = () => {
            console.log('ws连接状态：' + ws.value.readyState);
            //连接成功则发送一个数据
            // this.ws.send('连接成功')
            sendSocketMessage(msg)
            socketOpen.value = true
        }
        //接听服务器发回的信息并处理展示
        ws.value.onmessage = (res) => {
            aiLoading.value = false
            if(res.data == '[done]') {
                aiDone.value = true
                if(ws.value) {
                    ws.value.close();
                }
                return false
            }
            aiMsg.value += res.data
        }

        //监听连接关闭事件
        ws.value.onclose = () => {
            //监听整个过程中websocket的状态
            console.log('ws连接状态：' + ws.value.readyState);
            socketOpen.value = false
            ws.value = null
        }

        //监听并处理error事件
        ws.value.onerror = function (error) {
            console.log(error);
            socketOpen.value = false
            ws.value = null
        }
    }

    const sendSocketMessage = (msg) => {
        aiMsg.value = ''
        aiLoading.value = true
        aiDone.value = false
        if(ws.value == null) {
            //如果ws断开连接需要重新连接
            initWebSocket(msg)
            return
        }
        ws.value.send(msg)
    }

    const aiCancel = () => {
        aiVisible.value = false
        if(ws.value) {
            ws.value.close();
        }
        aiMsg.value = ''
        aiLoading.value = true
        aiDone.value = false
    }

    const copyText = async() => {
        await navigator.clipboard.writeText(aiMsg.value);
        ElMessage.success('复制成功')
    }

    const setAIContent = (type: string) => {
        if(type == 'insert') {
            let editor = ckeditorRef.value?.ckeditor
            const range = editor.createRange();
            range.selectNodeContents(editor.editable())
            range.collapse(false)
            // 选择范围，这将设置光标位置
            editor.getSelection().selectRanges([range]);
            ckeditorRef.value?.ckeditor.insertHtml(aiMsg.value)
        }else {
            let replacedContent = aiMsg.value
            let selectionText = ckeditorRef.value?.ckeditor.getSelection().getSelectedText()
            if(selectionText) {
                replacedContent = form.value.content.replace(selectionText, aiMsg.value);
            }
            ckeditorRef.value?.ckeditor.setData(replacedContent)
        }
        aiCancel()
    }

    onMounted(() => {
        // getUser()
        getUserEmail()
        getTemplateData('0')
        getTemplateData('1')
        // 监听粘贴事件
        document.addEventListener('paste', function (event) {
            inputRef.value[activeInput.value].paste()
        })
    })
</script>

<style scoped lang="scss">
    .send-email{
        background: var(--el-bg-color-page);
        height: 100vh;
        flex-direction: column;
        .header{
            height: 56px;
            padding: 0 16px;
            background: #FFF;
            box-shadow: 0px 1px 0px 0px #F0F0F0;
            justify-content: space-between;
            .el-select{
                width: 150px;
                :deep(.el-select__wrapper){
                    box-shadow: none;
                }
            }
        }
        .content{
            padding: 16px;
            column-gap: 16px;
            flex: 1;
            height: 0;
            .send-content, .mailList{
                background: #FFF
            }
            .send-content{
                flex: 1;
                padding: 16px;
                display: flex;
                flex-direction: column;
                .send-input{
                    margin-bottom: 12px;
                    .send-label{
                        color: #666666;
                        width: 60px;
                        margin-right: 8px;
                        text-align: right;
                    }
                    .el-input{
                        height: 32px;
                    }
                    svg{
                        margin-right: 5px;
                        cursor: pointer;
                    }
                }
                .search-item{
                    column-gap: 15px;
                    margin-bottom: 12px;
                    .el-select{
                        width: 150px;
                    }
                    .el-checkbox{
                        margin-right: 15px;
                    }
                }
                .msg-item{
                    flex: 1;
                    .editor-div{
                        flex: 1;
                        display: flex;
                        flex-direction: column;
                        :deep(.editor){
                            height: 100%;
                            display: flex;
                            flex-direction: column;
                            .ql-toolbar{
                                background: #F8F8F8;
                            }
                        }
                    }
                    .file-div{
                        width: 300px;
                        border: 1px solid #DCDEE2;
                        border-left: 0;
                        display: flex;
                        flex-direction: column;
                        .file-header{
                            height: 41px;
                            background: #f5f7f9;
                            justify-content: space-between;
                            padding: 0 10px;
                            border-bottom: 1px solid #DCDEE2;
                        }
                        :deep(.file-upload){
                            flex: 1;
                            position: relative;
                            .el-upload{
                                height: 100%;
                                .el-upload-dragger{
                                    height: 100%;
                                    padding: 10px;
                                    border: none;
                                }
                            }
                            .el-upload-list{
                                position: absolute;
                                top: 0;
                                width: 100%;
                            }
                        }
                    }
                    .ai-div{
                        height: 48px;
                        border: 1px solid #d1d1d1;
                        padding: 0 16px;
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                    }
                    .ai-button{
                        padding: 16px 15px;
                        border: 1px solid #d1d1d1;
                        border-top: none;
                        border-bottom: none;
                        .svg-icon{
                            margin-right: 6px;
                            width: 16px;
                            height: 16px;
                        }
                    }
                }
            }
            .mailList{
                width: 240px;
                display: flex;
                flex-direction: column;
                .el-radio-button{
                    width: 120px;
                    :deep(.el-radio-button__inner){
                        width: 100%;
                    }
                }
                .search{
                    margin: 15px 15px 0;
                }
                .person-list{
                    padding: 15px;
                    overflow: auto;
                    p{
                        margin-bottom: 8px;
                        cursor: pointer;
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;
                    }
                }
            }
        }
    }
    .success-div, .error-div{
        padding-top: 200px;
        .flex-center{
            justify-content: center;
        }
        .el-button{
            font-size: 16px;
        }
    }
    .ai-tips{
        margin-top: 10px;
        text-align: left;
        color: #666;
    }
</style>
