<script setup lang="ts" name="InspectionRule">
import apis from "@a"
import dayjs from "dayjs"
import CheckinLog from "./_checkinLog.vue"
import { Vue3NextQrcode } from "vue3-next-qrcode"

const deviceUsers = ref([])
const tableRef = ref()
const modalRef = ref()
const opts = reactive({
	columns: [
		{ field: "id", name: "点检规则ID", width: 100, isSort: true, visible: false, tooltip: true },
		{
			field: "taskName",
			name: "任务名称",
			visible: true,
			isSort: false,
			width: "auto",
			tooltip: true
		},
		{ field: "location", name: "地点", visible: true, isSort: false, width: "auto", tooltip: true },
		{
			field: "cycleHours",
			name: "周期（单位：时）",
			visible: true,
			isSort: false,
			width: 140,
			tooltip: true
		},
		{
			field: "toleranceHours",
			name: "误差（单位：时）",
			visible: true,
			isSort: false,
			width: 140,
			tooltip: true
		},
		{ field: "startTime", name: "开始时间", visible: true, isSort: false, width: 185 },
		{ field: "endTime", name: "结束时间", visible: true, isSort: false, width: 185 },
		// {
		// 	field: "requiredCount",
		// 	name: "需点检总次数",
		// 	visible: true,
		// 	isSort: false,
		// 	width: "auto",
		// 	tooltip: true
		// },
		// {
		// 	field: "actualCount",
		// 	name: "实际点检次数",
		// 	visible: true,
		// 	isSort: false,
		// 	width: "auto",
		// 	tooltip: true
		// },
		// {
		// 	field: "missedCount",
		// 	name: "漏检次数",
		// 	visible: true,
		// 	isSort: false,
		// 	width: "auto",
		// 	tooltip: true
		// },
		{
			field: "executorName",
			name: "执行人",
			visible: true,
			isSort: false,
			width: 100,
			tooltip: true
		},
		{ field: "status", name: "启用状态", visible: true, isSort: false, width: 100 },
		{ field: "actions", name: `操作`, width: 150 }
	] as any[],
	queryParams: {
		taskName: undefined,
		location: undefined,
		status: undefined
	},
	searchFormItems: [
		{
			field: "taskName",
			label: "任务名称",
			class: "w-100",
			required: false,
			placeholder: "请输入任务名称",
			component: "I",
			listeners: {
				keyup: (e: KeyboardEvent) => {
					if (e.code == "Enter") {
						handleQuery()
					}
				}
			}
		},
		{
			field: "location",
			label: "地点",
			class: "w-100",
			required: false,
			placeholder: "请输入地点",
			component: "I",
			listeners: {
				keyup: (e: KeyboardEvent) => {
					if (e.code == "Enter") {
						handleQuery()
					}
				}
			}
		},
		{
			field: "status",
			label: "启用状态",
			class: "w-100",
			required: false,
			component: "Dict",
			props: {
				placeholder: "请选择启用状态",
				dictType: "sys_normal_disable",
				valueIsNumber: 1,
				type: "select"
			},
			listeners: {
				change: () => {
					handleQuery()
				}
			}
		}
	] as any,
	permission: "device:inspection",
	handleBtns: [],
	handleFuns: {
		handleCreate,
		handleUpdate: () => {
			const row = tableRef.value.getSelected()
			handleUpdate(row)
		},
		handleDelete: () => {
			const rows = tableRef.value.getSelecteds()
			handleDelete(rows)
		}
	},
	customBtns: [],
	tableListFun: apis.device.inspectionRuleApi.list,
	getEntityFun: apis.device.inspectionRuleApi.get,
	deleteEntityFun: apis.device.inspectionRuleApi.del,
	exportUrl: apis.device.inspectionRuleApi.exportUrl,
	exportName: "InspectionRule",
	modalTitle: "点检规则管理",
	formItems: [
		{
			field: "taskName",
			label: "任务名称",
			class: "w-100",
			required: true,
			placeholder: "请输入任务名称",
			component: "I"
		},
		{
			field: "location",
			label: "地点",
			class: "w-100",
			required: false,
			placeholder: "请输入地点",
			component: "I"
		},
		{
			field: "cycleHours",
			label: "点检周期",
			class: "w-100",
			required: true,
			placeholder: "请输入点检周期",
			component: "I"
		},
		{
			field: "toleranceHours",
			label: "误差",
			class: "w-100",
			required: false,
			placeholder: "请输入误差",
			component: "I"
		},
		{
			field: "startTime",
			label: "开始时间",
			class: "w-100",
			required: false,
			component: "D",
			props: {
				placeholder: "请选择开始时间",
				type: "datetime",
				valueFormat: "YYYY-MM-DD HH:mm:ss"
			}
		},
		{
			field: "endTime",
			label: "结束时间",
			class: "w-100",
			required: false,
			component: "D",
			props: {
				placeholder: "请选择结束时间",
				type: "datetime",
				valueFormat: "YYYY-MM-DD HH:mm:ss"
			}
		},
		{
			field: "executorId",
			label: "执行人",
			class: "w-100",
			required: false,
			placeholder: "请选择执行人",
			component: "VS",
			data: () => {
				return deviceUsers.value.map((v) => {
					return { label: v.nickname + "(" + v.username + ")", value: v.userId }
				})
			},
			props: {
				placeholder: "请选择执行人",
				type: "select",
				valueIsNumber: 1
			}
		}
	] as any,
	resetForm: () => {
		form.value = emptyFormData.value
	},
	labelWidth: "80px",
	emptyFormData: {
		id: undefined,
		taskName: undefined,
		location: undefined,
		cycleHours: undefined,
		toleranceHours: undefined,
		startTime: undefined,
		endTime: undefined,
		executorId: undefined
	}
})
const { queryParams, emptyFormData } = toRefs(opts)
const form = ref<any>(emptyFormData.value)

/** 搜索按钮操作 */
function handleQuery(query?: any) {
	query = query || tableRef.value?.getQueryParams() || queryParams.value
	addDateRange(query, query.dateRangeStartTime, "StartTime")
	addDateRange(query, query.dateRangeEndTime, "EndTime")
	addDateRange(query, query.dateRangeCreateTime)
	addDateRange(query, query.dateRangeUpdateTime, "UpdateTime")
	tableRef.value?.query(query)
}

/** 重置按钮操作 */
function resetQuery(query?: any) {
	query = query || tableRef.value?.getQueryParams() || queryParams.value
	query.dateRangeStartTime = [] as any
	addDateRange(query, query.dateRangeStartTime, "StartTime")
	query.dateRangeEndTime = [] as any
	addDateRange(query, query.dateRangeEndTime, "EndTime")
	query.dateRangeCreateTime = [] as any
	addDateRange(query, query.dateRangeCreateTime)
	query.dateRangeUpdateTime = [] as any
	addDateRange(query, query.dateRangeUpdateTime, "UpdateTime")
	//
}
function handleCreate() {
	tableRef.value.defaultHandleFuns.handleCreate()
}
/** 修改按钮操作 */
function handleUpdate(row: any) {
	tableRef.value.defaultHandleFuns.handleUpdate("", row)
}

/** 删除按钮操作 */
function handleDelete(rows: any[]) {
	tableRef.value.defaultHandleFuns.handleDelete("", rows)
}

/** 提交按钮 */
function submitForm() {
	apis.device.inspectionRuleApi.addOrUpdate(form.value).then(() => {
		handleQuery()
	})
}

const qrModalRef = ref()
const qrModalData = ref()
const qrCode = ref({
	logo: "/media/logo.png",
	size: 300,
	// colorDark: "#0095e8",
	colorDark: "#000000",
	text: ""
})
function handleQrCode(row) {
	qrModalData.value = row
	qrCode.value.text = `vb@device@/checkin/${row.id}`
	qrModalRef.value.show()
}
function handleDownloadQr(id: string) {
	let myImg = document.querySelector("#" + id + " img") as HTMLImageElement
	let url = myImg?.src
	let a = document.createElement("a")
	a.href = url
	a.download = `${qrModalData.value.taskName}签到二维码`
	a.click()
}
// function handlePrintQr(id: string) {
// 	const printContent = document.querySelector("#" + id)
// 	if (!printContent) return

// 	// 创建打印样式
// 	const style = document.createElement("style")
// 	style.innerHTML = `
// 		@media print {
// 			body * {
// 				display: none !important;
//       }
// 			#print-area, #print-area * {
// 				display: block !important;
// 			}
// 			#print-area {
// 				position: absolute;
// 				top: 0;
// 				left: 0;
//         width: 100vw;
//         height: 600px;
// 				display: flex !important;
// 				flex-direction: column;
// 				align-items: center;
// 				justify-content: center;
// 				font-family: Arial, sans-serif;
// 			}

// 		}
// 	`
// 	document.head.appendChild(style)

// 	// 创建打印区域
// 	const printArea = document.createElement("div")
// 	printArea.id = "print-area"
// 	// printArea.innerHTML = `
// 	// 	<div style="width:100%;display:flex;flex-direction: column;align-items: center;justify-content: center;">${printContent.innerHTML}</div>
// 	// `
// 	printArea.innerHTML = printContent.innerHTML
// 	document.body.appendChild(printArea)

// 	// 打印
// 	window.print()

// 	// 清理
// 	setTimeout(() => {
// 		document.head.removeChild(style)
// 		document.body.removeChild(printArea)
// 	}, 500)
// }
const logModalRef = ref()
const logsRef = ref()
function handleLogs(row: any) {
	logsRef.value.load(row.id).then(() => {
		logModalRef.value.show()
	})
}
function init() {
	apis.device.deviceOrderApi.getAssUsers().then((res: any) => {
		deviceUsers.value = res.data
	})
}
onMounted(() => {
	init()
})
</script>
<template>
	<div class="app-container">
		<VbDataTable
			ref="tableRef"
			keyField="id"
			:columns="opts.columns"
			:handle-perm="opts.permission"
			:handle-btns="opts.handleBtns"
			:handle-funs="opts.handleFuns"
			:search-form-items="opts.searchFormItems"
			:custom-btns="opts.customBtns"
			:remote-fun="opts.tableListFun"
			:get-entity-fun="opts.getEntityFun"
			:delete-entity-fun="opts.deleteEntityFun"
			:export-url="opts.exportUrl"
			:export-name="opts.exportName"
			:modal="modalRef"
			:reset-form-fun="opts.resetForm"
			v-model:form-data="form"
			v-model:query-params="queryParams"
			:check-multiple="true"
			:reset-search-form-fun="resetQuery"
			:custom-search-fun="handleQuery">
			<template #startTime="{ row }">
				<template v-if="row.startTime">
					{{ dayjs(row.startTime).format("YYYY-MM-DD HH:mm:ss") }}
				</template>
				<template v-else>-</template>
			</template>
			<template #endTime="{ row }">
				<template v-if="row.startTime">
					{{ dayjs(row.endTime).format("YYYY-MM-DD HH:mm:ss") }}
				</template>
				<template v-else>-</template>
			</template>
			<template #status="{ row }">
				<DictTag type="sys_normal_disable" :value-is-number="1" :value="row.status"></DictTag>
			</template>
			<template #actions="{ row }">
				<vb-tooltip content="生成二维码" placement="top">
					<el-button link type="success" @click="handleQrCode(row)">
						<template #icon>
							<VbIcon icon-name="scan-barcode" icon-type="duotone" class="fs-3"></VbIcon>
						</template>
					</el-button>
				</vb-tooltip>
				<vb-tooltip content="签到日志" placement="top">
					<el-button link type="primary" @click="handleLogs(row)">
						<template #icon>
							<VbIcon icon-name="book" icon-type="duotone" class="fs-3"></VbIcon>
						</template>
					</el-button>
				</vb-tooltip>
				<vb-tooltip content="修改" placement="top">
					<el-button
						link
						type="primary"
						@click="handleUpdate(row)"
						v-hasPermission="'device:inspectionRule:edit'">
						<template #icon>
							<VbIcon icon-name="notepad-edit" icon-type="duotone" class="fs-3"></VbIcon>
						</template>
					</el-button>
				</vb-tooltip>
				<vb-tooltip content="删除" placement="top">
					<el-button
						link
						type="primary"
						@click="handleDelete([row])"
						v-hasPermission="'device:inspectionRule:remove'">
						<template #icon>
							<VbIcon icon-name="trash-square" icon-type="duotone" class="fs-3"></VbIcon>
						</template>
					</el-button>
				</vb-tooltip>
			</template>
		</VbDataTable>
		<VbModal
			v-model:modal="modalRef"
			:title="opts.modalTitle"
			:form-data="form"
			:form-items="opts.formItems"
			:label-width="opts.labelWidth"
			append-to-body
			@confirm="submitForm"></VbModal>
		<VbModal
			v-model:modal="qrModalRef"
			title="签到二维码"
			:confirm-btn="false"
			:close-btn-class="'btn btn-danger'"
			append-to-body>
			<template #body>
				<div
					id="qr"
					class="w-100 w-100 d-flex flex-column justify-content-center align-items-center">
					<span class="fs-5 fw-bold my-5 qr-title">{{ qrModalData?.taskName }} 签到二维码</span>
					<Vue3NextQrcode
						:text="qrCode.text"
						:size="qrCode.size"
						:color-dark="qrCode.colorDark"
						:logo-image="qrCode.logo"
						:logo-scale="0.15"
						:logo-margin="0"
						:logo-corner-radius="20"
						:margin="20" />
				</div>
				<div class="text-center">
					<el-button type="primary" class="mx-5 w-150px" @click="handleDownloadQr('qr')">
						保存
					</el-button>
					<!-- <el-button type="primary" class="mx-5 w-150px" @click="handlePrintQr('qr')">
						打印
					</el-button> -->
				</div>
			</template>
		</VbModal>
		<VbModal
			v-model:modal="logModalRef"
			title="签到记录"
			:confirm-btn="false"
			:close-btn-class="'btn btn-danger'"
			append-to-body>
			<template #body>
				<CheckinLog :is-self="false" ref="logsRef" />
			</template>
		</VbModal>
	</div>
</template>
