<template>
    <div class='follow_email' v-loading="emailLoading">
        <div class="btn_area">
            <template v-for="item in leftBtn">
                <el-button
                    @click="openDialog(item.value)"
                    v-if="item.show"
                >
                    {{ item.label }}
                </el-button>
            </template>
        </div>
        <div class="down">
            <div class="email_area">
                <div class='header_message'>
                    <div class='item'><div class="label">发件人</div><span>：</span><div class='value'>{{ emailDetail?.fromName }}({{ emailDetail?.from }})</div></div>
                    <div class='item' v-if='emailDetail?.sjr?.length>0'><div class="label">收件人</div><span>：</span><div class='value'>{{ emailDetail?.sjr.join(',') }}</div></div>
                    <div class='item' v-if='emailDetail?.csr?.length>0'><div class="label">抄送人</div><span>：</span><div class='value'>{{ emailDetail?.csr.join(',') }}</div></div>
                    <div class='item' v-if='emailDetail?.msr?.length>0'><div class="label">密送人</div><span>：</span><div class='value'>{{ emailDetail?.msr.join(',') }}</div></div>
                    <div class='item' v-if='emailDetail?.subject'><div class="label">主题</div><span>：</span><div class='value'>{{ emailDetail?.subject }}</div></div>
                    <div class='item' v-if='emailDetail?.sentDate'><div class="label">日期</div><span>：</span><div class='value'>{{ emailDetail?.sentDate }}</div></div>
                    <div class='item' v-if='emailDetail?.attachments&&emailDetail?.attachments?.length>0'><div class="label">附件</div><span>：</span>
                        <div v-if="emailDetail?.attachments">
                            <div class="file" v-for="item in emailDetail?.attachments" @click="downloadExt(item,item.fileExt)">{{ item.fileName }}.{{item.fileExt}}({{item.fileSizeName }})</div>
                        </div>
                    </div>
                </div>
                <div class="detail-editor" v-html="emailDetail?.content"></div>
            </div>
            <div class='follow_area' v-if='emailDetail?.customerls?.length==1'>
                <el-form
                    ref="ruleFormRef"
                    :model="ruleForm"
                    :rules="rules"
                    label-width="auto"
                    class="demo-ruleForm"
                    :size="formSize"
                    status-icon
                >
                    <el-form-item label="" prop="content">
                        <!-- <el-input
                            v-model="ruleForm.content"
                            maxlength="300"
                            style="width: 100%"
                            placeholder="勤跟进，多签单"
                            show-word-limit
                            type="textarea"
                        /> -->
                        <ckeditor class="template_ckeditor" type="mini" @sendContnet="getEditorContent" :content="ruleForm.content"></ckeditor>
                    </el-form-item>
                    <el-form-item label="上传附件：" class="form-item">
                        <Upload v-model="ruleForm.resourceIdList" :isTips='false' :resourceList="fileList" />
                    </el-form-item>
                    <el-form-item label="关联任务：" prop="taskId">
                        <el-select v-if="changeTask" placeholder="选择任务" v-model="ruleForm.taskId" filterable fit-input-width @change='gerTaskValue'>
                            <el-option v-for="item in taskList" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                        <el-input v-else v-model="ruleForm.taskContent" disabled/>
                    </el-form-item>
                    <el-form-item v-if="changeType" label="关联业务：" class="business-item" prop="resourceType">
                        <el-select placeholder="选择业务类型" v-model="customerResourceType" clearable @change="changeBusiness">
                            <el-option v-for="item in dictData.businessData" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                        <el-select placeholder="选择" v-model="CustomerResourceTypeId"  @change="changeBusinessId" v-loading="loading" fit-input-width filterable>
                            <el-option v-for="item in linkWorkData" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item v-if='emailDetail?.customerls?.length==1' :label="ruleForm.resourceType=='11'?'线索名称：':'客户名称：'" prop="customerName">
                        <el-input v-model="ruleForm.customerName" disabled/>
                    </el-form-item>
                    <!-- <el-form-item v-if='emailDetail.customerls.length>1' :label="ruleForm.resourceType=='11'?'线索名称：':'客户名称：'" prop="customerId">
                        <el-select-v2
                            v-model="ruleForm.customerId"
                            :options="customerOption"
                            placeholder="请选择客户"
                            filterable
                            @change='changeCustomer'
                        />
                    </el-form-item> -->


                    <!-- 客户、联系人 -->
                    <template v-if="ruleForm.resourceType=='10'||ruleForm.resourceType=='20'">
                        <el-form-item label="客户状态：" prop="resourceStageDictValue">
                            <SelectDict v-model="ruleForm.resourceStageDictValue" placeholder="客户状态" dictCode="customer_status"></SelectDict>
                        </el-form-item>
                    </template>
                    <!-- 线索 -->
                    <template v-if="ruleForm.resourceType=='11'">
                        <el-form-item label="线索状态：" prop="resourceStageDictValue">
                            <SelectDict v-model="ruleForm.resourceStageDictValue" placeholder="请选择线索状态"
                                dictCode="clue_status"></SelectDict>
                        </el-form-item>
                    </template>
                    <!-- 商机 -->
                    <template v-if="ruleForm.resourceType=='30'">
                        <el-form-item v-if="!changeType" label="商机标题：" prop="resourceName">
                            <el-input v-model="ruleForm.resourceName" disabled/>
                        </el-form-item>
                        <el-form-item label="商机阶段：" prop="resourceStageDictValue">
                            <SelectDict v-model="ruleForm.resourceStageDictValue" placeholder="请选择商机阶段"
                                        dictCode="business_stage"></SelectDict>
                        </el-form-item>
                    </template>
                    <!-- 订单 -->
                    <template v-if="ruleForm.resourceType=='40'">
                        <el-form-item v-if="!changeType" label="订单标题：" prop="resourceName">
                            <el-input v-model="ruleForm.resourceName" disabled/>
                        </el-form-item>
                    </template>
                    <el-form-item label="联系人：" prop="liaisonIdList" v-if="ruleForm.resourceType!='11'">
                        <el-select-v2
                            multiple
                            v-model="ruleForm.liaisonIdList"
                            :options="liaisonOption"
                            placeholder="请选择客户联系人"
                            filterable
                            :disabled="ruleForm.resourceType=='20'"
                        />
                    </el-form-item>

                    <el-form-item label="跟进目的：" prop="objectiveValue">
                        <SelectDict v-model="ruleForm.objectiveValue" placeholder="选择跟进目的"
                                        dictCode="objective_value"></SelectDict>
                    </el-form-item>
                    <el-form-item label="提醒谁看：" prop="remindUserIdsTemp">
                        <SelectUser multiple @onOk="selectsUser" v-model='ruleForm.remindUserIdsTemp'></SelectUser>
                    </el-form-item>
                    <CreateQuickTask v-model="ruleForm.task" label="创建下次跟进任务"></CreateQuickTask>
                </el-form>
                <el-button :loading="buttonLoading"  type="primary" @click="save()">提交</el-button>
            </div>
        </div>
    </div>
    <!-- 按钮弹窗 -->
    <component v-bind="componentProps" :is="dialogComponent" :ref="($event: any) => setItemRef($event)" @refresh=""></component>

    <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 { addFollow, getFollow } from '@/api/customer/follow';
import {useDictCache} from '@/hooks/web/useDict'
import { listDetialByCodes } from "@/api/system/dict/";
import { listLiaison } from '@/api/customer/liaison';
// import SelectUser from '@/components/SelectOrg/SelectUser.vue'
import Upload from '@/components/FileUpload/upload.vue'
import CreateQuickTask from '@/components/common/createQuickTask.vue';
import useUserStore from "@/store/modules/user";
import { noticeEventStore } from '@/store/modules/noticeEvent'
import ConvertCustomer from '@/components/common/convertCustomer.vue'
import { listTask } from '@/api/task';
import {getEmails, getEmailDetailContent, getRecord, setClickRecord, filePreviewUrl} from '@/api/emails'
import { EmailsVO } from '@/api/emails/types';
import { fileDownload,addEmailBlackList,trashEmails, emilsExport } from '@/api/emails'
import downloadPlugins from '@/plugins/download'
import moment from "moment";
import request from '@/utils/request';
import ckeditor from '@/components/ckeditor/index.vue'
const userNoticeEventStore = noticeEventStore()
const { queryDictDetailByCodes } = useDictCache(['customer_status', 'follow_up_type', 'sales_phase', 'task_remind_type', 'clue_status', 'task_mark_tag', 'task_priority_grade', 'task_remind_mode', 'business_stage','objective_value','in_out_mark'])
queryDictDetailByCodes()
    const followId = ref()
    const router: any = useRouter();
    let queryData = router.currentRoute.value.query

    const customerId = ref()
    const customerVO = ref()

    const leftBtn = ref([])
    leftBtn.value = [
        {label: '回复', value: 'replay', show: true},
        {label: '回复全部', value: 'replayAll', show: true},
        {label: '转发', value: 'return', show: true},
    ]
    const getNavData = ()=>{
        if(!customerId.value){
            if(queryData.emailType != 'senting') {
                if(!emailDetail.value.customerls || emailDetail.value.customerls.length == 1) {
                    leftBtn.value.push(
                        {label: '建联系人', value: 'createLiaison', show: true},
                        {label: '建线索', value: 'createClue', show: true},
                        {label: '建客户', value: 'createCustomer', show: true},
                    )
                }
            }

            leftBtn.value.push(
                {label: '删除', value: 'del', show: true},
                {label: '拉黑', value: 'block', show: true},
            )
        }else{
            if(!emailDetail.value.customerls){ // 非多客户
                if(customerVO.value.customerForm=='10'){
                    leftBtn.value.push(
                        {label: '新增商机', value: 'bussiness', show: true},
                        {label: '新增订单', value: 'order', show: true},
                    )
                }else{
                    leftBtn.value.push(
                        {label: '转为客户', value: 'customer', show: true},
                    )
                }
            }

        }
        leftBtn.value.push(
            {label: '导出邮件', value: 'export', show: true},
            {label: '浏览记录', value: 'record', show: true},
        )
    }

    const getEditorContent = (val: string) => {
        ruleForm.value.content = val
    }

    const changeTask = ref(true)
    const changeType = ref()
    const customerResourceType = ref()
    const CustomerResourceTypeId = ref()


    const dictData: any = reactive({
        businessData: []
    })
    const getContact = ()=>{
        changeType.value=true
        listDetialByCodes(['work_data_group']).then((res => {
            if(res.success) {
                dictData.businessData = res.result['work_data_group'].filter(item=>item.label=='商机'||item.label=='订单')
            }
        }))
    }

    const linkWorkData = ref<DictDataOption[] | null>([])
    const loading = ref(false)
    const typeList = ref([])
    const changeBusiness = (val: string) => {
        if(val){
            ruleForm.value.resourceTypeId = undefined
            CustomerResourceTypeId.value = undefined
            ruleForm.value.resourceStageDictValue = '' //客户关联业务 置空商机或订单状态
            ruleForm.value.dictCode = val=='30'?'business_stage':''
            let obj: { extField: string } = dictData.businessData.find((a: { value: string }) => a.value == val)
            if(!obj.extField) return
            let extField =  JSON.parse(obj.extField)
            ruleForm.value.resourceType = val
            let params: any = { pageIndex: 1, pageSize: 999999,customerId: ruleForm.value.customerId, commonScope: 1, commonScopeType: val }
            loading.value = true
            request({
                url: extField.requesUrl,
                method: extField.method,
                data: params
            }).then(res => {
                if(res.success) {
                    typeList.value = res.result.records
                    linkWorkData.value = (res.result.records || []).map((item: any) => {
                        let data = { label: item[extField.fieldKey.nameKey], value: item[extField.fieldKey.idKey] }
                        return data
                    })
                }
            }).finally(() => {
                loading.value = false
            })
        }else{
            CustomerResourceTypeId.value = ''
            ruleForm.value.resourceType = queryData.resourceType
            ruleForm.value.resourceTypeId = queryData.customerId
            linkWorkData.value = []
            ruleForm.value.dictCode = 'customer_status'
            ruleForm.value.resourceStageDictValue = customerVO.value.customerStatusDictValue
        }

    }
    const changeBusinessId = (val)=>{
        ruleForm.value.resourceTypeId = val
        if(val){
            if(ruleForm.value.resourceType =='30'){
                let current = typeList.value.filter(item=>item.id== val)
                ruleForm.value.resourceStageDictValue = current[0].stage
            }
        }
    }

    const dialogComponent = shallowRef()
    const dialogRef = ref()
    const setItemRef = (el: any) => {
        if (el) {
            dialogRef.value = el
        }
    }
    const componentProps = shallowRef()
    let propData = {}
    const openPage = (url,queryData)=>{
        const { href } = router.resolve({
            path: url,
            query: queryData
        })
        window.open(href, '_blank')
    }
    const openDialog = (val: string, column?: any) => {
        let query = {}
        let email = emailDetail.value.folder=='SENT'||emailDetail.value.folder=='SENTING'?emailDetail.value.recipient:emailDetail.value.from
        switch (val) {
            case 'replay': //回复
                query = {
                    id: emailDetail.value.id,
                    type:'reply'
                }
                openPage('/email/send',query)
                break;
            case 'replayAll': //回复全部
                query = {
                    id: emailDetail.value.id,
                    type:'replyAll'
                }
                openPage('/email/send',query)
                break;
            case 'return': //转发
                query = {
                    id: emailDetail.value.id,
                        type:'forward'
                }
                openPage('/email/send',query)
                break;
            case 'customer': // 转为客户
                propData = { obj: customerVO.value }
                dialogComponent.value = ConvertCustomer
                dialogRef.value.open(propData)
                break;
            case 'bussiness': // 新增商机
                 router.push('/business_opportunity/addbus?customerId='+customerId.value)
                break;
            case 'order': // 新增订单
                router.push('/order/add?customerId='+customerId.value+'&type=add')
                break;
            case 'createLiaison':
                query = {
                    type:'add',
                    email: email
                }
                openPage('/customer/liaison/add',query)
                break;
            case 'createClue':
                query = {
                    type:'add',
                    email: email
                }
                openPage('/clue/add',query)
                break;
            case 'createCustomer':
                query = {
                    type:'add',
                    email: email
                }
                openPage('/customer/addCustomer',query)
                break;
            case 'block': //拉黑
                blockEmail()
                break;
            case 'del': //删除
                delEmail()
                break;
            case 'export':
                emilsExport({ mailId: emailDetail.value.id }, 'alone').then(res => {
                    try {
                        downloadPlugins.download('export', res)
                    }catch {
                        ElMessage.error('导出失败，请稍后再试')
                    }
                })
                break;
            case 'record':
                recordTableParams.value = {
                    tableColumn: [
                        { show: true, label: '部门', prop: 'deptName' },
                        { show: true, label: '人员', prop: 'ownerByName' },
                        { show: true, label: '浏览时间', prop: 'createTime' },
                    ],
                    queryParams: {
                        customerMailId: queryData.id,
                    },
                    listFn: getRecord,
                }
                recordVisible.value = true
                break;
        }
    }
    const getFollowMsg = async (data:any) => {
        reset()
        if(data.followUpId){
            followId.value = data.followUpId
            await followDetail(followId.value)
            await getLiaison(customerId.value) //修改
        }else{
            getCustomer()
        }
    }
    const getCustomer = async ()=>{
        if(customerVO.value.customerForm=='10'||queryData.resourceType=='10'){
            getContact()
        }
        ruleForm.value.inOutMark = emailDetail.value.inOutMark //邮件的出入方向默认是跟进的出入方向
        ruleFormRef.value?.resetFields();
        ruleForm.value.customerId = customerId.value?customerId.value:''
        ruleForm.value.customerName = customerVO.value?.customerName?customerVO.value?.customerName:customerVO.value?.resourceName
        ruleForm.value.resourceType = customerVO.value?.customerForm?customerVO.value?.customerForm:queryData.resourceType
        ruleForm.value.resourceTypeId = customerId.value?customerId.value:''
        ruleForm.value.mailId = emailDetail.value.id?emailDetail.value.id:''
        ruleForm.value.resourceName = customerVO.value?.resourceName?customerVO.value?.resourceName:''
        // ruleForm.value.resourceStageName = data.resourceStageName?data.resourceStageName:''
        ruleForm.value.resourceStageDictValue = customerVO.value?.customerStatusDictValue?customerVO.value?.customerStatusDictValue:customerVO.value?.clueStatusDictValue
        ruleForm.value.taskId = emailDetail.value.taskId
        ruleForm.value.dictCode = (customerVO.value?.resourceType=='10'||customerVO.value?.resourceType=='20')?'customer_status':customerVO.value?.resourceType=='11'?'clue_status':customerVO.value?.resourceType=='30'?'business_stage':''
        changeRule(customerVO.value?.resourceType)
        await getLiaison(customerId.value)
        getTask()
    }
    const changeCustomer=(val)=>{
        customerVO.value = emailDetail.value?.customerls.filter(item=>val==item.id)[0]
        customerId.value = customerVO.value.id
        getCustomer()
        getNavData()
    }
    const changeRule = (type)=>{
        if(type=='11'){
            rules.value.resourceStageDictValue[0].message='请选择线索状态'
        }
        if(type=='30'){
            rules.value.resourceStageDictValue[0].message='请选择商机阶段'
        }
    }
    const fileList = ref([])
    const followDetail = async (id:any) =>{
        await getFollow(id).then(res => {
            if (res.success) {
                setValue(res)
            }
        })
    }
    const setValue = async (res)=>{
        Object.assign(ruleForm.value,res.result)
        ruleForm.value.content = res.result.content
        await nextTick()
        if(ruleForm.value.resourceType=='10'){
            getContact()
        }
        setTimeout(() => { ruleForm.value.content = res.result.content+'<span></span>' }, 500);
        if(ruleForm.value.taskId){
            changeTask.value = false
        }
        ruleForm.value.remindUserIdsTemp = ruleForm.value.remindUserIds?ruleForm.value.remindUserIds.split(','):[]
        fileList.value = res.result.resourceList
        changeRule(ruleForm.value.resourceType)
        getTask()
    }

    const emailDetail = ref()

    const customerOption = ref([])
    const emailLoading = ref(false)
    //获取邮件详情
    const getEmail = ()=>{
        let params = {
            mailId:queryData.id,
            customerId:queryData.customerId?queryData.customerId:'',
        }
        emailLoading.value = true
        getEmailDetailContent(params).then(res => {
            if(res.success) {
                customerVO.value = res.result.customerls?res.result.customerls[0]:[]
                customerId.value = customerVO.value.id
                if(res.result.customerls?.length>1){
                    // 客户列表数据
                    customerOption.value = res.result.customerls.map((item: { customerName: string, id: number|string }) => {
                        let obj = { label: item.customerName, value: item.id as string}
                        return obj
                    })
                }
                getContent(res.result) // 修改邮件内容格式
                getNavData() //邮件顶部按钮
                if(customerVO){
                    getFollowMsg(res.result)
                }
            }
        }).finally(() => {
            emailLoading.value = false
        })
    }
    const getContent = (val) => {
        emailDetail.value = val
        let sjr = val.recipient.split(',')
        emailDetail.value.sjr = []
        emailDetail.value.csr = []
        emailDetail.value.msr = []
        for(let i = 0;i < sjr.length; i++) {
            emailDetail.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++) {
                emailDetail.value.csr.push((val.recipientCcName || val.recipientCc).split(',')[i] + '<' + csr[i] +'>')
            }
        }
        if(val.recipientBcc){
            let msr = val.recipientBcc.split(',')
            for(let i = 0;i < msr.length; i++) {
                emailDetail.value.msr.push((val.recipientBccName || val.recipientBcc).split(',')[i] + '<' + msr[i] +'>')
            }
        }
    }
    const activeMail = ref() // 邮件类型
    const download = (item:any) =>{
        fileDownload({ attachmentId: item.id }, queryData.emailType).then(res => {
            if(res) {
                downloadPlugins.download('download', res)
            }else {
                ElMessage.error('下载失败，请稍后再试')
            }
        })
    }

    const downloadExt = (item:any,ext?: string) =>{
        if (canPreview(ext)) {
            const url = filePreviewUrl(item.id , queryData.emailType);
            window.open(url, '_blank');
        } else {
            fileDownload({ attachmentId: item.id }, queryData.emailType).then(res => {
                if(res) {
                    downloadPlugins.download('download', res)
                }else {
                    ElMessage.error('下载失败，请稍后再试')
                }
            })
        }
    }

    const PREVIEW_EXTS = ['pdf', 'png', 'jpg', 'jpeg', 'gif', 'webp'];

    const canPreview = (ext) => {
        if (!ext) return false;
        return PREVIEW_EXTS.includes(ext.toLowerCase());
    }

    const buttonLoading = ref(false);
    // 新建跟进
    interface RuleForm {
        dictCode:any,
        customerId:any,
        customerName:any,
        resourceType:string,
        resourceTypeId:any,
        resourceName:string,
        resourceStageName:string,
        resourceStageDictValue:any,
        content: string,
        // customerId: any,
        followUpMemberId: any,
        followUpTime: string,
        followUpTypeValue: string | number,
        id: any,
        liaisonIdList: any,
        remindUserIds: string,
        remindUserIdsTemp: (string | number)[],
        setTask:boolean,
        resourceIdList:string[] | number[],
        task:{
            taskBeginTime:string,
            taskContent:string,
            ownerBy:string,
            remindType:string,
            remindModels:any,
            isCreateTask: boolean,
            objectiveValue:any,
        },
        taskId?: string,
        objectiveValue:any,
        inOutMark:any,
        mailId:any,
        taskContent?: string,
        subject?: string,
    }
    const formSize = ref('default')
const ruleFormRef = ref<ElFormInstance>()
const initForm: RuleForm = {
    dictCode:'',
    customerId: '',
    customerName: '',
    resourceType: '',
    resourceTypeId: '',
    resourceName: '',
    resourceStageName: '',
    resourceStageDictValue: '',
    content: '',
    // customerId:customerId?customerId:'',
    followUpMemberId: null,
    followUpTime: '',
    followUpTypeValue: 5,
    id: null,
    liaisonIdList: null,
    remindUserIds: '',
    remindUserIdsTemp: [],
    setTask: true,
    task: {
        taskBeginTime: '',
        taskContent: '',
        ownerBy: '',
        remindType: '',
        remindModels: ['site'],
        isCreateTask: false,
        objectiveValue:'',
    },
    taskId: undefined,
    resourceIdList: [],
    objectiveValue:undefined,
    inOutMark:undefined,
    mailId:'',
    subject:undefined,
}
const ruleForm = ref<RuleForm>({ ...initForm })

const rules = ref({
    followUpTypeValue: [
        { required: true, message: '请选择跟进状态', trigger: 'change' },
    ],
    content: [
        { required: true, message: '请填写本次跟进内容', trigger: 'blur' },
    ],
    objectiveValue: [
        { required: true, message: '请选择填写本次跟进目的', trigger: 'change' },
    ],
    customerId: [
        { required: true, message: '请选择跟进客户', trigger: 'blur' },
    ],
    resourceStageDictValue: [
        { required: true, message: ruleForm.value.resourceType == '30' ? '请选择商机阶段' : '请选择客户状态', trigger: 'change' },
    ],
    liaisonIdList: [
        { required: true, message: '请选择联系人', trigger: 'change' },
    ],
    'task.taskBeginTime': [
        { required: true, message: '请选择下次跟进时间', trigger: 'blur' },
    ],
    'task.taskContent': [
        { required: true, message: '请填写下次任务主题', trigger: 'blur' },
    ],
    'task.objectiveValue': [
        { required: true, message: '请选择下次任务目的', trigger: 'change' },
    ],
    'task.remindType': [
        { required: true, message: "任务提醒不能为空", trigger: "change" }
    ],
    'task.ownerBy': [
        { required: true, message: '请选择跟进人员', trigger: 'change' },
    ],
})


const disabledDates = (time:Date) => {
    // 选择今天以及今天之前的日期
    return time.getTime() > Date.now() // 如果后面-8.64e7就是不可以选择今天的
}

const reset = () => {
    ruleForm.value = { ...initForm };
}

    const remindUserIds = ref([])
    const selectsUser = (data: any) => {
        ruleForm.value.remindUserIds = data.map(item=>item.id.toString()).join(',')
    }

    const liaisonOption = ref([])
    const getLiaison = (customerId: string) => {
        listLiaison({ pageIndex: 1, pageSize: 999999, customerId }).then(res => {
            if(res.success) {
                liaisonOption.value = res.result.records.map((item: { name: string, id: number }) => {
                    let obj = { label: item.name, value: item.id }
                    return obj
                })
            }
        })
    }
    const taskList = ref([])
    const taskListAll= ref([])
    const getTask = () => {
        listTask({ pageIndex: 1, pageSize: 999999, resourceType: ruleForm.value.resourceType,resourceTypeId: ruleForm.value.resourceTypeId,taskStatusList:[0,3,4],commonScope: 1, commonScopeType: ruleForm.value.resourceType }).then(res => {
            if(res.success) {
                taskListAll.value = res.result.records
                taskList.value = res.result.records.map((item: { taskContent: any, id: any }) => {
                    let obj = { label: item.taskContent, value: item.id }
                    return obj
                })
            }
        })
    }
    const gerTaskValue = (val)=>{
        let currentTask:any = taskListAll.value.filter(item=>item.id == val)
        ruleForm.value.followUpTime = currentTask[0].taskBeginTime
        ruleForm.value.subject = currentTask[0].taskContent
        ruleForm.value.objectiveValue = currentTask[0].objectiveValue
        if(changeType.value){
            if(currentTask[0].resourceType=='30'||currentTask[0].resourceType=='40'){
                customerResourceType.value = currentTask[0].resourceType
                changeBusiness(currentTask[0].resourceType)
                ruleForm.value.resourceTypeId = currentTask[0].resourceTypeId
                CustomerResourceTypeId.value = currentTask[0].resourceTypeId
                if(currentTask[0].resourceType=='30'){
                    ruleForm.value.resourceStageDictValue = currentTask[0].resourceObject.stage
                }
            }
        }
        console.log(ruleForm.value)
    }
    /** 保存按钮 */
    const save = () => {
        if(customerResourceType.value&&!CustomerResourceTypeId.value){
            ElMessage.error(`请选择关联的${customerResourceType.value=='30'?'商机业务':'订单业务'}`);
            return false
        }
        console.log(ruleForm.value)
        ruleFormRef.value?.validate(async (valid: boolean) => {
            ruleForm.value.subject = emailDetail.value.subject
            ruleForm.value.followUpTime = moment().format("YYYY-MM-DD HH:mm:ss")
            if (valid) {
                buttonLoading.value = true;
                await addFollow(ruleForm.value).finally(() => buttonLoading.value = false);
                ElMessage.success("新建跟进成功");
                ruleFormRef.value?.resetFields();
                window.close();
                reset()
            }
        });
    }
    // 拉黑
    const blockEmail = ()=>{
        ElMessageBox.confirm(
            '是否确认拉黑？',
            '确认提示',
            { type: 'warning', confirmButtonText: '提交' }
        ).then(() => {
            addEmailBlackList({emailAddress:emailDetail.value.from}).then(res => {
                if(res.success) {
                    ElMessage.success("拉黑成功");
                }
            })
        }).catch(() => {})

    }
    // 删除
    const delEmail = ()=>{
        ElMessageBox.confirm(
            '是否确认删除当前邮件？',
            '确认提示',
            { type: 'warning', confirmButtonText: '提交' }
        ).then(() => {
            let params = {
                emailIds:[emailDetail.value.id],
                isTrash:1,
            }
            trashEmails(params).then(res => {
                if(res.success) {
                    ElMessage.success('邮件已移至垃圾箱')
                    setTimeout(() => {
                        window.close()
                    }, 1500)
                }
            })
        }).catch(() => {})
    }

    const recordVisible = ref(false)
    const recordTableParams = ref()

    onMounted(() => {
        getEmail()
        setClickRecord(queryData.id)
    })


</script>
<style lang="scss" >
.follow_email{
    background-color: #fff;
    padding: 20px 16px;
    width: 100%;
    height: 100%;
    overflow-y: auto;
    .btn_area{
        margin-bottom: 20px;
    }
    .down{
        display: flex;
        .email_area{
            padding: 2px 0;
            flex:1;
            width: 0;
            .file{
                cursor: pointer;
                color: #1874FF
            }
            .detail-editor{
                padding: 20px;
                p{
                    line-height: 32px;
                }
                ul{
                    padding-inline-start: 20px;
                    margin-block-end: 0;
                    margin-block-start: 0;
                    li{
                        list-style: disc !important;
                    }
                }
                ol{
                    padding-inline-start: 20px;
                    margin-block-end: 0;
                    margin-block-start: 0;
                    li{
                        list-style: decimal !important;
                    }
                }
                :deep(img){
                    max-width: 100%;
                    height: auto !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(ul, li, p){
                    //margin: 0px 0;
                }
                :deep(a){
                    text-decoration: underline;
                    color: #1874FF;
                }
            }
        }
        .follow_area{
            width: 450px;
            padding: 2px 16px;
            border-left: 1px solid #F8FAFC;
            overflow-y: auto;
        }
        .header_message{
            background-color: #F8FAFC;
            padding: 20px 16px;
            .item{
                display: flex;
                span{
                    margin-right:18px;
                }
                .label{
                    width: 48px;
                    text-align: justify;
                    text-align-last: justify;
                }
                .value{
                    flex:1;
                    word-break: break-all;
                }
            }
        }
    }
}
.business-item{
    :deep(.el-form-item__content){
        display: flex;
        column-gap: 0;
        .el-select{
            flex:1
        }
        .el-input{
            flex: 2
        }
    }
}
</style>
