<template>
    <div class="nav_detail">
        <Table
            ref="emailTable"
            :tableParams="tableParams"
            :btnRole="btnRole"
            :right-btn="[]"
            :is-checkbox="false"
            @selectionChange="handleSelectionChange"
        >
            <template #left-search>
                <el-form :model="queryParams" ref="queryFormRef" :inline="true" class="nav_detail_search">
                    <el-form-item prop="beginTime">
                        <el-date-picker
                            v-model="rangeTime"
                            type="datetimerange"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            start-placeholder="时间范围"
                            end-placeholder="时间范围"
                            @change="changeTime"
                        />
                    </el-form-item>
                    <el-form-item prop="blurry">
                        <el-input
                            v-model="queryParams.blurry"
                            placeholder="内容关键词"
                            clearable
                            @keyup.enter="handleQuery"
                            prefix-icon="Search"
                        />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleQuery">查询</el-button>
                    </el-form-item>
                </el-form>
            </template>
            <!-- <template #left>
                <el-button @click="batchDel()" v-hasPermi="[`${perPrefix}:detail:tab_yjjl_sc`]" type="danger">删除</el-button>
            </template> -->
        </Table>
    </div>

    <el-dialog title="邮件详情" v-model="visible" width="850px" append-to-body>
        <p class="title">{{ emailData?.subject }}</p>
        <div class="flex-center header">
            <p>发送人员：{{ emailData?.fromName }}</p>
            <p>发送时间：{{ emailData?.createTime }}</p>
            <p style="flex: 1;" :title="emailData?.recipientName">接收对象：{{ emailData?.recipientName }}</p>
            <p class="flex-center">
                <span style="margin-right: 5px;">浏览次数：{{ recordCount }}</span>
                <el-button link type="primary" @click="recordVisible = true">查看浏览记录</el-button>
            </p>
        </div>
        <div class="email-content" v-html="emailData?.content"></div>
        <p style="margin-bottom: 15px;" class="title">附件</p>
        <div v-if="emailData?.attachments" class="email_file flex">
            <div class="file" v-for="item in emailData.attachments" @click="download(item)">
                {{ item.fileName }}.{{item.fileExt}}({{item.fileSize }}kb)
            </div>
        </div>
    </el-dialog>

    <el-dialog title="浏览记录" destroy-on-close v-model="recordVisible" width="850px" append-to-body>
        <Table
            ref="recordTable"
            :tableParams="recordTableParams"
            :btnRole="[]"
            :right-btn="[]"
            :is-checkbox="false"
        >
        </Table>
    </el-dialog>
</template>

<script setup lang="ts">
    import { getMailList, fileDownload, delEmails, trashEmails, setClickRecord, getRecord, getEmailDetailContent } from '@/api/emails';
import { ElButton, ElMessage, ElMessageBox } from 'element-plus';
import { EmailsVO } from '@/api/emails/types';
    import Table from '@/components/Table/index.vue'
    import { tableTypes } from '@/components/Table/types'
    import downloadPlugins from '@/plugins/download'
    import { useDictCache } from '@/hooks/web/useDict'
    import auth from "@/plugins/auth";
import { any } from 'vue-types';

    const { queryDictDetailByCodes } = useDictCache(['task_status_type'])
    queryDictDetailByCodes()

    const props = defineProps({
        perPrefix: {
            type: String,
        },
        customerId: {
            type: String,
        },
        liaisonId: {
            type: String,
        },
        resourceType: {
            type: String,
        }
    })

    const btnRole = ref([
        // { type: 'remove', hasPermi: `${ props.perPrefix }:detail:tab_yjjl_sc` },
    ])

    interface emailListQuery {
        customerId?: string;
        liaisonId?: string;
        blurry?: string;
        beginTime?: string;
        endTime?: string;
    }
    const router = useRouter();
    const tableParams = reactive<tableTypes<emailListQuery, EmailsVO>>({
        tableColumn: [
            { show: true, label: '发件人', prop: 'fromName' },
            { show: true, label: '接收时间', prop: 'recipientDate' },
            { show: true, label: '接收对象', prop: 'recipientName', showOverflowTooltip: true },
            { show: true, label: '接收邮箱', prop: 'recipient', showOverflowTooltip: true },
            { show: true, label: '邮件主题', width: 450, prop: 'subject', render: ({ column }: { column: EmailsVO }) => {
                return [
                    h('div', {
                        class: 'link',
                        onClick: async () => {
                            const { href } = router.resolve({
                                path: '/customer/followPanel/detail',
                                query: {
                                    id: column.mailId,
                                    customerId:props.customerId,
                                    resourceType:props.customerId,
                                }
                            })
                            window.open(href, '_blank')
                        }
                    }, column.subject),
                ]
            }},
            {
                show: true, label: '操作', width: 150, prop: 'operation', disabledMove: true, render: ({ column }: { column: EmailsVO }) => {
                    return [
                        h(ElButton, {
                            link: true, type: column.inOutMark == 1 ? 'primary' : 'success', onClick: ($event) => {
                                let query = {}
                                if(column.inOutMark==1){ //进
                                    query = {
                                        id: column.mailId,
                                        type: 'reply'
                                    }
                                }else{ // 出
                                    query = {
                                        id: column.mailId,
                                        type: 'edit'
                                    }
                                }
                                const { href } = router.resolve({
                                    path: '/email/send',
                                    query: query
                                })
                                window.open(href, '_blank')
                            }
                        }, () => column.inOutMark == 1 ? '回复' : '重发'),
                    ]
                }
            },
        ],
        queryParams: {
            customerId: props.customerId,
            liaisonId: props.liaisonId
        },
        listFn: getMailList,
        delFn: delEmails,
        keyId: 'id'
    })

    const { queryParams } = toRefs(tableParams);

    const rangeTime = ref()
    const changeTime = (value: string[] | null) => {
        queryParams.value.beginTime = value ? value[0] : null
        queryParams.value.endTime = value ? value[1] : null
    }

    const emailTable = ref()
    /** 搜索按钮操作 */
    const handleQuery = () => {
        emailTable.value.getData()
    }

    const visible = ref(false)
    const emailData = ref<EmailsVO>()
    const recordCount = ref(0)
    const recordTableParams = ref()
    const getDetail = (data: EmailsVO) => {
        getEmailDetailContent({ mailId: data.mailId }).then(res => {
            if(res.success) {
                emailData.value = res.result
            }
        })
        setClickRecord(data.mailId).then(res => {
            recordCount.value = res.result
        })
        recordTableParams.value = {
            tableColumn: [
                { show: true, label: '部门', prop: 'deptName' },
                { show: true, label: '人员', prop: 'ownerByName' },
                { show: true, label: '浏览时间', prop: 'createTime' },
            ],
            queryParams: {
                customerMailId: data.mailId,
            },
            listFn: getRecord,
        }
        visible.value = true
    }

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

    const ids = ref([])
    /** 多选框选中数据 */
    const handleSelectionChange = (selection: EmailsVO[]) => {
        ids.value = selection.map(item => item.id);
    }

    const batchDel = () => {
        if(ids.value.length == 0) {
            ElMessage.error('请选择需要删除的邮件')
            return false
        }
        ElMessageBox.confirm(
            '是否确认删除当前邮件？',
            '确认提示',
            { type: 'warning', confirmButtonText: '提交' }
        ).then(() => {
            let params = {
                emailIds: ids.value,
                isTrash: 1,
            }
            trashEmails(params).then(res => {
                if(res.success) {
                    ElMessage.success('邮件已移至垃圾箱')
                    handleQuery()
                }
            })
        }).catch(() => {})
    }

    const recordVisible = ref(false)
</script>

<style scoped lang="scss">
    .title{
        border-left: 3px solid var(--el-color-primary);
        font-size: 16px;
        padding-left: 10px;
    }
    .header{
        margin: 15px 0;
        padding: 10px;
        border: 1px solid #ebeef5;
        background: #f8f8f9;
        column-gap: 20px;
        .el-button{
            padding: 0;
        }
        p{
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
        }
    }
    .email_file{
        margin-top: 15px;
        .file{
            border-radius: 2px;
            border: 1px solid #1874FF;
            padding: 4px 17px;
            color: #1874FF;
            margin: 0 15px 10px 0;
            cursor: pointer;
        }
    }
    .email-content{
        :deep(p){
            line-height: 32px;
        }
        :deep(ul){
            padding-inline-start: 20px;
            margin-block-end: 0;
            margin-block-start: 0;
            li{
                list-style: disc !important;
            }

        }
        :deep(ol){
            padding-inline-start: 20px;
            margin-block-end: 0;
            margin-block-start: 0;
            li{
                list-style: decimal !important;
            }

        }
        :deep(ol, li){
            padding-inline-start: 20px;
            margin-block-end: 0;
            margin-block-start: 0;
        }
        :deep(ul, li){
            padding-inline-start: 20px;
            margin-block-end: 0;
            margin-block-start: 0;
        }
        :deep(a){
            text-decoration: underline;
            color: #1874FF;
        }
        :deep(img){
            max-width: 100%;
        }
    }
</style>
