<template>
	<el-dialog :model-value="props.showes" @close="closeFun" width="70%">
		<div ref="ceshiRef">
			<ceshi id="ceshi" :data="props.listData"></ceshi>
		</div>
		<div class="btnList">
			<el-button type="primary" @click="printElement">打印</el-button>
		</div>
	</el-dialog>
</template>
<script setup lang="ts">
import { defineProps, reactive, ref, nextTick, defineEmits } from 'vue';
import ceshi from './ceshi.vue';
import printJS from 'print-js';
import html2canvas from 'html2canvas';

const ceshiRef = ref();
const emits = defineEmits(['close']);
const props = defineProps({
	listData: {
		type: Array,
		default: () => [],
	},
	showes: {
		type: Boolean,
		default: true,
	},
});
const state = reactive({
	snapshotUrl: '',
});
const closeFun = () => {
	emits('close');
};
const printElement = () => {
	captureSnapshot();
	// 获取 DOM 元素的 HTML
	nextTick(() => {
		printJS({
			printable: state.snapshotUrl,
			type: 'image',
			style: `
        @page {
          size: auto;
          margin: 0mm;
        }
        body {
          margin: 0;
          padding: 36px;
        }
      `,
		});
	});
};
// 截图函数
const captureSnapshot = async () => {
	// 使用 html2canvas 将 div 渲染为 Canvas
	const canvas = await html2canvas(ceshiRef.value, {
		allowTaint: true, // 允许跨域图片
		useCORS: true, // 使用 CORS 加载图片
		scale: 2, // 提高截图分辨率
		width: ceshiRef.value.clientWidth,
		height: ceshiRef.value.clientHeight,
	});
	state.snapshotUrl = canvas.toDataURL('image/png');
};
</script>
<style scoped lang="scss">
.btnList {
	margin-top: 26px;
	display: flex;
	justify-content: center;
}
</style>
