<template>
    <Table
        ref="orderTable"
        :tableParams="tableParams"
        :btnRole="[]"
        :right-btn="[]"
        isEmail
        @selectionChange="handleSelectionChange"
        isCurrentChange
        @currentChange="emailContent"
    >
        <template #left>
            <el-button @click="followStatus(null, 1)">已跟进</el-button>
            <el-button @click="followStatus(null, 0)">未跟进</el-button>
        </template>
    </Table>
</template>

<script setup lang="ts">
    import Table from '@/components/Table/index.vue'
    import { tableTypes } from '@/components/Table/types'
    import { listEmails,markStar,markAllRead,markRead,trashEmails,completelyDelEmails, editFollowStatus } 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', '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{
                                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: 'customerVO.customerForm',
                sortable: false,
                render: ({column}: { column: EmailsVO }) => {
                    let typeName = ''
                    if(column.customerls && column.customerls.length != 0) {
                        if(column.customerls.length > 1) {
                            typeName = '客户/线索'
                        }else {
                            typeName = column.customerls[0].customerForm == 10 ? '客户' : '线索'
                        }
                    }
                    return [
                        h('span', {}, typeName),
                    ]
                }
            },
            {
                show: true,
                label: '主题',
                prop: 'subject',
                sortable: false,
                render: ({column}: { column: EmailsVO }) => {
                    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: {
                                            id: column.id,
                                            customerId: column.customerls[0].id,
                                            resourceType: column.customerls[0].customerForm
                                        }
                                    })
                                    window.open(href, '_blank')
                                }
                            }, column.subject)
                        ])
                    ]
                }
            },
            { show: true, label: '日期', prop: 'recipientDate', sortable: false },
            { show: true, label: '上次跟进日期', prop: 'customerVO.lastFollowUpTime', sortable: false },
            { show: true, label: '归属人', prop: 'customerVO.ownerByName', sortable: false },
            {
                show: true, label: '操作', width: 150, prop: 'operation', disabledMove: true, render: ({ column }: { column: EmailsVO }) => {
                    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')
                            }
                        }, '回复'),
                        h(ElButton, {
                            link: true,
                            type: column.followStatus?'primary':'danger',
                            onClick:async($event)=>{
                                $event.stopPropagation()
                                if(!column.followUpId){
                                    followStatus(column)
                                }
                            }
                        }, column.followStatus?'已跟进':'未跟进')
                    ]
                }
            },
        ],
        queryParams: {
            bindCustomer: 1,
            blurry: '',
            boxCode:'INBOX',
            followUpState: 0
        },
        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 followStatus = (column, followStatus?: number) => {
        if(!column && ids.value.length == 0) {
            ElMessage.error('请选择邮件')
            return false
        }
        let params = {
            followStatus: column ? (column.followStatus == 1 ? 0 : 1) : followStatus,
            idList: column ? [column.customerMailId] : ids.value.map(item => item.customerMailId)
        }
        editFollowStatus(params).then(res => {
            if(res.success) {
                if(column) {
                    column.followStatus = params.followStatus
                }else {
                    ids.value.map(item => {
                        item.followStatus = followStatus
                    })
                }
            }
        })
    }

    const ids = ref([])
    const single:any = ref(0)
    /** 多选框选中数据 */
    const handleSelectionChange = (selection: EmailsVO[]) => {
        ids.value = selection;
        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.map(item => item.id),
                isRead:1
            }
            if(data!=''){
                params.emailIds=id
            }
            markRead(params).then(res => {
                if(res.success) {
                    if(data!='') {
                        data.isRead = 1
                    }else{
                        handleQuery()
                    }
                    emits('readChange')
                }
            })
        }
    }

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

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

