<template>
    <Table
        ref="orderTable"
        :tableParams="tableParams"
        :btnRole="[]"
        :right-btn="[]"
        isEmail
        @selectionChange="handleSelectionChange"
        isCurrentChange
        @currentChange="emailContent"
    >
        <template #left>
            <el-button @click="setAllRead()">全部已读</el-button>
            <el-button @click="setRead('')">设为已读</el-button>
            <el-button @click='CompletelyDel("")'>删除</el-button>
            <el-button @click='CompletelyDel("complete")'>彻底删除</el-button>
            <!-- <el-button>拉黑</el-button> -->
            <el-button @click="exportMail">导出邮件</el-button>
            <el-dropdown style="margin-left: 12px;" @visible-change="visibleChange">
                <el-button>
                    移动到<el-icon class="el-icon--right">
                        <arrow-down v-if="!visible" />
                        <arrow-up v-else />
                    </el-icon>
                </el-button>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item v-for="item in folderData" @click="moveToFolder(item.id)">{{ item.folderName }}</el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
        </template>
    </Table>
</template>

<script setup lang="ts">
    import Table from '@/components/Table/index.vue'
    import { tableTypes } from '@/components/Table/types'
    import { listEmails, markStar, markAllRead, getEmails, markRead, trashEmails, completelyDelEmails, getEmailFolder, moveEmailToFolder } from '@/api/emails';
    import { EmailsVO, EmailsQuery } from '@/api/emails/types';
    import { Star,StarFilled } from "@element-plus/icons-vue"
    import SvgIcon from '@/components/SvgIcon/index.vue'

    const emits = defineEmits(['refresh', 'emailContent', 'delChange', 'exportMails', 'readChange'])
    const emailContent = (val: any) => {
        if(val) {
            emits('emailContent', val)
            if(val.isRead == 0){
                setRead(val)
            }
        }
    }
    const router: any = useRouter();
    const tableParams = reactive<tableTypes<EmailsQuery, EmailsVO>>({
        tableColumn: [
            {
                show: true,
                label: '发件人',
                prop: 'fromName',
                sortable: false,
                render: ({column}: { column: EmailsVO }) => {
                    let name = []
                    let nameItem = []
                    let style = column.isRead == 1 ? '' : 'font-weight: bold;'
                    if(column.customerls && column.customerls.length != 0) {
                        column.customerls.map(item => {
                            if(item.isDelete) {
                                name.push(item.customerName + '（已删除）')
                                nameItem.push({
                                    style,
                                    class: '',
                                })
                            }else if(!item.isMyCustomer) {
                                name.push(item.customerName +
                                    `（${ item.ownerByName ? (item.ownerByName + '的客户') : (item.hasGarbageCustomer ? '无效客户' : '公海客户') }）`
                                )
                                nameItem.push({
                                    style,
                                    class: '',
                                })
                            }else{
                                name.push(item.customerName)
                                nameItem.push({
                                    style,
                                    class: 'link',
                                    onClick: async ($event) => {
                                        $event.stopPropagation()
                                        const { href } = router.resolve({
                                            path: '/customer/followPanel',
                                            query: {
                                                id: item.id,
                                                resourceType: item.customerForm
                                            }
                                        })
                                        window.open(href, '_blank')
                                    }
                                })
                            }
                        })
                    }else {
                        name.push(column.fromName || column.from)
                        nameItem.push({
                            style,
                            class: '',
                        })
                    }
                    let nameHtml = []
                    for(let i = 0;i < name.length; i++) {
                        nameHtml.push(h(
                            'span',
                            nameItem[i],
                            name[i]
                        ))
                    }
                    return [
                        h('div',{style:'display:flex;align-items: center'},[
                            h(ElIcon, [
                                h(column.isStar?StarFilled:Star,{
                                    class:'star_icon',
                                    style:column.isStar?'color:#1874ff;':'',
                                    onClick: async ($event) => {
                                        $event.stopPropagation()
                                        setStar(column)
                                    }
                                })
                            ]),
                            h('div', { class: 'email_title' }, nameHtml)
                        ])
                    ]
                }
            },
            {
                show: true,
                label: '主题',
                prop: 'subject',
                sortable: false,
                render: ({column}: { column: EmailsVO }) => {
                    let query: any = { id: column.id }
                    if(column.customerls && column.customerls.length == 1) {
                        query.customerId = column.customerls[0].id
                        query.resourceType = column.customerls[0].customerForm
                    }
                    let annex = null
                    if(column.attachmentNum) {
                        annex = h(SvgIcon, { 'iconClass': 'email-annex', style: { 'margin-right': '2px', width: '16px', height: '16px' } })
                    }
                    return [
                        h('div', { style: { display: 'flex', 'align-items': 'center' } }, [
                            annex,
                            h('div', {
                                class: 'link',
                                style:column.isRead==1?'':'font-weight: bold;color:#333',
                                onClick: async ($event) => {
                                    $event.stopPropagation()
                                    if(column.isRead == 0){
                                        setRead(column)
                                    }
                                    const { href } = router.resolve({
                                        path: '/customer/followPanel/detail',
                                        query: query
                                    })
                                    window.open(href, '_blank')
                                }
                            }, column.subject)
                        ])
                    ]
                }
            },
            { show: true, label: '日期', prop: 'sentDate', sortable: false },
            { show: true, label: '大小', prop: 'emailSizeName', sortable: false, width: 120 },
            {
                show: true, label: '操作', width: 280, prop: 'operation', disabledMove: true, render: ({ column }: { column: EmailsVO }) => {
                    let recordFlag = false
                    let isDisabled = false
                    if(column.customerls && column.customerls.length != 0) {
                        if(column.customerls[0].isDelete) {
                            recordFlag = true
                        }
                    }else {
                        recordFlag = true
                    }
                    if(column.customerls && column.customerls.length > 1) {
                        isDisabled = true
                    }
                    return [
                        h(ElButton, {
                            link: true,
                            type: 'primary',
                            onClick:async($event)=>{
                                $event.stopPropagation()
                                const { href } = router.resolve({
                                    path: '/email/send',
                                    query: {
                                        id: column.id,
                                        type: 'reply'
                                    }
                                })
                                window.open(href, '_blank')
                            }
                        }, '回复'),
                        recordFlag ? [
                            h(ElButton, {
                                link: true,
                                type: !isDisabled?'primary':'info',
                                disabled: isDisabled,
                                onClick:async($event)=>{
                                    $event.stopPropagation()
                                    const { href } = router.resolve({
                                        path: '/customer/liaison/add',
                                        query: {
                                            type:'add',
                                            email: column.from
                                        }
                                    })
                                    window.open(href, '_blank')
                                }
                            }, '建联系人'),
                            h(ElButton, {
                                link: true,
                                type: !isDisabled?'primary':'info',
                                disabled: isDisabled,
                                onClick:async($event)=>{
                                    $event.stopPropagation()
                                    const { href } = router.resolve({
                                        path: '/clue/add',
                                        query: {
                                            type:'add',
                                            email: column.from
                                        }
                                    })
                                    window.open(href, '_blank')
                                }
                            }, '建线索'),
                            h(ElButton, {
                                link: true,
                                type: !isDisabled?'primary':'info',
                                disabled: isDisabled,
                                onClick:async($event)=>{
                                    $event.stopPropagation()
                                    const { href } = router.resolve({
                                        path: '/customer/addCustomer',
                                        query: {
                                            type:'add',
                                            email: column.from
                                        }
                                    })
                                    window.open(href, '_blank')
                                }
                            }, '建客户')
                        ] : h(ElButton, {
                            link: true,
                            type: 'info',
                            disabled: true,
                        }, '已建档')
                    ]
                }
            },
        ],
        queryParams: {
            boxCode:'INBOX',
            blurry: ''
        },
        listFn: listEmails
    })

    const { queryParams } = toRefs(tableParams)

    const setStar = (item:any) => {
        let params = {
            isStar:item.isStar?0:1,
            emailId:item.id,
        }
        markStar(params).then(res => {
            if(res.success) {
                handleQuery()
            }
        })
    }

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

    const setRead = (data:any) =>{
        let id = data.id
        if(single.value == 0 && data==''){
            ElMessage.error('请选择邮件')
        }else{
            let params = {
                emailIds:ids.value,
                isRead:1
            }
            if(data!=''){
                params.emailIds=id
            }
            markRead(params).then(res => {
                if(res.success) {
                    if(data!='') {
                        data.isRead = 1
                    }else{
                        handleQuery()
                    }
                    emits('readChange')
                }
            })
        }
    }

    const setAllRead = () =>{
        markAllRead().then(res => {
            if(res.success) {
                handleQuery()
                emits('readChange')
            }
        })
    }

    const CompletelyDel = (val:string) =>{
        if(single.value == 0){
            ElMessage.error('请选择需要删除的邮件')
        }else{
            let params = {
                emailIds:ids.value,
            }
            let tips = val==''?'':'彻底'
            ElMessageBox.confirm(
                '是否确认'+tips+'删除当前邮件？',
                '确认提示',
                { type: 'warning', confirmButtonText: '提交' }
            ).then(() => {
                if(val==''){
                    let params = {
                        emailIds:ids.value,
                        isTrash:1,
                    }
                    trashEmails(params).then(res => {
                        if(res.success) {
                            ElMessage.success('邮件已移至垃圾箱')
                            handleQuery()
                            emits('readChange')
                        }
                    })
                }else{
                    completelyDelEmails(ids.value).then(res => {
                        if(res.success) {
                            ElMessage.success('邮件已删除成功')
                            handleQuery()
                            emits('readChange')
                        }
                    })
                }

            }).catch(() => {})
        }
    }

    const exportMail = () => {
        emits('exportMails', ids.value)
    }

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

    const folderData = ref([])
    const moveToFolder = (id: string | number) => {
        if(ids.value.length == 0) {
            ElMessage.error('请选择邮件')
            return
        }
        let params = {
            mailIds: ids.value,
            folderId: id
        }
        moveEmailToFolder(params).then(res => {
            if(res.success) {
                ElMessage.success('移动成功')
                handleQuery()
                emits('readChange')
            }
        })
    }

    const visible = ref(false)
    const visibleChange = (val: boolean) => {
        visible.value = val
    }

    onMounted(() => {
        getEmailFolder().then(res => {
            folderData.value = res.result
        })
    })

    defineExpose({
        handleQuery,
        queryParams
    })
</script>

