<template>
	<div class="snapshot-invite-code-list-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<vxe-grid v-bind="gridOptions" ref="gridRef" @checkbox-all="selectAllChangeEvent" @checkbox-change="selectChangeEvent">
				<template #toolbar_buttons>
					<el-button type="primary" @click="onAdd" v-auth="'snapshot:inviteCode:list:add'">
						<SvgIcon name="ele-Plus" class="mr5" />新增邀请码
					</el-button>
					<el-button type="danger" @click="onDelete" v-auth="'snapshot:inviteCode:list:delete'" :disabled="isChecked" :loading="state.loading">
						<SvgIcon name="ele-Delete" class="mr5" />删除<span v-if="checkTable.length">({{ checkTable.length }})</span>
					</el-button>
					<el-button type="primary" @click="onExport" v-auth="'snapshot:inviteCode:list:export'">
						<SvgIcon name="iconfont icon-daochu" class="mr5" />导出邀请码
					</el-button>
					<el-button type="primary" @click="onCreate" v-auth="'snapshot:inviteCode:list:create'">
						<SvgIcon name="iconfont icon-daochu" class="mr5" />批量生成
					</el-button>
				</template>
				<template #qrCodeUrl="{ row }">
					<el-image style="width: 50px" :src="prefix + row.qrCodeUrl" :preview-src-list="[prefix + row.qrCodeUrl]" fit="cover" />
				</template>
				<template #action="{ row }">
					<el-button link type="primary" @click="onEdit(row)" v-auth="'snapshot:inviteCode:list:edit'" title="编辑"> 编辑 </el-button>
					<el-button link type="primary" @click="download(row)" v-auth="'snapshot:inviteCode:list:download'" title="编辑人员"> 下载 </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>
		<!--  新增 -->
		<code-add ref="codeAddRef" @updateList="queryList" />
		<!--  编辑  -->
		<code-edit ref="codeEditRef" @updateList="queryList" />
		<!--  导出邀请码  -->
		<export-code ref="exportCodeRef" />
	</div>
</template>

<script lang="tsx" setup name="snapshotInviteCodeList">
import { computed, defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { deleteInviteCode, getInviteCodeList } from '@/api/snapshot/inviteCode';
import { fileDownloadByUrl } from '@/api/public/file';

// 引入组件
const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页
const CodeAdd = defineAsyncComponent(() => import('@/views/snapshot/inviteCode/list/components/Code-add.vue')); //  新增
const CodeEdit = defineAsyncComponent(() => import('@/views/snapshot/inviteCode/list/components/Code-edit.vue')); // 编辑
const ExportCode = defineAsyncComponent(() => import('@/views/snapshot/inviteCode/list/components/Export-code.vue'));

// 定义变量内容
const state = reactive<any>({
	loading: false,
	queryParams: {
		// 查询参数
		PageIndex: 1,
		PageSize: 20,
		CaseName: null, // 线索名称
		IndustryName: null, // 行业类型
	},
	total: 0, // 总条数
});

const gridOptions = reactive<any>({
	loading: false,
	border: true,
	showOverflow: true,
	columnConfig: {
		resizable: true,
	},
	scrollY: {
		enabled: true,
		gt: 100,
	},
	toolbarConfig: {
		zoom: true,
		custom: true,
		refresh: {
			queryMethod: () => {
				handleQuery();
			},
		},
		slots: {
			buttons: 'toolbar_buttons',
		},
	},
	customConfig: {
		storage: true,
	},
	id: 'snapshotInviteCodeList',
	rowConfig: { isHover: true, height: 50, isCurrent: true, useKey: true },
	height: 'auto',
	columns: [
		{ type: 'checkbox', width: 50, align: 'center' },
		{
			field: 'orgName',
			title: '部门名称',
			minWidth: 200,
		},
		{
			field: 'beginCode',
			title: '邀请码',
		},
		{
			field: 'endCode',
			title: '邀请码2',
		},
		{
			field: 'qrCodeUrl',
			title: '邀请码地址',
			slots: { default: 'qrCodeUrl' },
		},
		{ title: '操作', width: 120, fixed: 'right', align: 'center', slots: { default: 'action' } },
	],
	data: [],
});
// 文件前缀
const prefix = import.meta.env.VITE_API_UPLOAD_URL;
/** 搜索按钮操作 节流操作 */
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
// 获取参数列表
const queryList = () => {
	state.loading = true;
	gridOptions.loading = true;
	getInviteCodeList(state.queryParams)
		.then((res) => {
			state.loading = false;
			gridOptions.data = res.result.items ?? [];
			state.total = res.result.total ?? 0;
			gridOptions.loading = false;
		})
		.finally(() => {
			state.loading = false;
			gridOptions.loading = false;
		});
};
// 新增
const codeAddRef = ref<RefType>();
const onAdd = () => {
	codeAddRef.value.openDialog();
};
// 编辑
const codeEditRef = ref<RefType>();
const onEdit = (row: any) => {
	codeEditRef.value.openDialog(row.id);
};
// 下载
const download = (row: any) => {
	ElMessageBox.confirm(`您确定要下载邀请码，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			fileDownloadByUrl({
				Source: 'hotline',
				Id: row.additions,
			}).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.creatorOrgName + '_' + row.beginCode; // 下载文件名
				document.body.appendChild(down);
				down.click(); // 模拟点击A标签
				document.body.removeChild(down); // 下载完成移除元素
				window.URL.revokeObjectURL(href); // 释放blob对象
			});
		})
		.catch(() => {});
};
const checkTable = ref<EmptyArrayType>([]);
const gridRef = ref<RefType>();
const selectAllChangeEvent = ({ checked }) => {
	if (gridRef.value) {
		const records = gridRef.value.getCheckboxRecords();
		checkTable.value = records;
		console.log(checked ? '所有勾选事件' : '所有取消事件', records);
	}
};

const selectChangeEvent = ({ checked }) => {
	if (gridRef.value) {
		const records = gridRef.value.getCheckboxRecords();
		checkTable.value = records;
		console.log(checked ? '勾选事件' : '取消事件', records);
	}
};
const isChecked = computed(() => {
	return !Boolean(checkTable.value.length);
});
// 删除
const onDelete = () => {
	const ids = checkTable.value.map((item) => item.id);
	ElMessageBox.confirm(`您确定要批量生成邀请码，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			deleteInviteCode(ids)
				.then(() => {
					handleQuery();
					ElMessage.success('删除成功');
				})
				.catch(() => {});
		})
		.catch(() => {});
};
// 导出邀请码
const exportCodeRef = ref<RefType>();
const onExport = () => {
	exportCodeRef.value.openDialog();
};
// 批量生成
const onCreate = () => {
	ElMessageBox.confirm(`您确定要批量生成邀请码，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			queryList();
		})
		.catch(() => {});
};
// 页面加载时
onMounted(() => {
	queryList();
});
</script>
