<template>
    <div class="detail_area panel_area" v-loading="loadingDetail">
        <div class="panel_left">
            <div class="message">
                <div class='title'>基础信息</div>
                <div v-if="(queryData.resourceType?queryData.resourceType:showDetailData.customerForm)==10">
                    <div class='item'><span class="label">客户代码：</span><span class="value">{{showDetailData?.dataCode}}</span></div>
                    <div class='item'><span class="label">客户名称：</span><span class="value">{{showDetailData?.customerName}}</span></div>
                    <div class='item'><span class="label">区域名称：</span><span class="value">{{showDetailData?.continent}}<span v-if='customerDetail?.country'>/{{showDetailData?.country}}</span></span></div>
                    <div class='item'><span class="label">客户类型：</span><span class="value">{{showDetailData?.customerStatusName}}</span></div>
                    <div class='item'><span class="label">客户等级：</span><span class="value">{{showDetailData?.customerLevelName}}</span></div>
                    <div class='item'><span class="label">客户来源：</span><span class="value">{{showDetailData?.customerSourceName}}</span></div>
                    <div class='item'><span class="label">客户状态：</span><span class="value">{{showDetailData?.customerStatusName}}</span></div>
                    <div class='item'><span class="label">企业网址：</span><a class="value blue" :href="'//'+showDetailData?.customerCompany?.website" target='_blank'>{{showDetailData?.customerCompany?.website||'--'}}</a></div>
                    <div class='item'><span class="label">备用网址：</span>
                        <span class="value">
                            <a class="blue" :href="'//'+showDetailData?.customerCompany?.website1" target='_blank'>{{showDetailData?.customerCompany?.website1||'--'}}</a>
                            <sapn v-if="customerDetail?.customerCompany?.website2">, <a class="blue" :href="'//'+showDetailData?.customerCompany?.website2" target='_blank'>{{showDetailData?.customerCompany?.website2}}</a></sapn>
                            <sapn v-if="customerDetail?.customerCompany?.website3">, <a class="blue" :href="'//'+showDetailData?.customerCompany?.website3" target='_blank'>{{showDetailData?.customerCompany?.website3}}</a></sapn>
                        </span>
                    </div>
                    <div class='item'><span class="label">联系电话：</span><span class="value">{{showDetailData?.customerCompany?.telephone||'--'}}</span></div>
                    <div class='item'><span class="label">意向产品：</span><span class="value">{{showDetailData?.intendedProductsNames}}</span></div>
                    <div class='item'><span class="label">企业邮箱：</span><span class="value">{{showDetailData?.customerCompany?.email||'--'}}</span></div>
                    <div class='item'><span class="label">备用邮箱：</span>
                        <span class="value">{{ customerDetail?.customerCompany?.email1||'--' }}<sapn v-if="customerDetail?.customerCompany.email2">, {{ customerDetail?.customerCompany.email2 }}</sapn><sapn v-if="customerDetail?.customerCompany.email3">, {{ customerDetail?.customerCompany.email3 }}</sapn></span>
                    </div>
                    <div class='item'><span class="label">通讯地址：</span><span class="value">{{showDetailData?.customerCompany?.communicationAddress||'--'}}</span></div>
                    <div class='item'><span class="label">客户归属：</span><span class="value">{{showDetailData?.ownerByName}}</span></div>
                    <div class='item' v-if="!customerDetail?.hasPublicCustomer"><span class="label">保护到期：</span><span class="value">{{showDetailData?.protectionDate}}</span></div>
                    <div class='item'><span class="label">下次跟进：</span><span class="value">{{showDetailData?.nextFollowUpTime}}</span></div>
                </div>
                <div v-if="(queryData.resourceType?queryData.resourceType:showDetailData.customerForm)==11">
                    <div class='item'><span class="label">线索名称：</span><span class="value">{{showDetailData?.customerName}}</span></div>
                    <div class='item'><span class="label">区域名称：</span><span class="value">{{showDetailData?.continent}}<span v-if='customerDetail?.country'>/{{showDetailData?.country}}</span></span></div>
                    <div class='item'><span class="label">线索来源：</span><span class="value">{{showDetailData?.customerSourceName}}</span></div>
                    <div class='item'><span class="label">线索状态：</span><span class="value">{{showDetailData?.customerStatusName}}</span></div>
                    <div class='item'><span class="label">企业网址：</span><a class="value blue" :href="'//'+showDetailData?.customerCompany?.website" target='_blank'>{{showDetailData?.customerCompany?.website||'--'}}</a></div>
                    <div class='item'><span class="label">备用网址：</span>
                        <span class="value">
                            <a class="blue" :href="'//'+showDetailData?.customerCompany?.website1" target='_blank'>{{showDetailData?.customerCompany?.website1||'--'}}</a>
                            <sapn v-if="customerDetail?.customerCompany?.website2">, <a class="blue" :href="'//'+showDetailData?.customerCompany?.website2" target='_blank'>{{showDetailData?.customerCompany?.website2}}</a></sapn>
                            <sapn v-if="customerDetail?.customerCompany?.website3">, <a class="blue" :href="'//'+showDetailData?.customerCompany?.website3" target='_blank'>{{showDetailData?.customerCompany?.website3}}</a></sapn>
                        </span>
                    </div>
                    <div class='item'><span class="label">联系电话：</span><span class="value">{{showDetailData?.customerCompany?.telephone||'--'}}</span></div>
                    <div class='item'><span class="label">企业邮箱：</span><span class="value">{{showDetailData?.customerCompany?.email||'--'}}</span></div>
                    <div class='item'><span class="label">备用邮箱：</span>
                        <span class="value">{{ customerDetail?.customerCompany?.email1||'--' }}<sapn v-if="customerDetail?.customerCompany?.email2">, {{ customerDetail?.customerCompany?.email2 }}</sapn><sapn v-if="customerDetail?.customerCompany?.email3">, {{ customerDetail?.customerCompany?.email3 }}</sapn></span>
                    </div>
                    <div class='item'><span class="label">线索归属：</span><span class="value">{{showDetailData?.ownerByName}}</span></div>
                    <div class='item'><span class="label">保护到期：</span><span class="value">{{showDetailData?.protectionDate}}</span></div>
                    <div class='item'><span class="label">下次跟进：</span><span class="value">{{showDetailData?.nextFollowUpTime}}</span></div>
                </div>
            </div>
            <div class='message liaison'>
                <div class='title'>联系人</div>
                <div style='flex:1;overflow-y:auto;'>
                    <template v-for="item in liaisonData">
                        <div class="liaison_item" v-if="item.email">
                            <div class='flex-between'><span @click="searchLiaison(item)">{{item.name}}</span><span @click='editLiaison(item.id)'>编辑</span></div>
                            <div><span @click="emailLiaison(item.email)">{{ item.email }}</span></div>
                        </div>
                        <div class="liaison_item" v-if="item.email1">
                            <div class='flex-between'><span @click="searchLiaison(item)">{{item.name}}</span><span @click='editLiaison(item.id)'>编辑</span></div>
                            <div><span @click="emailLiaison(item.email1)">{{ item.email1 }}（备用1）</span></div>
                        </div>
                        <div class="liaison_item" v-if="item.email2">
                            <div class='flex-between'><span @click="searchLiaison(item)">{{item.name}}</span><span @click='editLiaison(item.id)'>编辑</span></div>
                            <div><span @click="emailLiaison(item.email2)">{{ item.email2 }}（备用2）</span></div>
                        </div>
                        <div class="liaison_item" v-if="item.email3">
                            <div class='flex-between'><span @click="searchLiaison(item)">{{item.name}}</span><span @click='editLiaison(item.id)'>编辑</span></div>
                            <div><span @click="emailLiaison(item.email3)">{{ item.email3 }}（备用3）</span></div>
                        </div>
                    </template>
                    
                </div>
            </div>
        </div>
        <div class="panpel_right">
            <div class="card-header flex-between">
                <span>快捷看板</span>
                <div class="header_right flex" v-if="queryData.preNextScopeMenuId">
                    <div class="left" :class="customerDetail?.previousId?'':'btn-grey'">
                        <el-icon @click="changePage(customerDetail?.previousId)"><ArrowLeft /></el-icon>
                    </div>
                    <div class="right" :class="customerDetail?.nextId?'':'btn-grey'">
                        <el-icon @click="changePage(customerDetail?.nextId)"><ArrowRight /></el-icon>
                    </div>
                </div>
            </div>
            <div class='table_form'>
                <el-form class='' :model="queryParams" ref="queryFormRef" :inline="true">
                    <el-row :gutter="16">
                        <el-col :span="4">
                            <el-form-item prop="blurry">
                                <el-input
                                    v-model="queryParams.blurry"
                                    placeholder="内容关键词"
                                    clearable
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item prop="objectiveValue">
                                <SelectDict v-model="queryParams.objectiveValue" placeholder="选择跟进目的"
                                            dictCode="objective_value"></SelectDict>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item>
                                <el-date-picker
                                    v-model="daterange"
                                    type="datetimerange"
                                    range-separator="-"
                                    start-placeholder="时间范围"
                                    end-placeholder="时间范围"
                                    value-format="YYYY-MM-DD HH:mm:ss"
                                    @change="getDate"
                                    />
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item prop="resourceType">
                                <!-- <SelectDict v-model="queryParams.resourceType" placeholder="选择关联业务类型"
                                            dictCode="query_work_data_group"></SelectDict> -->
                                <el-select placeholder="选择关联业务类型" v-model="queryParams.resourceType">
                                    <el-option v-for="item in dictData.businessData" :label="item.label" :value="item.value"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4" v-if='showAll'>
                            <el-form-item prop="followUpTypeValue">
                                <SelectDict v-model="queryParams.followUpTypeValue" placeholder="选择跟进方式" dictCode="follow_up_type"></SelectDict>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6" v-if='!showAll'>
                            <el-form-item>
                                <el-button type="primary" @click="handleQuery">查询</el-button>
                                <el-button @click="resetQuery">重置</el-button>
                                <el-button type="primary" icon="ArrowDown" text @click="showAll=true">展开检索</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="16" v-if='showAll'>
                        <el-col :span="4">
                            <el-form-item prop="inOutMark">
                                <SelectDict v-model="queryParams.inOutMark" placeholder="选择跟进方向"
                                            dictCode="in_out_mark"></SelectDict>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item prop="liaisonIdList">
                                <el-select-v2
                                    v-model="queryParams.liaisonIdList"
                                    :options="liaisonOption"
                                    placeholder="请选择客户联系人"
                                    filterable
                                    multiple
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item prop="followStatus">
                                <el-select v-model="queryParams.followStatus" placeholder="选择跟进状态">
                                    <el-option :value="0" label="未跟进"></el-option>
                                    <el-option :value="1" label="已跟进" ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item prop="createdByList">
                                <SelectUser multiple v-model="queryParams.createdByList" placeholder="选择跟进人" :inputWidth='200'></SelectUser>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item>
                                <el-button type="primary" @click="handleQuery">查询</el-button>
                                <el-button @click="resetQuery">重置</el-button>
                                <el-button type="primary" icon="ArrowUp" text @click="showAll=false">收起检索</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <div>
                    <el-button color="#1874FF" @click='followStatus(1,[])'>标记为已跟进</el-button>
                    <el-button color="#EF352B" @click='followStatus(0,[])'>标记为未跟进</el-button>
                    <el-button color="#1874FF" @click="openFollow('add',{})">写跟进</el-button>
                </div>
                <div style='flex:1;height: 0;'>
                    <Table ref="CustomerTable"
                        :tableParams="tableParams"
                        :rightBtn=[]
                        @selectionChange="handleSelectionChange"
                        @currentChange="handleCurrentChange"
                        isCurrentChange
                    >
                    </Table>
                </div>
            </div>
            <div class="resizable-container" v-loading='emailLoading' v-if='showEmail'>
                <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"
                                    effect="light"
                                    v-if="Econtent?.recipientCc"
                                    popper-class="max-width-popover"
                                >
                                    <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="showEmail = false"><Close /></el-icon>
                            </div>
                            <div class="detail-content">
                                <div style='flex:1;word-break: break-all;padding-right: 16px' 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>
        <Teleport to="body">
            <div
                class="drag_box"
                draggable="true"
                @dragstart="dragstart($event)"
                @dragend="dragend($event)"
                :style="`position: absolute;right:${elRight}px;bottom:${elBottom}px;z-index: 9999`"
            >
                <div class='follow_style' @click="changeStyle()">
                    <img src="@/assets/images/dafult_style.png"/>
                    <p>常规模式</p>
                </div>
            </div>
        </Teleport>
        <AddFollow ref="addFollow"></AddFollow>
        <!-- 跟进详情 -->
        <FollowDetail ref="detail"></FollowDetail>
</template>


<script setup lang="ts">
import { getCustomer,getNexCustomer } from '@/api/customer';
import { formateNullFieldData} from '@/api/customer';
import { listLiaison } from '@/api/customer/liaison';
import {FollowEmailQuery} from "@/api/customer/follow/types";
import {emailFollow} from '@/api/customer/follow';
import {EmailsVO} from '@/api/emails/types';
import {tableTypes} from '@/components/Table/types'
import { fileDownload,getEmailDetailContent,editFollowStatus } from '@/api/emails'
import downloadPlugins from '@/plugins/download'
import auth from '@/plugins/auth'
import AddFollow from '@/components/Follow/add.vue'
import { useDictCache } from '@/hooks/web/useDict'
import FollowDetail from '@/components/Follow/detail.vue'
import SvgIcon from '@/components/SvgIcon/index.vue'
import { noticeEventStore } from '@/store/modules/noticeEvent'
import useAppStore from '@/store/modules/app';
import { listDetialByCodes } from "@/api/system/dict/";
import useSettingsStore from '@/store/modules/settings';
const useSetStore = useSettingsStore();
const appStore = useAppStore();
const toggleSideBar = () => {
    appStore.closeSideBar(false);
}
toggleSideBar()
const userNoticeEventStore = noticeEventStore()
const { queryDictDetailByCodes } = useDictCache(['query_work_data_group', 'objective_value','in_out_mark'])
    queryDictDetailByCodes()

    const dictData: any = reactive({
        businessData: []
    })
    listDetialByCodes(['query_work_data_group']).then((res => {
        if(res.success) {
            dictData.businessData = res.result['query_work_data_group'].filter(item => item.label != '业绩目标')
        }
    }))

    const showAll = ref(false)
    const emit = defineEmits(['handleEdit'])
    const customerDetail = ref<any>()

    const loadingDetail = ref(false)
    const Econtent = ref()

    const ids = ref();
    const single = ref(true);
    const multiple = ref(true);

    const isDrag = ref(false)
    const startclientX = ref(0)
    const startclientY = ref(0)
    const elRight = ref(30)
    const elBottom = ref(100)
    // 拖拽开始事件
    const dragstart=(e)=>  {
        isDrag.value = true
        startclientX.value = e.clientX; // 记录拖拽元素初始位置
        startclientY.value = e.clientY;
    }
    // 拖拽完成事件
    const dragend=(e)=> {
        isDrag.value = false
        let x = e.clientX - startclientX.value; // 计算偏移量
        let y = e.clientY - startclientY.value;
        elRight.value -= x; // 实现拖拽元素随偏移量移动
        elRight.value = elRight.value < 0 ? 0 : elRight.value
        elRight.value = ((elRight.value + 72) > window.innerWidth) ? (window.innerWidth - 72) : elRight.value
        elBottom.value -= y;
        elBottom.value = elBottom.value < 0 ? 0 : elBottom.value
        elBottom.value = ((elBottom.value + 72) > window.innerHeight) ? (window.innerHeight - 72) : elBottom.value
    }

    const router: any = useRouter();
    let queryData = router.currentRoute.value.query
    // 获取客户详情
    const showDetailData = ref<any>()
    const getDetail = (id:string)=>{
        loadingDetail.value = true
        if(queryData.preNextScopeMenuId){ // 列表进
            queryData.hasOrderForm = queryData.hasOrderForm=='false'?false:queryData.hasOrderForm=='true'?true:queryData.hasOrderForm
            queryData.hasFollowMode = queryData.hasFollowMode=='false'?false:queryData.hasFollowMode=='true'?true:queryData.hasFollowMode
            queryData.hasPublicCustomer = queryData.hasPublicCustomer=='0'?false:queryData.hasPublicCustomer=='1'?true:queryData.hasPublicCustomer
            queryData.ownerByIds = (!queryData.ownerByIds||queryData.ownerByIds=='')?[]:queryData.ownerByIds.split(',')
            console.log(queryData)
            getNexCustomer(queryData).then((res) => {
                detailRes(res)
            })
        }else{
            let scopeMenuId = queryData.scopeMenuId=='undefined'||!queryData.scopeMenuId?'':queryData.scopeMenuId
            getCustomer(id,scopeMenuId).then((res) => {
                detailRes(res)
            })
        }

    }
    const detailRes = (res)=>{
        if(res.success) {
            showDetailData.value = formateNullFieldData(JSON.parse(JSON.stringify(res.result)))
            customerDetail.value = res.result
            useSetStore.setTitle(res.result.customerName)
        }
        loadingDetail.value = false
    }
    // 详情切换
    const changePage = (id?:string)=>{
        if(id){
            if(queryData.preNextScopeMenuId){
                router.replace('./followPanel?id=' + id +'&preNextScopeMenuId='+queryData.preNextScopeMenuId+'&scopeMenuId='+queryData.scopeMenuId+'&resourceType=10&blurry='+queryData.blurry+'&customerForm=10&customerStatusDictValue='+queryData.customerStatusDictValue+'&customerTypeDictValue='+queryData.customerTypeDictValue+'&customerLevelDictValue='+queryData.customerLevelDictValue+'&lastFollowUpTime='+queryData.lastFollowUpTime+'&queryRangeType='+queryData.queryRangeType+'&hasOrderForm='+queryData.hasOrderForm+'&hasPublicCustomer='+queryData.hasPublicCustomer+'&ownerByIds='+queryData.ownerByIds+'&hasFollowMode='+queryData.hasFollowMode+'&customerName='+queryData.customerName+'&liaisonName='+queryData.liaisonName+'&country='+queryData.country)
            }else{
                router.replace('./followPanel?id=' + id +"&resourceType="+queryData.resourceType)
            }
        }
    }
    const route = useRoute();
    watch(route, (newRoute, oldRoute) => {
        let queryDataNew: any = router.currentRoute.value.query
        if (queryDataNew.id) {
            queryData = router.currentRoute.value.query
            queryParams.value.customerId = queryDataNew.id
            init()
        }
    });
    const init = async ()=>{
        getDetail(queryData.id)
        getLiaison(queryData.id)
        handleQuery()
        toggleSideBar()
    }

    // 写跟进
    const addFollow = ref()
    const openFollow = (type,item)=>{
        let propData = {}
        if(type=='add'){
            propData = {
                type,
                resourceType:queryData.resourceType,
                customerId:customerDetail.value.id,
                resourceTypeId:customerDetail.value.id,
                resourceName:customerDetail.value.customerName,
                resourceStageName:customerDetail.value.customerStatusName,
                resourceStageDictValue:queryData.resourceType=='10'?customerDetail.value.customerStatusDictValue:customerDetail.value.clueStatusDictValue,
                changeType:queryData.resourceType=='10'?true:false,
            }
        }else{
            propData = {
                type,
                id:item.id,
                customerId: item.customerId
            }
        }
        addFollow.value.open(propData)
    }

    watch(() => userNoticeEventStore.noticeFllow, (newValue, oldValue) => {
        handleQuery()
    });

    const liaisonData = ref()
    const liaisonOption = ref([])
    const getLiaison = (customerId: string | number) => {
        listLiaison({ pageIndex: 1, pageSize: 999999, customerId,}).then(res => {
            if(res.success) {
                liaisonData.value = res.result.records
                liaisonOption.value = res.result.records.map((item: { name: string, id: number }) => {
                    let obj = { label: item.name, value: item.id }
                    return obj
                })
            }
        })
    }

    const daterange = ref('')
    const getDate = (val: string[] | null) => {
        tableParams.queryParams.followUpBeginTime = val ? val[0] : ''
        tableParams.queryParams.followUpEndTime = val ? val[1] : ''
    }

    const perPrefix = ref<string>('customerFormAll')
    perPrefix.value = queryData.perPrefix

    const tableParams = reactive<tableTypes<FollowEmailQuery, EmailsVO>>({
        cloumnCode:queryData.perPrefix,
        tableColumn: [
            {show: true, label: '联系人', width:145,prop: 'liaisonNames', sortable: false,
                // render: ({column}: { column: EmailsVO }) => {
                //     return [
                //         h('div', {},column.liaisonNames.join(','))
                //     ]
                // }
            },
            {
                show: true,
                label: '跟进主题',
                prop: 'subject',
                sortable: false,
                render: ({column}: { column: EmailsVO }) => {
                    let annex = null
                    if(column.attachmentNum && column.attachmentNum > 0) {
                        annex = h(SvgIcon, { 'iconClass': 'email-annex', style: { 'margin-right': '2px', width: '16px', height: '16px', flexShrink:'0' } })
                    }
                    return [
                        h('div', { style: { display: 'flex', 'align-items': 'center' } }, [
                            annex,
                            h(ElButton, {
                                link: true, type: 'primary', onClick: ($event) => {
                                    $event.stopPropagation()
                                    if(column.type=='90'){ // 跟进
                                        openFollow('edit',column)
                                    }else{ // 邮件
                                        let { href } = router.resolve({
                                            path: '/customer/followPanel/detail',
                                            query:{
                                                id:column.mailId,
                                                resourceType:queryData.resourceType,
                                                customerId:customerDetail.value.id      
                                            }
                                        })
                                        window.open(href, '_blank')
                                    }
                                }
                            }, column.subject),
                        ])
                    ]
                }
            },
            {show: true, label: '跟进情况', prop: 'content', sortable: false,
                render: ({column}: { column: EmailsVO }) => {
                    let parser = new DOMParser();
                    let doc = parser.parseFromString(column.content, 'text/html');
                    let body = doc.body;
                    let text = body.textContent || "";
                    text = text&&text.length>20?text.slice(0, 25)+'...':text
                    return [
                        h('div', text=='null'?'':text )
                    ]
                }
            },
            {show: true, label: '跟进时间',width:190, prop: 'followUpTime', sortable: false,},
            {show: true, label: '目的', width:90,prop: 'objectiveName', sortable: false},
            {show: true, label: '方向',width:60, prop: 'inOutMarkName', sortable: false,
                render: ({column}: { column: EmailsVO }) => {
                    return [
                        h('div', {style:column.inOutMarkName=='进'?'color:#EF352B':'color:#00c100'},column.inOutMarkName)
                    ]
                }
            },
            {show: true, label: '跟进方式',width:80, prop: 'followUpTypeName', sortable: false},
            {show: queryData.resourceType=='10'?true:false, label: '关联业务', prop: 'resourceTypeName', sortable: false,
                render: ({column}: { column: EmailsVO }) => {
                    return [
                        h('div', {},column.resourceTypeName?column.resourceTypeName+'/'+column.resourceName:'')
                    ]
                }
            },
            // {show: queryData.resourceType=='10'?true:false, label: '关联业务', prop: 'resourceName', sortable: false,},
            {show: true, label: '状态',width:80, prop: 'followStatus', sortable: false,
                render: ({column}: { column: EmailsVO }) => {
                    return [
                        h(ElButton, {
                            link: true, type: column.followStatus?'primary':'danger', onClick: ($event) => {
                                $event.stopPropagation()
                                if(column.type=='110'){
                                    if(column.followUpId){
                                        ElMessage.error('已跟进，状态不可修改')
                                    }else{
                                        followStatus(column.followStatus==1?0:1,[column.id])
                                    }

                                }else{
                                    ElMessage.error('跟进状态不可修改')
                                }
                            }
                        }, column.followStatus?'已跟进':'未跟进'),
                    ]
                }
            },
            {show: true, label: '跟进人', width:70,prop: 'createByName', sortable: false},
            // {show: true, label: '被阅读', prop: 'recipientRead', sortable: false,
            //     render: ({column}: { column: EmailsVO }) => {
            //         return [
            //             h('div', {},column.recipientRead?'已读':'未读')
            //         ]
            //     }
            // },
            {
                show: true,
                label: '操作',
                prop: 'operation',
                width:100,
                disabledMove: true,
                render: ({column}: { column: EmailsVO }) => {
                    return [
                        h(ElButton, {
                            link: true, type: column.type=='90' || column.inOutMark==1? 'primary' : 'success', onClick: ($event) => {
                                $event.stopPropagation()
                                let query = {}
                                if(column.type=='90'){ //跟进发邮件
                                    query = {
                                        email: column?.recipientls.join(',')
                                    }
                                }else{
                                    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.type=='90'?'发邮件':column.inOutMark==1?'回复':'重发'),
                    ]
                }
            },
        ],
        selectableKey:'type',
        selectableValue:'110',
        queryParams: {
            blurry: undefined,
            inOutMark: undefined,
            liaisonIdList: undefined,
            objectiveValue: undefined,
            followStatus: undefined,
            resourceType: undefined,
            followUpBeginTime: undefined,
            followUpEndTime: undefined,
            createdByList: undefined,
            customerId:queryData.id,
            followUpTypeValue: undefined,
        },
        listFn: emailFollow,
        keyId: 'id',
        menuId: router.currentRoute.value?.meta?.menuId,
    })

    const {queryParams} = toRefs(tableParams);

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

    const queryFormRef = ref<ElFormInstance>();

    /** 重置按钮操作 */
    const resetQuery = () => {
        daterange.value = ''
        getDate([])
        queryFormRef.value?.resetFields();
        handleQuery();
    }

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

    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 changeStyle = ()=>{
        if(queryData.resourceType==10){
            if(queryData.scopeMenuId){
                router.replace('/customer/customerDetail?id=' + queryData.id+'&preNextScopeMenuId='+queryData.preNextScopeMenuId+'&scopeMenuId='+router.currentRoute.value?.meta?.menuId+'&resourceType=10&blurry='+queryData.blurry+'&customerForm=10&customerStatusDictValue='+queryData.customerStatusDictValue+'&customerTypeDictValue='+queryData.customerTypeDictValue+'&customerLevelDictValue='+queryData.customerLevelDictValue+'&lastFollowUpTime='+queryData.lastFollowUpTime+'&queryRangeType='+queryData.queryRangeType+'&hasOrderForm='+queryData.hasOrderForm+'&hasPublicCustomer='+queryData.hasPublicCustomer+'&ownerByIds='+queryData.ownerByIds+'&hasFollowMode='+queryData.hasFollowMode+'&customerName='+queryData.customerName+'&liaisonName='+queryData.liaisonName+'&country='+queryData.country)
            }else{
                router.replace('../customer/customerDetail?id=' + customerDetail.value.id+'&scopeMenuId='+router.currentRoute.value?.meta?.menuId+'&resourceType=10')
            }
        }else{
            router.replace('/clue/detail?id=' + customerDetail.value.id+'&scopeMenuId='+router.currentRoute.value?.meta?.menuId+'&resourceType=11')
        }
    }

    // 邮件内容
    const sendEmail = () => {
        const { href } = router.resolve({
            path: '/email/send'
        })
        window.open(href, '_blank')
    }

    const emailLoading = ref(false)
    //获取邮件详情
    const getEmail = (id)=>{
        let params = {
            mailId:id,
            customerId:customerDetail.value.id?customerDetail.value.id:'',
        }
        emailLoading.value = true
        getEmailDetailContent(params).then(res => {
            if(res.success) {
                emailLoading.value = false
                getContent(res.result)
            }
        })
    }

    const getContent = (val) => {
        Econtent.value = val
        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] +'>')
            }
        }
    }
    const activeMail = ref() // 邮件类型
    const download = (item:any) =>{
        fileDownload({ attachmentId: item.id }, activeMail.value).then(res => {
            if(res) {
                downloadPlugins.download('download', res)
            }else {
                ElMessage.error('下载失败，请稍后再试')
            }
        })
    }

    const edit = ()=>{
        emit('handleEdit')
    }

    const followStatus=(followStatus,List)=>{
        let idList = []
        if(List.length>0){
            idList = List
        }else{
            if(!ids.value){
                ElMessage.error('请选择邮件')
                return;
            }else{
                idList = ids.value
            }
        }
        let params  = {
            followStatus,
            idList
        }
        editFollowStatus(params).then(res => {
            if(res.success) {
                handleQuery()
            }
        })
    }
    const showEmail = ref(false)
    const detail = ref()
    const handleCurrentChange = (item)=>{
        if(item.type=='110'){ //邮件
            getEmail(item.mailId)
            showEmail.value = true
            CustomerTable.value?.setCurrent()
        }else{
            showEmail.value = false
            let params = {
                id:item.followUpId,
                btnRole:[{type: 'edit', hasPermi: `customer:followUp:edit`}]
            }
            detail.value.open(params)
            CustomerTable.value?.setCurrent()
        }
    }
    // 左侧联系人搜索
    const searchLiaison = (item)=>{
        queryParams.value.liaisonIdList = [item.id]
        handleQuery()
    }
    // 左侧联系人编辑
    const editLiaison = (id)=>{
        router.push('/customer/liaison/add?id=' + id+'&type=edit')
    }
    // 联系人发邮件
    const emailLiaison = (email)=>{
        const { href } = router.resolve({
            path: '/email/send',
            query: {email}
        })
        window.open(href, '_blank')
    }
    const toWebsite = ()=>{
        if(customerDetail.value.customerCompany.website){
            window.open(customerDetail.value.customerCompany.website, '_blank')
        }
    }
    const handleVisibilityChange = () => {
        if(document.visibilityState === 'visible'){
            handleQuery()
        }
    }

    onMounted(() => {
        getDetail(queryData.id)
        getLiaison(queryData.id)
        toggleSideBar()
        document.addEventListener('visibilitychange', handleVisibilityChange);
    })


</script>
<style lang="scss" scoped>
.panel_area{
    width: 100%;
    flex-direction:row;
    overflow: hidden;
    .panel_left{
        width:290px;
        display: flex;
        flex-direction: column;
        .message{
            background-color: #fff;
            padding: 10px 16px;
            margin-bottom: 16px;
            border-radius: 8px;
            .title{
                color: #333;
                font-size: 16px;
                font-weight: bold;
                margin-bottom: 8px;
            }
            .item{
                color: #666;
                font-size: 14px;
                margin-bottom: 8px;
                display: flex;
                .label{
                    width: 74px;
                }
                .value{
                    flex: 1;
                    word-break: break-all;
                }
                .blue{
                    color: #1874FF;
                    cursor: pointer;
                }
            }
            .liaison_item{
                border-radius: 5px;
                border: 1px dashed #979797;
                width: 100%;
                padding: 7px 8px;
                margin-bottom: 16px;
                span{
                    cursor: pointer;
                    color: #1874FF;
                }
            }
        }
        .liaison{
            flex:1;
            height: 0;
            display: flex;
            flex-direction: column;
            margin-bottom: 0
        }
    }
    .panpel_right{
        display: flex;
        flex-direction: column;
        background-color: #fff;
        border-radius: 8px;
        flex:1;
        margin-left: 16px;
        position: relative;
        width: 0;
        .card-header{
            color: #333;
            font-size: 16px;
            font-weight: bold;
            padding:14px 16px;
            border-bottom: 1px solid #DCDEE2;
            align-items: center;
        }
        .table_form{
            padding:14px 16px;
            flex: 1;
            height:0;
            display: flex;
            flex-direction: column;
            .el-select,.el-input,.el-date-editor,.el-form-item{
                width: 100%;
            }
        }
        .detail{
				flex-direction: column;
				height: 100%;
				.detail-header{
					height: 48px;
					background: #F8FAFC;
					column-gap: 50px;
					padding: 0 16px;
					border-bottom: 1px solid #DCDEE2;
					.el-tooltip__trigger{
						flex: 1;
						overflow: hidden;
						white-space: nowrap;
						text-overflow: ellipsis;
					}
					.first-popover{
						max-width: 650px;
						flex: none;
					}
				}
				.detail-content{
					padding: 12px 16px;
					color: #666666;
					flex: 1;
					height: 0;
					overflow: auto;
					display: flex;
				}
			}
        .email_file{
            width: 240px;
            border-left:1px solid #DCDEE2;
            display: flex;
            flex-direction: column;
            padding-left: 16px ;
            .file{
                border-radius: 2px;
                border: 1px solid #1874FF;
                padding:4px 17px;
                color: #1874FF;
                margin:0 15px 10px 0;
                cursor: pointer;
                word-break: break-all;
            }
        }
    }
}

.follow_style{
    color: #1874FF;
    background-color: #fff;
}
</style>
<style>
    .max-width-popover {
        width: auto !important;
        max-width: 500px;
    }
</style>
