<template>
	<el-card shadow="never" class="list-card">
		<template #header>
			<div class="search table_area">
                <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
                    <el-row :gutter="16">
                        <el-col :span="4">
                            <el-form-item prop="blurry">
                                <el-input
                                    v-model="queryParams.blurry"
                                    placeholder="搜索客户信息"
                                    clearable
                                    prefix-icon="Search"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item prop="liaisonName">
                                <el-input
                                    v-model="queryParams.liaisonName"
                                    placeholder="搜索联系人"
                                    clearable
                                    prefix-icon="Search"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item prop="customerStatusDictValue">
                                <SelectDict v-model="queryParams.customerStatusDictValue" placeholder="客户状态"
                                            dictCode="customer_status"></SelectDict>
                            </el-form-item>
                        </el-col>
						<el-col :span="4">
                            <el-form-item prop="continent">
                                <el-cascader  placeholder="区域名称" :options="region" v-model="regionValue" clearable filterable @change="getRegion"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4" v-if='showAll'>
                            <el-form-item prop="customerTypeDictValue">
                                <SelectDict v-model="queryParams.customerTypeDictValue" placeholder="客户类型"
                                            dictCode="customer_type"></SelectDict>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4" v-if='showAll'>
                            <el-form-item prop="customerLevelDictValue">
                                <SelectDict v-model="queryParams.customerLevelDictValue" placeholder="客户等级"
                                            dictCode="customer_level"></SelectDict>
                            </el-form-item>
                        </el-col>

                        <el-col :span="6" v-if='!showAll'>
                            <el-form-item>
                                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                                <el-button icon="Refresh" @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="ownerByIds">
                                <SelectUser multiple v-model="queryParams.ownerByIds" placeholder="归属人员"></SelectUser>
                            </el-form-item>
                        </el-col> -->
						<el-col :span="4">
                            <el-form-item prop="formerOwnerByList">
                                <SelectUser multiple v-model="queryParams.formerOwnerByList" placeholder="前归属人员"></SelectUser>
                            </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="6">
                            <el-form-item>
                                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                                <el-button icon="Refresh" @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>
		</template>

		<Table
			ref="rubbishCustomerTable"
			:tableParams="tableParams"
			:btnRole="btnRole"
            @handleEdit="handleUpdate"
            @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>
			<template #right>
                <el-checkbox v-model="followStyle" label="跟进模式" @change='setFollow'></el-checkbox>
                <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="选择跟进模式后，列表将展示有最新邮件和待跟进的客户，且客户详情切换至跟进面板状态"
                    placement="top"
                >
                    <el-icon style='margin-right: 10px'><QuestionFilled /></el-icon>
                </el-tooltip>
            </template>
		</Table>
	</el-card>

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

<script setup name="rubbishCustomer" lang="ts">
import { listCustomer, delCustomer, receiveClue } from '@/api/customer';
import { CustomerVO, CustomerQuery } from '@/api/customer/types';
import { getRuleConfig } from '@/api/system/ruleConfig';
import Table from '@/components/Table/index.vue'
import { tableTypes } from '@/components/Table/types'
import TransferClue from '@/components/common/transferClue.vue'
import Merge from '@/components/common/merge.vue'
import BulkEdit from '@/components/common/bulkEdit.vue';
import InSeas from '@/components/common/inSeas.vue';
import AddFollow from '@/components/Follow/add.vue'
import auth from '@/plugins/auth'
import {region} from '@/utils/region';
import {useDictCache} from '@/hooks/web/useDict'
const { queryDictDetailByCodes } = useDictCache(['customer_status', 'customer_type', 'customer_level'])
queryDictDetailByCodes()

const router = useRouter();
const btnRole = ref([
	{ type: 'edit', hasPermi: `customer:rubbishCustomer:edit` },
    { type: 'remove', hasPermi: `customer:rubbishCustomer:remove` },
    { type: 'import', hasPermi: `customer:rubbishCustomer:import` },
    { type: 'export', hasPermi: `customer:rubbishCustomer:export` }
]);
const followStyle = ref(false)
const daterange = ref('')
const getDate = (val: string[] | null) => {
	tableParams.queryParams.lastFollowUpBeginTime = val ? val[0] : ''
	tableParams.queryParams.lastFollowUpEndTime = val ? val[1] : ''
}
const showAll = ref(false)

const queryFormRef = ref<ElFormInstance>();

const tableParams = reactive<tableTypes<CustomerQuery, CustomerVO>>({
	cloumnCode: 'rubbishCustomer',
	menuId: router.currentRoute.value?.meta?.menuId,
	tableColumn: [
		{ show: true, label: '客户名称', prop: 'customerName', sortable: true, disabledMove: true, render: ({column}: { column: CustomerVO }) => {
			return [
				h('div', { class: 'link', onClick: () => {
						if(followStyle.value){
							router.pushTarget('/customer/followPanel?id=' + column.id + '&form=rubbish&resourceType=10')
						}else{
							// router.pushTarget('/customer/customerDetail?id=' + column.id + '&form=rubbish')
							router.pushTarget('/customer/customerDetail?id=' + column.id+'&form=rubbish&scopeMenuId='+router.currentRoute.value?.meta?.menuId+'&resourceType=10&blurry='+tableParams.queryParams.blurry+'&customerForm=10&customerStatusDictValue='+tableParams.queryParams.customerStatusDictValue+'&customerTypeDictValue='+tableParams.queryParams.customerTypeDictValue+'&customerLevelDictValue='+tableParams.queryParams.customerLevelDictValue+'&lastFollowUpTime='+tableParams.queryParams.lastFollowUpTime+'&hasOrderForm='+tableParams.queryParams.hasOrderForm+'&hasPublicCustomer='+tableParams.queryParams.hasPublicCustomer+'&ownerByIds='+tableParams.queryParams.ownerByIds+'&hasFollowMode='+tableParams.queryParams.hasFollowMode+'&customerName='+tableParams.queryParams.customerName+'&liaisonName='+tableParams.queryParams.liaisonName+'&country='+tableParams.queryParams.country+'&preNextScopeMenuId='+router.currentRoute.value?.meta?.menuId)
						}
					}
				}, column.customerName),
			]
		} },
		{ show: true, label: '客户来源', prop: 'customerSourceName', sortable: false },
		{ show: true, label: '客户等级', prop: 'customerLevelName', sortable: false },
		{ show: true, label: '所属大洲', prop: 'continent', sortable: true},
        { show: true, label: '所属国家', prop: 'country', sortable: true},
		{ show: true, label: '放弃日期', prop: 'giveUpTime', sortable: false },
		{ show: true, label: '最后跟进', prop: 'lastFollowUpTime', sortable: true },
		{ show: true, label: '未跟进天数', prop: 'noFollowUpDate', sortable: true },
		{ show: true, label: '前归属人', prop: 'formerOwnerByName', sortable: false },
		{ show: false, label: '企业网址', prop: 'customerCompany.website', sortable: false},
		{ show: false, label: '客户代码', prop: 'dataCode', sortable: true },
		{ show: false, label: '归属人员姓名', prop: 'ownerName', sortable: false },
		{ show: false, label: '意向产品名称', prop: 'intendedProductsNames', sortable: false },
		{ show: false, label: '客户状态', prop: 'customerStatusName', sortable: false },
		{ show: false, label: '客户类型', prop: 'customerTypeName', sortable: false },
		{ show: false, label: '客户信用等级', prop: 'customerCreditLevelName', sortable: false },
		{ show: false, label: '客户经济性质', prop: 'customerEconomicNatureName', sortable: false },
		{ show: false, label: '助记名称', prop: 'mnemonicName', sortable: false },
		{ show: false, label: '备注信息', prop: 'remarks', sortable: false },
		{ show: false, label: '开户行', prop: 'openingBank', sortable: false },
		{ show: false, label: '税号', prop: 'taxNumber', sortable: false },
		{ show: false, label: '银行账号', prop: 'bankAccount', sortable: false },
		{ show: false, label: '创建时间', prop: 'createTime', sortable: true },
		{
            show: true, label: '操作', width: 200, prop: 'operation', disabledMove: true, render: ({ column }: { column: CustomerVO }) => {
				let followBtn = auth.hasPermi('customer:rubbishCustomer:gj') ?
					h(ElButton, { link: true, type: 'primary', onClick: () => { openDialog('follow', column) }}, '跟进') : ''
				let toppingBtn = auth.hasPermi('customer:rubbishCustomer:zd') ?
					h(ElButton, {link: true, type: 'primary'}, () => '置顶'): ''
                return [
					followBtn,
                    // toppingBtn
                ]
            }
        }
	],
	queryParams: {
		blurry: '',
		customerForm: 10,
		hasGarbageCustomer: true,
		customerStatusDictValue: '',
		customerTypeDictValue: '',
		customerLevelDictValue: '',
		lastFollowUpTime: '',
		ownerByIds:[],
		hasFollowMode:false,
		customerName:'',
        liaisonName:'',
		country:'',
		formerOwnerByList:null,
	},
	listFn: listCustomer,
	delFn: delCustomer,
	keyId: 'id',
	importCode: 'IMPORT_CUSTOM_EXCEL',
    exportCode: 'EXPORT_CUSTOM_EXCEL',
	importType: '3',
	commonQueryOrderBy: 'lastFollowUpTime',
	sortMethod: 'asc'
})

let leftBtn = [
    { label: '领取客户', value: 'receive', hasPermi: 'customer:rubbishCustomer:lqkh' },
    { label: '转移客户', value: 'transfer', hasPermi: 'customer:rubbishCustomer:zykh' },
	{ label: '移入公海', value: 'inSeas', hasPermi: 'customer:rubbishCustomer:yrgh' },
    { label: '合并客户', value: 'merge', hasPermi: 'customer:rubbishCustomer:hbkh' },
	{ label: '批量编辑', value: 'batchEdit', hasPermi: 'customer:rubbishCustomer:plbj' },
    { label: '发邮件', value: 'email', hasPermi: 'customer:rubbishCustomer:fyj' }
]

const { queryParams } = toRefs(tableParams);

const regionValue = ref([])
const getRegion = (value) => {
    tableParams.queryParams.country = value?value[1]:''
}

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

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

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

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

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

/** 修改按钮操作 */
const handleUpdate = async (row: CustomerVO) => {
	router.push('../customer/addCustomer?type=edit&id=' + row.id + '&form=rubbish')
}

// 左侧按钮弹窗
const dialogComponent = shallowRef()
const dialogRef = ref()
const setItemRef = (el: any) => {
    if (el) {
        dialogRef.value = el
    }
}
const openDialog = (val: string, column?: CustomerVO) => {
	if(val != 'follow'&&val != 'merge' && ids.value.length == 0) {
        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 '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(() => {
				receiveClue({ idList }).then(res => {
					if(res.success) {
						ElMessage.success('领取成功')
						handleQuery()
					}else{
						ElMessage.error('领取失败')
					}
				})
			}).catch(() => {})
            break;
		case 'transfer': // 转移客户
			dialogComponent.value = TransferClue
			query = {
                resourceType: '10',
                typeName: '客户',
                idList
            }
			break;
		case 'inSeas': // 移入公海
			dialogComponent.value = InSeas
			query = idList
			break;
        case 'merge': // 合并客户
			if(idList.length > 2){
                ElMessage.error('仅可选择两位客户进行合并')
                return false
            }
            dialogComponent.value = Merge
			query = {
				ids: idList,
				querys:tableParams.queryParams,
				selectedData: ids.value
			}
            break;
        case 'batchEdit': // 批量编辑
            dialogComponent.value = BulkEdit
			query = {
				ids: idList
			}
            break;
		case 'follow': // 跟进
            dialogComponent.value = AddFollow
			query = {
				type: 'add',
				customerId: column?.id,
				resourceType: 10,
				resourceTypeId: column?.id,
				resourceName: column?.customerName,
				resourceStageName: column?.customerStatusName,
				resourceStageDictValue: column?.customerStatusDictValue,
				changeType:true,
			}
            break;
    }
	if(val != 'email' && val != 'receive') {
		nextTick(() => {
			dialogRef.value.open(query)
		})
	}
}

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