<template>
    <el-card shadow="never" class="list-card">
        <template #header>
            <HeaderSearch :queryParams="queryParams" @handleQuery="handleQuery" />
        </template>

        <Table ref="clueTable" :tableParams="tableParams" :btnRole="btnRole" @handleAdd="handleAdd('add')"
            @handleEdit="handleAdd('edit', $event)" @selectionChange="handleSelectionChange">
            <template #left>
                <el-button :type="item.value=='check'?'danger':''" v-for="item in leftBtn" :key="item.value" @click="openDialog(item.value)" v-hasPermi="[item.hasPermi]">
                    {{ item.label }}
                </el-button>
            </template>
            <template #right>
                <el-checkbox v-model="followStyle" label="跟进模式" @change='setFollow'></el-checkbox>
                <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="选择跟进模式后，列表将展示有最新邮件和待跟进的客户，且客户详情切换至跟进面板状态"
                    placement="top"
                    style='margin-right: 10px;'
                >
                    <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
            </template>
        </Table>
    </el-card>

    <!-- 左侧按钮弹窗 -->
    <component
        :is="dialogComponent"
        v-bind="componentProps"
        :ref="($event: any) => setItemRef($event)"
        @refresh="handleQuery"
    ></component>
</template>

<script setup lang="ts">
    import { listCustomer, delCustomer } from '@/api/customer';
    import { CustomerVO, CustomerQuery } from '@/api/customer/types';
    import Table from '@/components/Table/index.vue'
    import { tableTypes } from '@/components/Table/types'
    import HeaderSearch from '../components/search.vue'
    import ConvertCustomer from '@/components/common/convertCustomer.vue'
    import CreateTask from '@/components/common/createTask.vue'
    import TransferClue from '@/components/common/transferClue.vue'
    import InSeas from '@/components/common/inSeas.vue'
    import AddFollow from '@/components/Follow/add.vue'
    import { useDictCache } from '@/hooks/web/useDict'
    import CustomerCheck from '@/components/common/customerCheck.vue'
    import auth from '@/plugins/auth';
    const { queryDictDetailByCodes } = useDictCache(['customer_source', 'clue_status'])
    queryDictDetailByCodes()

    const props = defineProps({
        perPrefix: {
            type: String,
            required: true
        },
        queryRangeType: {
            type: Number
        }
    })
    const followStyle = ref(false)
    const router = useRouter();
    const btnRole = ref([
        { type: 'add', hasPermi: `clue:${ props.perPrefix }:add` },
        { type: 'edit', hasPermi: `clue:${ props.perPrefix }:edit` },
        { type: 'remove', hasPermi: `clue:${ props.perPrefix }:remove` },
        { type: 'import', hasPermi: `clue:${ props.perPrefix }:import` },
        { type: 'export', hasPermi: `clue:${ props.perPrefix }:export` }
    ])

    const tableParams = reactive<tableTypes<CustomerQuery, CustomerVO>>({
        cloumnCode: props.perPrefix,
        menuId: router.currentRoute.value?.meta?.menuId,
        tableColumn: [
            { show: true, label: '线索名称', prop: 'customerName', sortable: true, render: ({ column }: { column: CustomerVO }) => {
                return h('span', { class: 'link', onClick: () => { detail(column.id) } }, column.customerName)
            }},
            { show: true, label: '联系人姓名', prop: 'liaison.name', sortable: false },
            { show: true, label: '邮箱', prop: 'liaison.email', sortable: false },
            { show: true, label: '归属人', prop: 'ownerByName', sortable: false },
            { show: true, label: '最后跟进', prop: 'lastFollowUpTime', sortable: true },
            { show: true, label: '未跟进天数', prop: 'noFollowUpDate', sortable: true },
            { show: true, label: '创建时间', prop: 'createTime', sortable: true },
            { show: false, label: '尊称', prop: 'liaison.callName', sortable: false },
            { show: false, label: '角色', prop: 'liaison.liaisonRoleName', sortable: false },
            { show: false, label: '部门职务', prop: 'liaison.departmentPosition', sortable: false },
            { show: false, label: '所属大洲', prop: 'continent', sortable: true },
            { show: false, label: '所属国家', prop: 'country', sortable: true },
            { show: false, label: '详细地址', prop: 'liaison.address', sortable: false },
            { show: false, label: '线索来源', prop: 'customerSourceName', sortable: false },
            { show: false, label: '线索状态', prop: 'clueStatusName', sortable: false },
            { show: true, label: '企业网址', prop: 'customerCompany.website', sortable: false },
            { show: false, label: 'Linkedin', prop: 'liaison.linkedin', sortable: false },
            { show: false, label: 'Whatsapp', prop: 'liaison.whatsapp', sortable: false },
            { show: false, label: '固定电话', prop: 'liaison.fixedLineTelephone', sortable: false },
            { show: false, label: '传真号码', prop: 'liaison.faxNumber', sortable: false },
            { show: false, label: '宅电', prop: 'liaison.homeElectricity', sortable: false },
            { show: false, label: 'SKYPE', prop: 'liaison.skype', sortable: false },
            { show: false, label: '微信', prop: 'liaison.wechat', sortable: false },
            { show: false, label: 'Facebook', prop: 'liaison.facebook', sortable: false },
            { show: false, label: '手机号码', prop: 'liaison.telephone', sortable: false },
            { show: false, label: 'Twitter', prop: 'liaison.twitter', sortable: false },
            { show: false, label: '邮政编码', prop: 'liaison.postcode', sortable: false },
            { show: false, label: 'QQ', prop: 'liaison.qq', sortable: false },
            { show: false, label: '旺旺', prop: 'liaison.wangwang', sortable: false },
            {
                show: true, label: '操作', width: 200, prop: 'operation', disabledMove: true, render: ({ column }: { column: CustomerVO }) => {
                    let followBtn = auth.hasPermi(`clue:${ props.perPrefix }:gj`) ?
                        h(ElButton, { link: true, type: 'primary', onClick: () => { openDialog('follow', column) } }, '跟进') : ''
                    let toppingBtn = auth.hasPermi(`clue:${ props.perPrefix }:zd`) ?
                        h(ElButton, { link: true, type: 'primary' }, '置顶'): ''
                    return [
                        followBtn,
                        // toppingBtn
                    ]
                }
            }
        ],
        queryParams: {
            blurry: undefined,
            customerSourceDictValue: undefined,
            clueStatusDictValue: undefined,
            ownerByIds: undefined,
            customerForm: props.perPrefix == 'transferCustom' ? 10 : 11,
            queryRangeType: props.perPrefix == 'transferCustom' ? 0 : props.queryRangeType,
            hasPublicCustomer: 0,
            hasFollowMode:false,
            customerName: undefined,
            liaisonName: undefined,
            country: undefined,
            hasFromClue: props.perPrefix == 'transferCustom'
        },
        listFn: listCustomer,
        delFn: delCustomer,
        keyId: 'id',
        importCode: 'IMPORT_CLUE_EXCEL',
        exportCode: 'EXPORT_CLUE_EXCEL',
        commonQueryOrderBy: 'lastFollowUpTime',
        sortMethod: 'asc'
    })

    const { queryParams } = toRefs(tableParams);

    let leftBtn = [
        { label: '转为客户', value: 'convert', hasPermi: `clue:${ props.perPrefix }:zwkh` },
        { label: '转移线索', value: 'transfer', hasPermi: `clue:${ props.perPrefix }:zyxs` },
        { label: '移入公海', value: 'inSeas', hasPermi: `clue:${ props.perPrefix }:yrgh` },
        { label: '新建任务', value: 'task', hasPermi: `clue:${ props.perPrefix }:xjrw` },
        { label: '发邮件', value: 'email', hasPermi: `clue:${ props.perPrefix }:fyj` },
        { label: '查重', value: 'check', hasPermi: `clue:${ props.perPrefix }:fyj` }
    ]

    const setFollow  = (val)=>{
        tableParams.queryParams.hasFollowMode = val
        handleQuery()
    }

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

    /** 多选框选中数据 */
    const ids = ref<CustomerVO[]>([])
    const handleSelectionChange = (selection: CustomerVO[]) => {
        ids.value = selection
    }

    /** 新增按钮操作 */
    const handleAdd = (type: string, data?: CustomerVO) => {
        // 已转客户的菜单编辑跳去客户的编辑页面
        if(props.perPrefix == 'transferCustom') {
            router.push('../customer/addCustomer?type=' + type + "&id=" + data?.id)
        }else {
            router.push('./add?type=' + type + "&id=" + data?.id)
        }
    }

    // 左侧按钮弹窗
    const dialogComponent = shallowRef()
    const componentProps = shallowRef()
    const dialogRef = ref()
    const setItemRef = (el: any) => {
        if (el) {
            dialogRef.value = el
        }
    }
    const openDialog = (val: string, data?: CustomerVO) => {
        if(val != 'follow'&&val != 'check' && ids.value.length == 0) {
            ElMessage.error("请选择数据")
            return false
        }
        if(val == 'convert' && ids.value.length > 1) {
            ElMessage.error("请选择单一条数据转为客户")
            return false
        }
        if (val == 'email') {
            let params = ids.value.map(item => item.liaison.email).join(",")
            const { href } = router.resolve({
                path: '/email/send',
                query: {
                    email: params
                }
            })
            window.open(href, '_blank')
            return false
        }
        let query = {}
        let idList = ids.value.map(item => item.id)
        switch (val) {
            case 'convert': // 转为客户
                dialogComponent.value = ConvertCustomer
                query = { obj: ids.value[0] }
                break;
            case 'transfer': // 转移线索
                dialogComponent.value = TransferClue
                query = {
                    resourceType: '11',
                    typeName: '线索',
                    idList
                }
                break;
            case 'inSeas': // 移入公海
                dialogComponent.value = InSeas
                query = idList
                break;
            case 'task': // 新建任务
                dialogComponent.value = CreateTask
                componentProps.value = { isCorrelation: false }
                query = { type: 'add', obj: { resourceType: '11', resourceTypeIdls: idList } }
                break;
            case 'follow': // 跟进
                dialogComponent.value = AddFollow
                query = {
                    type: 'add',
                    resourceType: '11',
                    resourceTypeId: data?.id,
                    resourceName: data?.customerName,
                    resourceStageName: data?.clueStatusName,
                    resourceStageDictValue: data?.clueStatusDictValue,
                    customerId: data?.id
                }
                break;
            case 'check': // 查重
                dialogComponent.value = CustomerCheck
                query = {
                    resourceType: '11',
                }
                break;
        }
        nextTick(() => {
            dialogRef.value.open(query)
        })
    }

    const detail = (id: string | number) => {
        if(followStyle.value){
            let resourceType = props.perPrefix == 'transferCustom' ? '10' : '11'
            router.pushTarget('/customer/followPanel?id=' + id+'&scopeMenuId='+router.currentRoute.value?.meta?.menuId+'&resourceType=' + resourceType)
        }else{
            if(props.perPrefix == 'transferCustom') {
                router.pushTarget('/customer/customerDetail?id=' + id + '&scopeMenuId=' + router.currentRoute.value?.meta?.menuId)
            }else {
                router.pushTarget('/clue/detail?id=' + id + '&scopeMenuId=' + router.currentRoute.value?.meta?.menuId)
            }
        }
        
    }
</script>
