<template>
	<div class="tels-record-upload-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<vxe-grid v-bind="gridOptions" v-on="gridEvents" ref="gridRef">
				<template #form>
					<el-form :model="state.queryParams" ref="ruleFormRef" @submit.native.prevent inline>
						<el-form-item label="录音名称" prop="Keyword">
							<el-input v-model="state.queryParams.Keyword" placeholder="录音名称" clearable @keyup.enter="handleQuery" class="keyword-input" />
						</el-form-item>
						<el-form-item prop="crTime" label="上传时间">
							<el-date-picker
								v-model="state.queryParams.crTime"
								type="datetimerange"
								unlink-panels
								range-separator="至"
								start-placeholder="开始时间"
								end-placeholder="结束时间"
								:shortcuts="shortcuts"
								@change="handleQuery"
								value-format="YYYY-MM-DD[T]HH:mm:ss"
								:default-time="defaultTimeStartEnd"
								:clearable="false"
							/>
						</el-form-item>
						<el-form-item>
							<el-button type="primary" @click="handleQuery" :loading="state.loading"> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
							<el-button @click="resetQuery(ruleFormRef)" class="default-button" :loading="state.loading">
								<SvgIcon name="ele-Refresh" class="mr5" />重置
							</el-button>
						</el-form-item>
					</el-form>
				</template>
				<template #toolbar_buttons>
					<el-button type="primary" @click="onUpload" v-auth="'tels:recordUpload:add'" :loading="state.loading">
						<SvgIcon name="ele-Upload" class="mr5" />上传录音
					</el-button>
				</template>
				<template #action="{ row }">
					<el-button link type="primary" @click="onPlay(row)" v-auth="'tels:recordUpload:play'"> 播放 </el-button>
					<el-button link type="primary" @click="onDownload(row)" v-auth="'tels:recordUpload:download'"> 下载 </el-button>
					<el-button link type="danger" @click="onDelete(row)" v-auth="'tels:recordUpload:delete'"> 删除 </el-button>
				</template>
				<template #pager>
					<pagination
						@pagination="queryList"
						:total="state.total"
						v-model:current-page="state.queryParams.PageIndex"
						v-model:page-size="state.queryParams.PageSize"
						:disabled="state.loading"
					/>
				</template>
			</vxe-grid>
		</div>
		<el-dialog v-model="state.dialogVisible" width="500px" draggable title="关联工单" append-to-body destroy-on-close>
			<vxe-table
				border
				:loading="state.loading"
				:data="state.tableData"
				:column-config="{ resizable: true }"
				:row-config="{ isCurrent: true, isHover: true, height: 30, useKey: true }"
				ref="tableRef"
				max-height="500px"
				show-overflow
				:scrollY="{ enabled: true, gt: 100 }"
				showHeaderOverflow
			>
				<vxe-column field="no" title="工单编码" width="140"></vxe-column>
				<vxe-column field="title" title="工单标题">
					<template #default="{ row }">
						<order-detail :order="row" @updateList="queryList">{{ row.title }}</order-detail>
					</template>
				</vxe-column>
			</vxe-table> </el-dialog
		>‘
		<!--	录音上传	-->
		<RecordUpload ref="uploadRef" @updateList="queryList" />
		<!-- 播放录音 -->
		<play-record ref="playRecordRef" />
	</div>
</template>
<script setup lang="tsx" name="telsRecordUpload">
import { defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { defaultDate, defaultTimeStartEnd, shortcuts } from '@/utils/constants';
import Other from '@/utils/other';
import { uploadRecordDelete, uploadRecordExport, uploadRecordList } from '@/api/tels/uploadRecord';
import { fileDownloadByUrl } from '@/api/public/file';

const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页
const OrderDetail = defineAsyncComponent(() => import('@/components/OrderDetail/index.vue')); // 工单详情
const RecordUpload = defineAsyncComponent(() => import('@/views/tels/recordUpload/components/Upload.vue')); // 录音上传
const PlayRecord = defineAsyncComponent(() => import('@/components/PlayRecord/index.vue')); // 播放录音
// 定义变量内容
const state = reactive<any>({
	queryParams: {
		// 查询条件
		PageIndex: 1,
		PageSize: 20,
		Keyword: null, // 关键词
		crTime: defaultDate, // 时间默认今天开始到今天结束
		SortField: null,
		SortRule: 0,
	},
	tableData: [], //表单
	loading: false, // 加载
	total: 0, // 总数
});

const requestParams = ref<EmptyObjectType>({});
const gridOptions = reactive<any>({
	loading: false,
	border: true,
	showOverflow: true,
	columnConfig: {
		resizable: true,
	},
	scrollY: {
		enabled: true,
		gt: 100,
	},
	sortConfig: {
		remote: true,
	},
	toolbarConfig: {
		zoom: true,
		custom: true,
		refresh: {
			queryMethod: () => {
				handleQuery();
			},
		},
		tools: [{ toolRender: { name: 'exportCurrent' } }, { toolRender: { name: 'exportAll' } }],
		slots: {
			buttons: 'toolbar_buttons',
		},
	},
	customConfig: {
		storage: true,
	},
	id: 'statisticsKnowledgeQuote',
	rowConfig: { isHover: true, height: 30, isCurrent: true, useKey: true },
	height: 'auto',
	columns: [
		{
			field: 'fileName',
			title: '录音名称',
		},
		{
			field: 'creationTime',
			title: '上传时间',
			sortable: true,
			formatter: 'formatDate',
		},

		{ title: '操作', width: 180, fixed: 'right', align: 'center', slots: { default: 'action' } },
	],
	data: [],
	params: {
		exportMethod: uploadRecordExport,
		exportParams: requestParams,
	},
});
const gridEvents = {
	sortChange(val: any) {
		state.queryParams.SortField = val.order ? val.field : null;
		// 0 升序 1 降序
		state.queryParams.SortRule = val.order ? (val.order == 'desc' ? 1 : 0) : null;
		handleQuery();
	},
};
/** 搜索按钮操作 */
const ruleFormRef = ref<RefType>(); // 表单ref
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
/** 获取列表 */
const queryList = () => {
	state.loading = true;
	gridOptions.loading = true;
	requestParams.value = Other.deepClone(state.queryParams);
	requestParams.value.StartTime = state.queryParams.crTime === null ? null : state.queryParams.crTime[0];
	requestParams.value.EndTime = state.queryParams.crTime === null ? null : state.queryParams.crTime[1];
	Reflect.deleteProperty(requestParams.value, 'crTime');
	uploadRecordList(requestParams.value)
		.then((res: any) => {
			state.tableData = res.result?.items ?? [];
			gridOptions.data = res.result?.items ?? [];
			state.total = res.result?.total ?? 0;
			state.loading = false;
			gridOptions.loading = false;
		})
		.catch(() => {
			state.loading = false;
			gridOptions.loading = false;
		});
};
/** 重置按钮操作 */
const statisticalTimeRef = ref<RefType>();
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	statisticalTimeRef.value.reset();
	queryList();
};
// 上传录音
const uploadRef = ref<RefType>();
const onUpload = () => {
	uploadRef.value.openDialog();
};
// 播放
const onPlay = (row: any) => {
	window.open(row.allPath)
};
// 下载
const onDownload = (row: any) => {
	ElMessageBox.confirm(`确定要下载 ${row.name} 吗？`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
	})
		.then(() => {
			fileDownloadByUrl({
				Source: 'hotline',
				Id: row.fileId,
			}).then((res: any) => {
				let blob: Blob = new Blob([res.data], { type: res.data.type }); // 创建blob 设置blob文件类型 data 设置为后端返回的文件(例如mp3,jpeg) type:这里设置后端返回的类型 为 mp3
				let down: HTMLAnchorElement = document.createElement('a'); // 创建A标签
				let href: string = window.URL.createObjectURL(blob); // 创建下载的链接
				down.href = href; // 下载地址
				down.download = row.fileName; // 下载文件名
				document.body.appendChild(down);
				down.click(); // 模拟点击A标签
				document.body.removeChild(down); // 下载完成移除元素
				window.URL.revokeObjectURL(href); // 释放blob对象
			});
		})
		.catch(() => {});
};
// 删除
const onDelete = (row: any) => {
	ElMessageBox.confirm(`确定要删除 ${row.name} 吗？`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
	})
		.then(() => {
			uploadRecordDelete({ ids: [row.id] }).then(() => {
				queryList();
				ElMessage.success('删除成功');
			});
		})
		.catch(() => {});
};
onMounted(() => {
	queryList();
});
</script>
