<template>
	<div class="tels-smart-record-container layout-pd">
		<!--		<el-card shadow="never">
			<el-form :model="state.queryParams" ref="ruleFormRef" @submit.native.prevent label-width="20px">
				<el-row :gutter="10">
					<el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
						<el-form-item prop="callNumber">
							<el-input v-model="state.queryParams.callNumber" placeholder="主叫号码" clearable @keyup.enter="handleQuery" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
						<el-form-item prop="callTime">
							<el-date-picker
								v-model="state.queryParams.callTime"
								type="datetimerange"
								unlink-panels
								range-separator="至"
								start-placeholder="智能应答进入开始时间"
								end-placeholder="智能应答进入结束时间"
								:shortcuts="shortcuts"
								@change="timeStartChangeCall"
								value-format="YYYY/MM/DD HH:mm:ss"
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
						<el-form-item>
							<el-button type="primary" @click="handleQuery" :loading="state.loading" v-waves>
								<SvgIcon name="ele-Search" class="mr5" />查询
							</el-button>
							<el-button @click="resetQuery(ruleFormRef)" v-waves class="default-button" :loading="state.loading">
								<SvgIcon name="ele-Refresh" class="mr5" />重置
							</el-button>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</el-card>
		&lt;!&ndash; 播放录音 &ndash;&gt;-->
		<el-card shadow="never">
			<el-form :model="state.testForm" @submit.native.prevent>
				<el-row :gutter="10">
					<el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
						<el-form-item prop="serIp" label="服务器ip：">
							<el-input v-model="state.testForm.serIp" placeholder="例如：114.114.114.114" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
						<el-form-item prop="serPort" label="服务器端口：">
							<el-input v-model="state.testForm.serPort" placeholder="例如：29003" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
						<el-form-item prop="queue" label="队列：">
							<el-input v-model="state.testForm.queue" placeholder="例如：10010" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
						<el-form-item prop="callNumber" label="分机：">
							<el-input v-model="state.testForm.agent" placeholder="例如：1001" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
						<el-form-item prop="agentPwd" label="分机密码：">
							<el-input v-model="state.testForm.agentPwd" placeholder="例如：!@#123Qw" clearable />
						</el-form-item>
					</el-col>
					<el-divider>
						<span class="ss_title">连接状态：{{ wsStatus }}</span>

						<el-button @click="websocket_connect" type="primary" class="ml10" v-if="showConnect">连接</el-button>
					</el-divider>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<div class="mb10">签入状态：{{ olaStatus }}</div>
						<el-button @click="login" type="primary">签入</el-button>
						<el-button @click="logout" type="primary">签出</el-button>
						<el-button @click="ready" type="primary">示闲</el-button>
						<el-button @click="unReady" type="primary">示忙</el-button>
						<el-button @click="hold" type="primary">保持</el-button>
						<el-button @click="unHold" type="primary">取消保持</el-button>
						<el-button @click="hangup" type="primary">挂机</el-button>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="JSON数据">
							{{ jsonData }}
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<VTreeSearch
				selectable
				:load="remoteLoad"
				titleField="hotSpotFullName"
				keyField="id"
				searchRemote
				@search="handleSearch"
				ref="treeRef"
				isLeaf="hasChild"
				:datafields="{
						label: 'hotSpotFullName',
						children: 'children',
						isLeaf: 'hasChild',
				}"
				:expandedKeys="expandedKeys"
				@select="nodeClick"
			>
			</VTreeSearch>
		</el-card>
	</div>
</template>

<script lang="tsx" setup name="telsSmartRecord">
import { onMounted, reactive, ref } from 'vue';
import type { FormInstance } from 'element-plus';
import { ElMessage } from 'element-plus';
import { formatDate } from '@/utils/formatTime';
import { olaFn } from '@/utils/olaFn';
import { VTreeSearch } from '@wsfe/vue-tree';
import { hotSpotSearch, hotSpotType } from '@/api/business/order';
import { removeDuplicate } from '@/utils/arrayOperation';

// 表格配置项
const columns = ref<any[]>([
	{ prop: 'callNumber', label: '主叫号码' },
	{
		prop: 'questionTime',
		label: '智能应答进入时间',
		width: 170,
		render: (scope) => <span>{formatDate(scope.row.questionTime, 'YYYY-mm-dd HH:MM:SS')}</span>,
	},
	{ prop: 'operation', label: '操作', fixed: 'right', width: 160, align: 'center' },
]);
// 定义变量内容
const state = reactive({
	queryParams: {
		pageno: 1, // 当前页
		pagesize: 10, // 每页条数
		callNumber: null, // 主叫号码
		callTime: [],
		startTime: null,
		endTime: null,
	},
	tableData: [], // 列表数据
	loading: false, // 加载
	total: 0, // 总条数
	callDirection: [],
	onState: [],
	endByOptions: [],
	testForm: {
		serIp: '222.213.23.229',
		serPort: '29003',
		queue: '10010',
		agent: '1100',
		agentPwd: '!@#123Qw',
	},
});
const ruleFormRef = ref<FormInstance>(); // 表单ref
const searchCol = ref(true); // 展开/收起
// 展开/收起
const closeSearch = () => {
	searchCol.value = !searchCol.value;
};
const handleTimeChange = (val: string[], startKey: string, endKey: string) => {
	if (val) {
		state.queryParams[startKey] = val[0];
		state.queryParams[endKey] = val[1];
	} else {
		state.queryParams[startKey] = '';
		state.queryParams[endKey] = '';
	}
	handleQuery();
};
// 时间段
const timeStartChangeCall = (val: string[]) => {
	handleTimeChange(val, 'startTime', 'endTime');
};
// 手动查询，将页码设置为1
const handleQuery = () => {
	state.queryParams.pageno = 1;
	queryList();
};
/** 通话记录列表 */
const queryList = async () => {
	state.loading = true;
	try {
	} catch (e) {
		state.loading = false;
		console.log(e);
	}
};
/** 重置按钮操作 */
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	state.queryParams.startTime = null;
	state.queryParams.endTime = null;
	queryList();
};
// 播放录音
const toolbarRef = ref<RefType>();
const tableRef = ref<RefType>();
onMounted(() => {
	// queryList();
	const $table = tableRef.value;
	const $toolbar = toolbarRef.value;
	if ($table && $toolbar) {
		$table.connect($toolbar);
	}
});
const wsStatus = ref('Disconnected');
const jsonData = ref('');
const showConnect = ref(true);

// 链接呼叫中心
const olaRef = ref();
const websocket_connect = () => {
	const websocket_url = 'ws://' + state.testForm.serIp + ':' + state.testForm.serPort + '/ola_socket';
	olaRef.value = olaFn(websocket_url, {
		username: state.testForm.agent,
		password: state.testForm.agentPwd,
		onConnected: onConnected, // 连接成功
		onDisconnected: onDisconnected, // 断开链接
		onMessage: onMessage, // 接收消息
		heartbeat: {
			message: JSON.stringify({ cmd: 'ping' }),
			interval: 5000,
			// pongTimeout: 1000,
		},
	});
};
const onConnected = () => {
	showConnect.value = false;
	wsStatus.value = 'Connected';
	//连接之后，先登出一次,防止其他地方已经登陆
	olaRef.value.logout();
};
const onDisconnected = () => {
	console.log('websocket closed!');
	ElMessage.warning('链接断开');
	wsStatus.value = 'Disconnected';
	showConnect.value = true;
};
const login = () => {
	let array_ola_queue: EmptyArrayType = []; // 队列
	if (state.testForm.queue != '') {
		const array = state.testForm.queue.split(',');
		for (let i = 0; i < array.length; i++) {
			array_ola_queue[i] = array[i];
		}
		olaRef.value.login(array_ola_queue, state.testForm.agent, { type: 'onhook' });
	}
};
const logout = () => {
	olaRef.value.logout();
	olaRef.value.close();
	olaStatus.value = '未签入';
};
const olaStatus = ref('');
const onMessage = (evt: any) => {
	const data = JSON.parse(evt);
	if (data.event_type === 'agent_state') {
		jsonData.value = evt;
		if (data.state == 'login') {
			olaStatus.value = '已签入';
		} else if (data.state == 'logout') {
			olaStatus.value = '未签入';
		} else if (data.state == 'ready') {
			olaStatus.value = '示闲中';
		} else if (data.state == 'unready') {
			olaStatus.value = '示忙中';
		} else if (data.state == 'acw') {
			olaStatus.value = '话后整理中';
		} else if (data.state == 'busy') {
			olaStatus.value = '通话中';
		} else {
			olaStatus.value = data.state;
		}

		if (data.state == 'busy') {
			if (data.call_direction == 'outbound') {
				if (data.private_data == 'calling') {
					olaStatus.value = '拨号中';
				} else if (data.private_data == 'answered') {
					if (data.other_answered == false) {
						olaStatus.value = '振铃中';
					} else if (data.other_answered == true) {
						olaStatus.value = '通话中';
					}
				}
			} else {
				if (data.private_data == 'ring') {
					olaStatus.value = '振铃中';
				} else if (data.private_data == 'answered') {
					olaStatus.value = '通话中';
				}
			}
		} else if (data.old_state == 'busy') {
			//挂机后系统可以返回两种状态:acw 话后整理状态 ready 示闲状态，如果不需要acw，可以联系我们后台修改配置，如果需要保留，如果需要再次
			//拨打电话的话，需要手动点击示闲按钮
			alert('已挂机');
			olaStatus.value = '已挂机';
		}
	} else if (data.event_type == 'agent_caller_state') {
	} else if (data.event_type == 'command/reply') {
	}
};
const ready = () => {
	olaRef.value.go_ready();
};
const unReady = () => {
	olaRef.value.go_break('');
};
const hold = () => {
	olaRef.value.hold();
};
const unHold = () => {
	olaRef.value.unhold();
};
const hangup = () => {
	olaRef.value.hangup();
};

const searchKeyword = ref('');

const handleSearch = (keyword: string) => {
	searchKeyword.value = keyword;
};
//
const treeRef = ref();
const expandedKeys = ref<EmptyArrayType>([]);
const nodeClick = async (node: any) => {
	console.log(node)
	expandedKeys.value = [];
	console.log(node.id)
	expandedKeys.value = getParentId(node, expandedKeys.value);
	console.log(expandedKeys.value,'1111')
	if (node.isLeaf) {

	}
};
// 递归查找父级Id
const getParentId = (val: any, arr: string[]) => {
	if (val.parentId) {
		arr.push(val.parentId);
		getParentId(val._parent, arr);
	}
	return removeDuplicate(arr);
};
const remoteLoad = async (node: any, resolve: any) => {
	console.log(node, '11');
	try {
		if (searchKeyword.value) {
			const { result } = await hotSpotSearch(searchKeyword.value);
			resolve(result);
			setTimeout(() => {
				treeRef.value.setExpandAll(true);
			}, 300);
		} else {
			const { result } = await hotSpotType({ id: node?.id ? node?.id : null });
			resolve(result);
			console.log(expandedKeys.value,'2222')
		}
	} catch (e) {
		console.log(e);
	}
};
</script>
