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

		<Table
            ref="publicTable"
            :tableParams="tableParams"
            :btnRole="btnRole"
            @handleAdd="handleAdd('add')"
            @handleEdit="handleAdd('edit', $event)"
            @selectionChange="handleSelectionChange"
        >
            <template #left>
                <el-button
                    v-for="item in leftBtn"
                    :key="item.value"
                    @click="openDialog(item.value)"
                    v-hasPermi="[item.hasPermi]"
                >
                    {{ item.label }}
                </el-button>
            </template>
        </Table>
	</el-card>

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

<script setup name="clue_public" lang="ts">
import { listCustomer, delCustomer, receiveClue, distributionClue } from '@/api/customer';
import { CustomerVO, CustomerQuery } from '@/api/customer/types';
import Table from '@/components/Table/index.vue'
import { tableTypes } from '@/components/Table/types'
import { getRuleConfig } from '@/api/system/ruleConfig';
import HeaderSearch from '../components/search.vue'
import ConvertCustomer from '@/components/common/convertCustomer.vue'
import Distribution from '@/components/common/distribution.vue'
import AddFollow from '@/components/Follow/add.vue'
import auth from '@/plugins/auth';

const router = useRouter();
const btnRole = ref([
    { type: 'add', hasPermi: `clue:public:add` },
    { type: 'edit', hasPermi: `clue:public:edit` },
    { type: 'remove', hasPermi: `clue:public:remove` },
    { type: 'import', hasPermi: `clue:public:import` },
    { type: 'export', hasPermi: `clue:public:export` }
]);

const queryFormRef = ref<ElFormInstance>();

const tableParams = reactive<tableTypes<CustomerQuery, CustomerVO>>({
    cloumnCode: 'public',
    menuId: router.currentRoute.value?.meta?.menuId,
	tableColumn: [
		{ show: true, label: '线索名称', prop: 'customerName', sortable: true, render: ({ column }: { column: CustomerVO }) => {
            return h('span', { class: 'link', onClick: () => { getDetail(column.id) } }, column.customerName)
        }},
        { show: true, label: '联系人姓名', prop: 'liaison.name', sortable: false },
        { show: true, label: '邮箱', prop: 'liaison.email', sortable: false },
        { show: true, label: '前归属人', prop: 'formerOwnerByName', sortable: false },
        { show: true, label: '最后跟进', prop: 'lastFollowUpTime', sortable: true },
        { show: true, label: '未跟进天数', prop: 'noFollowUpDate', sortable: true },
        { show: true, label: '创建时间', prop: 'createTime', sortable: true },
        { show: true, label: '置公原因', prop: 'reasonPublicCustomerName', sortable: false },
        { 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: 'customerSourceDictValue', sortable: false },
        { show: false, label: '线索状态', prop: 'clueStatusName', sortable: false },
        { show: false, 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:public:gj`) ?
                    h(ElButton, { link: true, type: 'primary', onClick: () => { openDialog('follow', column) } }, '跟进') : ''
                let toppingBtn = auth.hasPermi(`clue:public:zd`) ?
                    h(ElButton, { link: true, type: 'primary' }, '置顶'): ''
                return [
                    followBtn,
                    // toppingBtn
                ]
            }
        }
	],
	queryParams: {
		blurry: '',
        hasPublicCustomer: 1,
        customerForm: 11,
        formerOwnerByList:null,
	},
	listFn: listCustomer,
	delFn: delCustomer,
	keyId: 'id',
    importCode: 'IMPORT_CLUE_EXCEL',
    importType: '2',
    exportCode: 'EXPORT_CLUE_EXCEL',
    commonQueryOrderBy: 'lastFollowUpTime',
    sortMethod: 'asc'
})

let leftBtn = [
    { label: '转为客户', value: 'convert', hasPermi: `clue:public:zwkh` },
    { label: '领取线索', value: 'receive', hasPermi: `clue:public:lqxs` },
    { label: '分配线索', value: 'distribution', hasPermi: `clue:public:fpxs` },
    { label: '发邮件', value: 'email', hasPermi: `clue:public:fyj` }
]

const { queryParams } = toRefs(tableParams);

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

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

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

/** 新增按钮操作 */
const handleAdd = (type: string, data?: CustomerVO) => {
	router.push('./add?hasPublicCustomer=1&type=' + type + "&id=" + data?.id)
}

const getDetail = (id) => {
    router.pushTarget('/clue/detail?hasPublicCustomer=1&id=' + id + '&scopeMenuId=' + router.currentRoute.value?.meta?.menuId)
}

const ruleData = ref()
const getRuleData = () => {
    getRuleConfig({ resourceType: 11 }).then(res => {
        ruleData.value = res.result
    })
}

// 左侧按钮弹窗
const dialogComponent = shallowRef()
const dialogRef = ref()
const setItemRef = (el: any) => {
    if (el) {
        dialogRef.value = el
    }
}
const openDialog = (val: string, data?: CustomerVO) => {
    if(val != 'follow' && 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 = {}
    switch(val) {
        case 'convert': // 转为客户
            dialogComponent.value = ConvertCustomer
            query = { obj: ids.value[0] }
            break;
        case 'receive': // 领取线索
            let ruleText = ruleData.value.hasPublicClues ?
            h('p', null, `领取${ ruleData.value.maxPublicCluesNum }天后未跟进，线索将自动转为公共线索`) : ''
			ElMessageBox({
				title: '确认提示',
				type: 'warning',
                confirmButtonText: '提交',
				customClass: 'receive-msg',
				showCancelButton: true,
				message: h('div', null, [
					h('p', { class: 'content bold' }, '是否确认领取所选择的线索？'),
					ruleText
				])
			}).then(() => {
                let idList = ids.value.map(item => item.id)
                receiveClue({ idList }).then(res => {
                    if(res.success) {
                        ElMessage.success("领取线索成功");
                        handleQuery()
                    }
                })
            })
            break;
        case 'distribution': // 分配线索
            dialogComponent.value = Distribution
            query = {
                typeName: '线索',
                handleFn: distributionClue,
                query: { idList: ids.value.map(item => item.id) }
            }
            break;
        case 'follow': // 跟进
            dialogComponent.value = AddFollow
            query = {
                resourceType: '11',
                resourceTypeId: data?.id,
                resourceName: data?.customerName,
                resourceStageName: data?.clueStatusName,
                resourceStageDictValue: data?.clueStatusDictValue
            }
            break;
    }
    if(val != 'receive') {
        nextTick(() => {
            dialogRef.value.open(query)
        })
    }

}

onMounted(() => {
    getRuleData()
})
</script>

<style lang="scss">
	.receive-msg{
		.el-message-box__status{
			top: 25%;
		}
		.content{
			font-size: 16px;
			color: #333;
		}
	}
</style>
