<template>
    <div class="email flex">
        <div class="left">
            <el-button style="width: 100%" @click="backCRM()">
                <SvgIcon iconClass="back" style="margin-right: 5px;" />领存CRM
            </el-button>
            <div class="write-btn flex-column">
                <el-button type="primary" @click="sendEmail">写邮件</el-button>
                <el-button type="warning" @click="receiveEmail" :loading="receiveLoading">收邮件</el-button>
            </div>
            <div class="email-btn flex-column">
                <el-button
                    link
                    v-for="item in emailBtn"
                    :class="{ active: item.value == activeMail }"
                    @click="changeEmail(item)"
                >
                    <SvgIcon :iconClass="`email-${ item.value }${ item.value == activeMail ? '-checked' : '' }`" />
                    {{ item.label }}{{ item.countType && countData[item.countType] > 0 ? `（${ countData[item.countType] || 0 }）` : '' }}
                </el-button>
                <div class="my-folder" @click="showFolderList = !showFolderList">
                    <el-icon style="margin-right: 9px">
                        <CaretRight v-if="!showFolderList" />
                        <CaretBottom v-else />
                    </el-icon>
                    我的文件夹{{ countData?.folderCount > 0 ? `（${ countData?.folderCount }）` : '' }}
                </div>
                <div class="folder-list" v-if="showFolderList">
                    <el-button
                        link
                        v-for="item in folderData"
                        :class="{ active: item.value == activeMail }"
                        @click="changeEmail(item, item.id)"
                    >
                        {{ item.folderName }}{{ countData?.folderUnReadMap?.[item.id] ? `（${ countData?.folderUnReadMap?.[item.id] || 0 }）` : '' }}
                    </el-button>
                </div>
            </div>
            <el-divider />
            <div class="email-btn flex-column">
                <el-button
                    link
                    v-for="item in emailStatusBtn"
                    :class="{ active: item.value == activeMail }"
                    @click="changeEmail(item)"
                >
                    <SvgIcon :iconClass="`email-${ item.value }${ item.value == activeMail ? '-checked' : '' }`" />
                    {{ item.label }}{{ item.countType && countData[item.countType] > 0 ? `（${ countData[item.countType] || 0 }）` : '' }}
                </el-button>
            </div>
        </div>
        <div class="right flex">
            <div class="top-search flex-center">
                <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                    <el-form-item prop="blurry">
                        <el-input
                            placeholder="搜索关键词"
                            prefix-icon="Search"
                            v-model="queryParams.blurry"
                            @input="changeSearch('blurry')"
                        />
                    </el-form-item>
                    <el-form-item prop="customerName" v-if="activeMail != 'annex'">
                        <el-input
                            :placeholder="
                                `搜索${ activeMail == 'allClue' ? '线索' : '客户' }名称`
                            "
                            prefix-icon="Search"
                            v-model="queryParams.customerName"
                            @input="changeSearch('customerName')"
                        />
                    </el-form-item>
                    <el-form-item prop="emailAddress" v-if="!['allCustomer', 'allClue', 'annex'].includes(activeMail)">
                        <el-input
                            placeholder="搜索邮箱"
                            prefix-icon="Search"
                            v-model="queryParams.emailAddress"
                            @input="changeSearch('emailAddress')"
                        />
                    </el-form-item>
                    <template v-if="activeMail == 'allCustomer' || activeMail == 'allClue'">
                        <template v-if="activeMail == 'allCustomer'">
                            <el-form-item prop="customerTypeDictValue">
                                <SelectDict
                                    v-model="queryParams.customerTypeDictValue"
                                    placeholder="客户类型"
                                    dictCode="customer_type"
                                    @onchange="changeSearch('customerTypeDictValue')"
                                ></SelectDict>
                            </el-form-item>
                            <el-form-item prop="customerLevelDictValue">
                                <SelectDict
                                    v-model="queryParams.customerLevelDictValue"
                                    placeholder="客户等级"
                                    dictCode="customer_level"
                                    @onchange="changeSearch('customerLevelDictValue')"
                                ></SelectDict>
                            </el-form-item>
                        </template>
                        <template v-if="activeMail == 'allClue'">
                            <el-form-item prop="clueStatusDictValue">
                                <SelectDict
                                    v-model="queryParams.clueStatusDictValue"
                                    placeholder="线索状态"
                                    dictCode="clue_status"
                                    @onchange="changeSearch('clueStatusDictValue')"
                                ></SelectDict>
                            </el-form-item>
                        </template>
                        <el-form-item prop="customerSourceDictValue">
                            <SelectDict
                                v-model="queryParams.customerSourceDictValue"
                                :placeholder="`${ activeMail == 'allClue' ? '线索' : '客户' }来源`"
                                dictCode="customer_source"
                                @onchange="changeSearch('customerSourceDictValue')"
                            ></SelectDict>
                        </el-form-item>
                        <el-form-item prop="continent">
                            <el-cascader :options="region" v-model="regionValue" clearable @change="getRegion" placeholder="所在区域" />
                        </el-form-item>
                    </template>
                    <el-form-item>
                        <el-button type="primary" @click="handleQuery">查询</el-button>
                        <el-button @click="reset">重置</el-button>
                    </el-form-item>
                </el-form>
                <el-select v-model="selectedEmail" class="email-select" @change="changeUserEmail" style="margin-right: 16px">
                    <template #prefix>
                        <span>{{(emailsData.find(s => s.id === selectedEmail) || {}).mailAccount}}<span style="color: #000;font-weight: bold;">{{ allMailCount ? `（${allMailCount}）` : ''}}</span></span>
                    </template>
                    <el-option v-for="item in emailsData" :label="item.label" :value="item.id">
                        <div>
                            <span>{{ item.mailAccount }}</span>
                            <span v-if="item.unReadCount" style="color: #000;font-weight: bold;">（{{ item.unReadCount }}）</span>
                        </div>
                    </el-option>
                </el-select>
            </div>
            <div class="content flex">
                <div class="table-div">
                    <component
                        :ref="($event: any) => setItemRef($event)"
                        :is="activeComponents"
                        @emailContent="getContent"
                        @refresh="changeSetting"
                        @delChange="delChange"
                        @exportMails="exportMails"
                        @readChange="readChange"
                        v-if="!isFolder"
                    ></component>
                    <!-- 自定义文件夹的内容，区分一下 -->
                    <customFolder
                        ref="customFolderRef"
                        @emailContent="getContent"
                        @refresh="changeSetting"
                        @delChange="delChange"
                        @exportMails="exportMails"
                        v-else
                    />
                </div>
                <div class="resizable-container" v-if="isShowDetail" v-loading="dataLoading">
                    <div class="resizable-handle" @mousedown.stop.prevent="startResize"></div>
                    <div class="resizable-content" :style="{ height: height + 'px' }">
                        <div class="detail flex">
                            <div class="detail-header flex-center">
                                <span v-if="activeMail != 'draft'">发件人：{{ Econtent?.from ? Econtent?.fromName + '<' + Econtent?.from + '>' : '' }}</span>
                                <el-popover
                                    placement="top-start"
                                    popper-class="max-width-popover"
                                >
                                    <template #reference>
                                        <span class="first-popover">收件人：{{ Econtent?.sjr?.join(",") }}</span>
                                    </template>
                                    <template #default>
                                        {{ Econtent?.sjr?.join(",") }}
                                    </template>
                                </el-popover>
                                <el-tooltip
                                    placement="top-start"
                                    popper-class="max-width-popover"
                                    v-if="Econtent?.recipientCc"
                                >
                                    <template #content>
                                        {{ Econtent?.csr?.join(",") }}
                                    </template>
                                    <span>抄送人：{{ Econtent?.csr?.join(",") }}</span>
                                </el-tooltip>
                                <span v-else style="flex: 1">抄送人：</span>
                                <el-icon :size="16" style="cursor: pointer;" @click="isShowDetail = false"><Close /></el-icon>
                            </div>
                            <div class="detail-content">
                                <div style="flex: 1;word-break: break-all;" v-html="Econtent?.content"></div>
                                <div v-if="Econtent?.attachments && Econtent?.attachments.length != 0" class="email_file flex">
                                    <div class="file" v-for="item in Econtent?.attachments" @click="download(item)">
                                        {{ item.fileName }}.{{item.fileExt}}（{{item.fileSizeName }}）
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
    import { getUserEmails, receiveEmails, setDefault, fileDownload, getEmailDetailContent, emilsExport, getEmailFolder, getNoReadCount } from '@/api/emails'
    import Inbox from './components/Inbox.vue'
    import Sent from './components/Sent.vue'
    import Senting from './components/Senting.vue'
    import Starred from './components/Starred.vue'
    import Draft from './components/Draft.vue'
    import Trash from './components/Trash.vue'
    import Annex from './components/Annex.vue'
    import Strange from './components/Strange.vue'
    import Documented from './components/Documented.vue'
    import SystemRemind from './components/SystemRemind.vue'
    import AllCustomer from './components/AllCustomer.vue'
    import AllClue from './components/AllClue.vue'
    import customFolder from './components/customFolder.vue'
    import downloadPlugins from '@/plugins/download'
    import { region } from '@/utils/region';
    import { useDictCache } from '@/hooks/web/useDict'
    import SvgIcon from '@/components/SvgIcon/index.vue'

    const { queryDictDetailByCodes } = useDictCache(['customer_type', 'customer_level', 'customer_source', 'clue_status'])
    queryDictDetailByCodes()

    const receiveLoading = ref(false)
    // 接收邮箱内容
    const receiveEmail = () => {
        receiveLoading.value = true
        receiveEmails().then(res => {
            if(res.success) {
                handleQuery()
            }
        }).finally(() => {
            receiveLoading.value = false
        })
    }

    const regionValue = ref([])
    const getRegion = (value) => {
        queryParams.value.continent = value ? value[0] : ''
        queryParams.value.country = value ? value[1] : ''
        changeSearch('continent')
        changeSearch('country')
    }

    const queryParams = ref({
        blurry: undefined,
        customerName: undefined,
        emailAddress: undefined,
        customerTypeDictValue: undefined,
        customerLevelDictValue: undefined,
        customerSourceDictValue: undefined,
        continent: undefined,
        country: undefined,
        clueStatusDictValue: undefined
    })
    const changeSearch = (type) => {
        dialogRef.value.queryParams[type] = queryParams.value[type]
    }
    const queryFormRef = ref()
    const reset = () => {
        queryFormRef.value?.resetFields()
        queryParams.value.country = undefined
        regionValue.value = []
        dialogRef.value.queryParams = Object.assign(dialogRef.value.queryParams, queryParams.value)
    }

    const dialogRef = ref()
    const setItemRef = (el: any) => {
        if (el) {
            dialogRef.value = el
        }
    }

    const delChange = (id: string | number) => {
        if(id == selectedEmail.value) {
            selectedEmail.value = ''
            handleQuery()
        }
        emailsData.value.splice(emailsData.value.findIndex(e => e.id == id), 1)
    }

    // 切换邮箱
    const changeUserEmail = (val: string) => {
        ElMessageBox.confirm(
            '切换操作会将选定的邮箱设置为默认邮箱，确定切换邮箱吗',
            '确认提示',
            { type: 'warning', confirmButtonText: '提交' }
        ).then(() => {
            copySelectedEmail.value = val
            setDefault(val).then(res => {
                if(res.success) {
                    receiveEmail()
                    handleQuery()
                }
            })
        }).catch(() => {
            selectedEmail.value = copySelectedEmail.value
        })
    }

    const handleQuery = () => {
        if(activeMail.value.indexOf('customFolder') == -1) {
            dialogRef.value.handleQuery()
        }else {
            customFolderRef.value.handleQuery()
        }
        getCountData()
    }

    const folderData = ref([])
    const showFolderList  = ref(false)
    const getFolder = () => {
        getEmailFolder().then(res => {
            if(res.success) {
                folderData.value = res.result.map(item => {
                    item.components = customFolder
                    item.value = 'customFolder' + item.id
                    return item
                })
            }
        })
    }

    const countData = ref<any>({})
    const getCountData = () => {
        getNoReadCount().then(res => {
            if(res.success) {
                countData.value = res.result
            }
        })
    }

    const emailsData = ref([])
    const selectedEmail = ref('')
    const isSetting = ref(false)
    const copySelectedEmail = ref('')
    const allMailCount = ref(0)
    const getUserEmail = () => {
        getUserEmails().then(res => {
            if(res.success) {
                if(res.result.length != 0) {
                    emailsData.value = res.result
                    allMailCount.value = res.result.map(item => item.unReadCount).reduce((a, b) => a + b, 0)
                    selectedEmail.value = res.result.filter(item => item.useDefault == 1)[0].id || ''
                    copySelectedEmail.value = selectedEmail.value
                    // receiveEmail()
                    getFolder()
                    getCountData()
                }else {
                    ElMessage.error('请先配置邮箱')
                    isSetting.value = true
                }
            }
        })
    }

    const emailBtn = ref([
        { label: '收件箱', value: 'inbox', components: Inbox, countType: 'inboxCount' },
        { label: '已发送', value: 'sent', components: Sent, countType: '' },
        { label: '发件箱', value: 'senting', components: Senting, countType: 'sentingCount' },
        { label: '星标邮件', value: 'starred', components: Starred, countType: '' },
        { label: '草稿箱', value: 'draft', components: Draft, countType: '' },
        { label: '垃圾箱', value: 'trash', components: Trash, countType: '' },
        { label: '邮件附件', value: 'annex', components: Annex, countType: '' }
    ])

    const emailStatusBtn = ref([
        { label: '陌生待处理', value: 'strange', components: Strange, countType: 'unknownCount' },
        { label: '有档待处理', value: 'documented', components: Documented, countType: 'knownCount' },
        { label: '系统提醒', value: 'systemRemind', components: SystemRemind, countType: 'systemCount' },
        { label: '所有客户', value: 'allCustomer', components: AllCustomer, countType: 'customerCount' },
        { label: '所有线索', value: 'allClue', components: AllClue, countType: 'clueCount' },
    ])

    const activeMail = ref('inbox')
    const activeComponents = shallowRef(Inbox)
    const isFolder = ref(false)
    const customFolderRef = ref()
    const prevValue = ref('')
    const changeEmail = (item, id?: string) => {
        if(!isSetting.value) {
            activeMail.value = item.value
            if(prevValue.value.indexOf('customFolder') != -1 && activeMail.value.indexOf('customFolder') != -1) {
                customFolderRef.value.queryParams['folderId'] = id
                customFolderRef.value.handleQuery()
            }else {
                if(id) {
                    isFolder.value = true
                }else{
                    isFolder.value = false
                }
                nextTick(() => {
                    if(id) customFolderRef.value.queryParams['folderId'] = id
                    activeComponents.value = item.components
                })
            }
            Econtent.value = null
            isShowDetail.value = false
            reset()
            prevValue.value = item.value
        }else{
            ElMessage.error('请先配置邮箱')
        }
    }

    const router = useRouter()
    const queryData: { type?: string } = router.currentRoute.value.query
    if(queryData.type) {
        activeMail.value = queryData.type
        activeComponents.value = emailBtn.value.find(item => item.value == queryData.type).components
    }

    const changeSetting = () => {
        if(isSetting.value) {
            getUserEmail()
            isSetting.value = false
        }else{
            ElMessage.error('请先配置邮箱')
        }
    }

    const sendEmail = () => {
        if(!isSetting.value) {
            const { href } = router.resolve({
                path: '/email/send'
            })
            window.open(href, '_blank')
        }else{
            ElMessage.error('请先配置邮箱')
        }
    }

    const Econtent = ref()
    const dataLoading = ref(false)
    const isShowDetail = ref(false)
    const getContent = (val) => {
        if(val){
            dataLoading.value = true
            isShowDetail.value = true
            getEmailDetailContent({ mailId: val.id }).then(res => {
                if(res.success) {
                    Econtent.value = res.result
                    let sjr = val.recipient.split(',')
                    Econtent.value.sjr = []
                    Econtent.value.csr = []
                    for(let i = 0;i < sjr.length; i++) {
                        Econtent.value.sjr.push((val.recipientName || val.recipient).split(',')[i] + '<' + sjr[i] +'>')
                    }
                    if(val.recipientCc){
                        let csr = val.recipientCc.split(',')
                        for(let i = 0;i < csr.length; i++) {
                            Econtent.value.csr.push((val.recipientCcName || val.recipientCc).split(',')[i] + '<' + csr[i] +'>')
                        }
                    }
                }
            }).finally(() => {
                dataLoading.value = false
            })
        }
    }

    const download = (item:any) =>{
        fileDownload({ attachmentId: item.id }, activeMail.value).then(res => {
            if(res) {
                downloadPlugins.download('download', res)
            }else {
                ElMessage.error('下载失败，请稍后再试')
            }
        })
    }

    const exportMails = (mailIds: (string | number)[]) => {
        if(mailIds.length == 0) {
            ElMessage.error('请选择要导出的邮件')
            return false
        }
        emilsExport({ mailIds }, 'batch').then(res => {
            try {
                downloadPlugins.download('export', res)
            }catch {
                ElMessage.error('导出失败，请稍后再试')
            }
        })
    }

    const handleVisibilityChange = () => {
        if(document.visibilityState === 'visible'){
            getUserEmail()
        }
    }

    const height = ref(425)
    const startY = ref(0)
    const dragging = ref(false)
    const startResize = (event) =>{
        dragging.value = true;
        startY.value = event.clientY;
        document.addEventListener('mousemove', doResize);
        document.addEventListener('mouseup', stopResize);
    }
    const doResize = (event) =>{
        if (dragging.value) {
            const deltaY = event.clientY - startY.value;
            height.value = Math.max(100, height.value - deltaY); // 最小高度设为100px
            startY.value = event.clientY;
        }
    }
    const stopResize = () =>{
        dragging.value = false;
        document.removeEventListener('mousemove', doResize);
        document.removeEventListener('mouseup', stopResize);
    }

    const backCRM = () => {
        const { href } = router.resolve({
            path: '/index'
        })
        window.open(href, '_blank')
    }

    const readChange = () => {
        const channel = new BroadcastChannel('email_channel');
        channel.postMessage('readChange');
        getUserEmail()
    }

    onMounted(() => {
        getUserEmail()
        // document.addEventListener('visibilitychange', handleVisibilityChange);
    })
</script>

<style scoped lang="scss">
    .top-search{
        justify-content: space-between;
        .el-input, .el-select{
            width: 200px;
        }
    }
    .left svg{
        width: 16px;
        height: 16px;
    }
    .my-folder{
        display: flex;
        width: 100%;
        padding: 4px 0 2px 12px;
        align-items: center;
        color: var(--el-text-color-regular);
        cursor: pointer;
        margin-bottom: 8px;
    }
    .folder-list{
        padding-left: 15px;
        width: 100%;
        .el-button{
            margin-left: 10px;
            :deep(span){
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
                display: inline;
            }
        }
        .el-button + .el-button{
            margin-left: 10px;
        }
    }
    .email-select{
        min-width: 200px;
        width: auto!important;
        :deep(.el-select__prefix){
            color: #606266;
        }
    }
</style>

<style>
    .max-width-popover {
        width: auto !important;
        max-width: 500px;
    }
    .el-select-dropdown__item{
        padding: 0 10px 0 20px;
    }
</style>
