<template>
    <div class="detail_area">
        <div class="detail_header">
            <div class="detail_company flex">
                <div class="flex-center">
                    <div>
                        <div class="company_name">{{ showDetailData?.customerName }}</div>
                        <div class="company_user">
                            <span>线索归属：{{ showDetailData?.ownerByName }}</span>
                            <span>联系人姓名：{{ showDetailData?.liaison.name }}</span>
                            <span>下次跟进：{{ showDetailData?.nextFollowUpTime }}</span>
                        </div>
                    </div>
                </div>
                <div class="header_right flex" v-if="queryData.scopeMenuId">
                    <div class="left" :class="detailData?.previousId?'':'btn-grey'" @click="changePage(detailData?.previousId)">
                        <el-icon><ArrowLeft /></el-icon>
                    </div>
                    <div class="right" :class="detailData?.nextId?'':'btn-grey'" @click="changePage(detailData?.nextId)">
                        <el-icon><ArrowRight /></el-icon>
                    </div>
                </div>
            </div>
            <div class="operateBtn-div">
                <SelectDict
                    v-model="clueStatusDictValue"
                    :clearable="false"
                    placeholder="请选择线索状态"
                    dictCode="clue_status"
                    @onchange="changeStatus"
                ></SelectDict>
                <template v-for="item in operateBtn" :key="item.value">
                    <el-button  v-if="item.show" @click="openDialog(item.value)">{{ item.label }}</el-button>
                </template>
            </div>
        </div>
        <div class="detail_main">
            <InfoMainNav :navList="navList" @change="changeTab" ref="informationRef"></InfoMainNav>
            <div class="nav_detail" v-if="navValue == 'infomation'">
                <div class="nav_sec">
                    <div class="title flex">
                        <span class="bold">基本信息</span>
                    </div>
                    <div class="form_area flex">
                        <div class="form_item">
                            <div class="flex">
                                <div class="label">线索名称：</div>
                                <div class="value">{{ showDetailData?.customerName }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">尊称：</div>
                                <div class="value">{{ showDetailData?.liaison.callName }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">部门职务：</div>
                                <div class="value">{{ showDetailData?.liaison.departmentPosition }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">详细地址：</div>
                                <div class="value">{{ showDetailData?.liaison.address }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">线索状态：</div>
                                <div class="value">{{ showDetailData?.clueStatusName }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">企业网址：</div>
                                <div class="value">{{ showDetailData?.customerCompany?.website || '--' }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">备用网址：</div>
                                <div class="value">{{ showDetailData?.customerCompany?.website1 || '--' }}<sapn v-if="detailData?.customerCompany?.website2">, {{ detailData?.customerCompany?.website2 }}</sapn><sapn v-if="detailData?.customerCompany?.website3">, {{ detailData?.customerCompany?.website3 }}</sapn></div>
                            </div>
                            <div class="flex">
                                <div class="label">企业邮箱：</div>
                                <div class="value">{{ showDetailData?.customerCompany?.email || '--' }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">企业备用邮箱：</div>
                                <div class="value">{{ showDetailData?.customerCompany?.email1 || '--' }}<sapn v-if="detailData?.customerCompany?.email2">, {{ detailData?.customerCompany?.email2 }}</sapn><sapn v-if="detailData?.customerCompany?.email3">, {{ detailData?.customerCompany?.email3 }}</sapn></div>
                            </div>
                            <div class="flex">
                                <div class="label">Linkedin：</div>
                                <div class="value">{{ showDetailData?.liaison.linkedin }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">Whatsapp：</div>
                                <div class="value">{{ showDetailData?.liaison.whatsapp }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">固定电话：</div>
                                <div class="value">{{ showDetailData?.liaison.fixedLineTelephone }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">传真号码：</div>
                                <div class="value">{{ showDetailData?.liaison.faxNumber }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">宅电：</div>
                                <div class="value">{{ showDetailData?.liaison.homeElectricity }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">SKYPE：</div>
                                <div class="value">{{ showDetailData?.liaison.skype }}</div>
                            </div>
                        </div>
                        <div class="form_item">
                            <div class="flex">
                                <div class="label">联系人姓名：</div>
                                <div class="value">{{ showDetailData?.liaison.name }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">角色：</div>
                                <div class="value">{{ showDetailData?.liaison.liaisonRoleName }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">区域名称：</div>
                                <div class="value">{{ showDetailData?.continent }}<span v-if='showDetailData?.country'>/{{ showDetailData.country }}</span></div>
                            </div>
                            <div class="flex">
                                <div class="label">线索来源：</div>
                                <div class="value">{{ showDetailData?.customerSourceName }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">线索归属：</div>
                                <div class="value">{{ showDetailData?.ownerByName }}<span v-if='!detailData?.hasPublicCustomer&&detailData?.customerForm!=10'>（保护到期时间{{showDetailData?.protectionDate}}）</span></div>
                            </div>
                            <div class="flex">
                                <div class="label">电子邮箱：</div>
                                <div class="value">{{ showDetailData?.liaison.email }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">备用邮箱：</div>
                                <div class="value">{{ showDetailData?.liaison.email1 }}<sapn v-if="detailData?.liaison.email2">, {{ detailData?.liaison.email2 }}</sapn><sapn v-if="detailData?.liaison.email3">, {{ detailData?.liaison.email3 }}</sapn></div>
                            </div>
                            <div class="flex">
                                <div class="label">Facebook：</div>
                                <div class="value">{{ showDetailData?.liaison.facebook }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">手机号码：</div>
                                <div class="value">{{ showDetailData?.liaison.telephone }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">Twitter：</div>
                                <div class="value">{{ showDetailData?.liaison.twitter }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">邮政编码：</div>
                                <div class="value">{{ showDetailData?.liaison.postcode }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">QQ：</div>
                                <div class="value">{{ showDetailData?.liaison.qq }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">旺旺：</div>
                                <div class="value">{{ showDetailData?.liaison.wangwang }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">微信：</div>
                                <div class="value">{{ showDetailData?.liaison.wechat }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">备注信息</div>
                                <div class="value">{{showDetailData?.remark}}</div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="nav_sec">
                    <div class="title flex">
                        <span class="bold">系统信息</span>
                    </div>
                    <div class="form_area flex">
                        <div class="form_item">
                            <div class="flex">
                                <div class="label">系统编号：</div>
                                <div class="value">{{ showDetailData?.dataCode }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">创建人员：</div>
                                <div class="value">{{ showDetailData?.createByName }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">前所属部门：</div>
                                <div class="value">{{ showDetailData?.formerDeptName }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">更新时间：</div>
                                <div class="value">{{ showDetailData?.updateTime }}</div>
                            </div>
                            <!-- <div class="flex">
                                <div class="label">下次跟进：</div>
                                <div class="value">{{ detailData?.nextFollowUpTime }}</div>
                            </div> -->
                        </div>
                        <div class="form_item">
                            <div class="flex">
                                <div class="label">所属部门：</div>
                                <div class="value">{{ showDetailData?.deptName }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">前归属人：</div>
                                <div class="value">{{ showDetailData?.formerOwnerByName }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">创建时间：</div>
                                <div class="value">{{ showDetailData?.createTime }}</div>
                            </div>
                            <div class="flex">
                                <div class="label">最后跟进：</div>
                                <div class="value">{{ showDetailData?.lastFollowUpTime }}</div>
                            </div>
                            <!-- <div class="flex">
                                <div class="label"></div>
                                <div class="value"></div>
                            </div> -->
                        </div>
                    </div>
                </div>
                <div class="nav_sec">
                    <div class="title flex">
                        <span class="bold">线索动态</span>
                        <span class="flex-center">
                            <el-checkbox v-model="onlyFollow" size="large" />
                            <span style="margin: 0 16px 0 4px;">只看跟进</span>
                            <el-button type="primary" v-if="auth.hasPermi('clue:detail:xxgj')" @click="openDialog('AddFollow')">写跟进</el-button>
                        </span>
                    </div>
                    <div>
                        <Follow :onlyShowFollow="onlyFollow" :btnRole='roleBtn' :followParams="{ resourceType: '11', resourceTypeId: queryData.id }" :showAll="false" />
                    </div>
                </div>
            </div>
            <component v-else :is="navComponent" v-bind="navProps" :ref="($event: any) => setComponentsRef($event)"></component>
        </div>
    </div>
    <div
        class="drag_box"
        draggable="true"
        @dragstart="dragstart($event)"
        @dragend="dragend($event)"
        :style="`position: absolute;right:${elRight}px;bottom:${elBottom}px;z-index: 99`"
    >
        <div class='follow_style' @click="router.replace('../customer/followPanel?id=' + showDetailData.id+'&scopeMenuId='+queryData.scopeMenuId+'&resourceType=11')">
            <img src="@/assets/images/follow_style.png"/>
            <p>跟进模式</p>
        </div>
    </div>
    <!-- 按钮弹窗 -->
    <component
        :is="dialogComponent"
        :ref="($event: any) => setItemRef($event)"
        v-bind="componentProps"
        @refresh="detailRefresh"
    ></component>
</template>

<script setup lang="ts">
import Follow from '@/components/Follow/index.vue'
import CreateTask from '@/components/common/createTask.vue'
import AddFollow from '@/components/Follow/add.vue'
import ConvertCustomer from '@/components/common/convertCustomer.vue'
import Task from '@/components/detailCommon/task.vue'
import FollowUp from '@/components/detailCommon/followUp.vue'
import OperationLog from '@/components/detailCommon/operationLog.vue'
import ResourceList from '@/components/detailCommon/resourceList.vue'
import InfoMainNav from '@/components/common/InfoMainNav.vue'
import EmailList from '@/components/detailCommon/emailList.vue'
import { getNexCustomer, delCustomer, updateClueStatus, formateNullFieldData } from '@/api/customer';
import { CustomerVO } from '@/api/customer/types';
import { useTagsViewStore } from '@/store/modules/tagsView';
import { useDictCache } from '@/hooks/web/useDict'
import auth from '@/plugins/auth'
import useSettingsStore from '@/store/modules/settings'
import useAppStore from '@/store/modules/app';
const appStore = useAppStore();
const toggleSideBar = () => {
    appStore.closeSideBar(false);
}
toggleSideBar()
const { queryDictDetailByCodes } = useDictCache(['clue_status'])
queryDictDetailByCodes()

const onlyFollow = ref<boolean>(false)
const navList = [
    { label: '概况信息', value: 'infomation', show: auth.hasPermi('customer:detail:tab_gkxx') },
    { label: '跟进记录', value: 'follow', show: auth.hasPermi('customer:detail:tab_gjjl'), components: FollowUp },
    { label: '任务记录', value: 'task', show: auth.hasPermi('customer:detail:tab_rwjl'), components: Task },
    { label: '邮件记录', value: 'email', show: auth.hasPermi('customer:detail:tab_yjjl'), components: EmailList },
    { label: '相关附件', value: 'file', show: auth.hasPermi('customer:detail:tab_xgfj'), components: ResourceList },
    { label: '操作日志', value: 'operationLog', show: auth.hasPermi('customer:detail:tab_czrz'), components: OperationLog }
];

const roleBtn = ref([
    { type: 'commit', hasPermi: `clue:detail:tab_gjjl_tj` },
    { type: 'detail', hasPermi: `clue:detail:tab_gjjl_xq` },
    { type: 'remove', hasPermi: `clue:detail:tab_gjjl_sc` },
    {type: 'edit', hasPermi: `clue:detail:tab_gjjl_bj`},
])

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 navValue = ref<string>('infomation')
const navComponent = shallowRef()
const navProps = ref()
const changeTab = (value: string) => {
    navValue.value = value
    navComponent.value = navList.find(a => a.value == value)?.components
    if(value == 'task') {
        navProps.value = { resourceType: '11', resourceTypeId: queryData.id }
    }else if(value == 'email') {
        navProps.value = { customerId: queryData.id,resourceType:11}
    }else if(value == 'file') {
        navProps.value = { resourceType: '11', resourceTypeId: queryData.id, customerId: queryData.id }
    }else {
        let resourceType = value == 'follow' ? '11' : '10'
        navProps.value = { resourceType, resourceTypeId: queryData.id }
    }
    navProps.value.perPrefix = 'clue'
}

const componentsRef = ref()
const setComponentsRef = (el: any) => {
    if (el) {
        componentsRef.value = el
    }
}
const detailRefresh = () => {
    componentsRef.value?.handleQuery()
}

const clueStatusDictValue = ref()

// 获取线索详情数据
const router = useRouter();
let queryData: any = router.currentRoute.value.query
const detailData = ref<CustomerVO>()
const showDetailData = ref<CustomerVO>()
const useSetStore = useSettingsStore()
const getDetailData = () => {
    let params = { id: queryData.id, scopeMenuId: queryData.scopeMenuId, preNextScopeMenuId: queryData.scopeMenuId }
    getNexCustomer(params).then(res => {
        if (res.success) {
            showDetailData.value = formateNullFieldData(JSON.parse(JSON.stringify(res.result)))
            detailData.value = res.result
            clueStatusDictValue.value = res.result.clueStatusDictValue
            useSetStore.setTitle(detailData.value.customerName)
        }
    })
}

if (queryData.id) {
    getDetailData()
}

// 修改线索状态
const changeStatus = ({ value }: { value: string }) => {
    let params: any = { id: queryData.id, clueStatusDictValue: value, customerForm: '11' }
    updateClueStatus(params).then(res => {
        if(res.success) {
            ElMessage.success("更改线索状态成功")
            getDetailData()
        }
    })
}

// 操作按钮弹窗
let operateBtn = [
    { label: '转为客户', value: 'convert', show: auth.hasPermi('clue:detail:zwkh') },
    { label: '写新跟进', value: 'AddFollow', show: auth.hasPermi('clue:detail:xxgj') },
    { label: '新建任务', value: 'task', show: auth.hasPermi('clue:detail:xjrw') },
    { label: '发邮件', value: 'email', show: auth.hasPermi('clue:detail:fyj') },
    { label: '编辑线索', value: 'editClue', show: auth.hasPermi('clue:detail:bjxs') },
    // { label: '新增需求', value: 'addDemand' },
    { label: '删除线索', value: 'delClue', show: auth.hasPermi('clue:detail:scxs') },
]
const dialogComponent = shallowRef()
const componentProps = shallowRef()
const dialogRef = ref()
const setItemRef = (el: any) => {
    if (el) {
        dialogRef.value = el
    }
}
const openDialog = (val: string) => {
    if (val == 'email') {
        const { href } = router.resolve({
            path: '/email/send',
            query: {
                email: detailData.value?.liaison.email
            }
        })
        window.open(href, '_blank')
        return false
    }
    let query = {}
    switch (val) {
        case 'convert': // 转为客户
            dialogComponent.value = ConvertCustomer
            query = { obj: detailData.value }
            break;
        case 'AddFollow': // 写新跟进
            dialogComponent.value = AddFollow
            query = {
                type: 'add',
                resourceType: '11',
                resourceTypeId: queryData.id,
                resourceName: detailData.value?.customerName,
                resourceStageName: detailData.value?.clueStatusName,
                resourceStageDictValue: detailData.value?.clueStatusDictValue,
                customerId: queryData.id
            }
            break;
        case 'task': // 新建任务
            dialogComponent.value = CreateTask
            componentProps.value = { isCorrelation: false }
            query = { type: 'add', obj: { resourceType: '11', resourceTypeId: queryData.id } }
            break;
        case 'editClue': // 编辑线索
            router.push('./add?type=edit&id=' + queryData.id + '&hasPublicCustomer=' + (detailData.value?.hasPublicCustomer ? '1' : '0'))
            break;
        case 'delClue': // 删除线索
            ElMessageBox.confirm(
                '是否确认删除当前数据？',
                '确认提示',
                { type: 'warning', confirmButtonText: '提交' }
            ).then(() => {
                delCustomer(queryData.id).then(res => {
                    if(res.success) {
                        ElMessage.success('删除成功')
                        router.go(-1)
                        useTagsViewStore().delView(router.currentRoute.value)
                    }else{
                        ElMessage.error('删除失败')
                    }
                })
            }).catch(() => { })
            break;
    }
    if (['convert', 'AddFollow', 'task'].includes(val)) {
        nextTick(() => {
            dialogRef.value.open(query)
        })
    }

}

// 详情切换
const informationRef = ref()
const changePage = (id?:string)=>{
    if(id){
        router.replace('./detail?id=' + id + '&scopeMenuId=' + queryData.scopeMenuId)
    }
    changeTab('infomation')
    informationRef.value.resetNavList()
}
const route = useRoute();
watch(route, (newRoute, oldRoute) => {
    let queryDataNew: any = router.currentRoute.value.query
    if (queryDataNew.id) {
        queryData.id = queryDataNew.id
        getDetailData()
    }
});
</script>

<style scoped lang="scss">
    .operateBtn-div{
        .el-select{
            width: 120px;
            margin-right: 12px;
        }
    }
    .follow_style{
        background: #1874FF;
        color: #fff;
    }
</style>
