<template>
	<a-card :bordered="false" :body-style="{ 'padding-bottom': '0px' }" class="mb-2">
		<a-form ref="searchFormRef" name="advanced_search" :model="searchFormState" class="ant-advanced-search-form">
			<a-row :gutter="24">
				<a-col :span="6">
					<a-form-item label="关键词" name="searchKey">
						<a-input v-model:value="searchFormState.searchKey" placeholder="请输入设备名称或编码" />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="所属区域" name="region">
						<a-input v-model:value="searchFormState.region" placeholder="请输入所属区域" />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-button type="primary" @click="tableRef.refresh(true)">查询</a-button>
					<a-button class="xn-mg08" @click="reset">重置</a-button>
				</a-col>
			</a-row>
		</a-form>
	</a-card>
	<a-card :bordered="false">
		<s-table
			ref="tableRef"
			:columns="columns"
			:data="loadData"
			:alert="options.alert.show"
			:row-key="(record) => record.id"
			:tool-config="toolConfig"
			:row-selection="options.rowSelection"
		>
			<template #operator class="table-operator">
				<a-space>
					<a-button type="primary" @click="formRef.onOpen()">
						<template #icon><plus-outlined /></template>
						新增设备
					</a-button>
					<xn-batch-button
						buttonName="批量删除"
						icon="DeleteOutlined"
						buttonDanger
						:selectedRowKeys="selectedRowKeys"
						@batchCallBack="deleteBatchDevice"
					/>
				</a-space>
			</template>
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'code'">
					<span>{{ record.code }}</span>
				</template>
				<template v-if="column.dataIndex === 'fileId'">
					<a-image v-if="record.fileId && getImageUrl(record.fileId)" :width="50" :src="getImageUrl(record.fileId)" />
					<a-spin v-else-if="record.fileId" size="small" />
					<span v-else>-</span>
				</template>
				<template v-if="column.dataIndex === 'action'">
					<a-space>
						<a @click="formRef.onOpen(record)">编辑</a>
						<a-divider type="vertical" />
						<a-popconfirm title="确定要删除此设备吗？" @confirm="deleteDevice(record)">
							<a-button type="link" danger size="small">删除</a-button>
						</a-popconfirm>
					</a-space>
				</template>
			</template>
		</s-table>
	</a-card>
	<Form ref="formRef" @successful="tableRef.refresh(true)" />
</template>

<script setup name="nlBaseDataDevice">
	import Form from './form.vue'
	import deviceApi from '@/api/baseData/deviceApi'
	import fileApi from '@/api/dev/fileApi'

	const searchFormState = ref({})
	const searchFormRef = ref()
	const tableRef = ref()
	const formRef = ref()
	const toolConfig = { refresh: true, height: true, columnSetting: false, striped: false }

	// 存储图片blob URL的映射
	const imageUrlMap = ref(new Map())

	const columns = [
		{
			title: '设备编码',
			dataIndex: 'code'
		},
		{
			title: '设备名称',
			dataIndex: 'name'
		},
		{
			title: '设备类型',
			dataIndex: 'type'
		},
		{
			title: '描述',
			dataIndex: 'description'
		},
		{
			title: '扩展参数',
			dataIndex: 'editParam'
		},
		{
			title: '图片文件ID',
			dataIndex: 'fileId'
		},
		{
			title: '所属区域',
			dataIndex: 'region'
		},
		{
			title: '设备图片ID',
			dataIndex: 'icon'
		},
		{
			title: 'X坐标',
			dataIndex: 'x'
		},
		{
			title: 'Y坐标',
			dataIndex: 'y'
		},
		{
			title: '角度',
			dataIndex: 'angle'
		},
		{
			title: '放大比例',
			dataIndex: 'size'
		},
		{
			title: '操作',
			dataIndex: 'action',
			align: 'center',
			width: '150px'
		}
	]

	let selectedRowKeys = ref([])

	// 列表选择配置
	const options = {
		alert: {
			show: false,
			clear: () => {
				selectedRowKeys = ref([])
			}
		},
		rowSelection: {
			onChange: (selectedRowKey, selectedRows) => {
				selectedRowKeys.value = selectedRowKey
			}
		}
	}

	// 根据文件ID加载图片
	const loadImageById = (fileId) => {
		if (!fileId || imageUrlMap.value.has(fileId)) {
			return
		}

		const param = {
			storageId: fileId
		}

		fileApi
			.fileDownload(param)
			.then((response) => {
				const blob = response.data
				if (blob && blob instanceof Blob) {
					const url = URL.createObjectURL(blob)
					imageUrlMap.value.set(fileId, url)
				}
			})
			.catch((error) => {
				console.error('图片加载失败:', error)
			})
	}

	// 获取图片URL
	const getImageUrl = (fileId) => {
		return imageUrlMap.value.get(fileId) || ''
	}

	const loadData = (parameter) => {
		return deviceApi.list(Object.assign(parameter, searchFormState.value)).then((res) => {
			console.log('API返回的原始数据:', res)
			// 加载所有图片
			if (res.records && res.records.length > 0) {
				res.records.forEach((item) => {
					if (item.fileId) {
						loadImageById(item.fileId)
					}
				})
			}
			return res
		})
	}

	// 重置
	const reset = () => {
		searchFormRef.value.resetFields()
		tableRef.value.refresh(true)
	}

	// 删除
	const deleteDevice = (record) => {
		deviceApi.delete({ id: record.id }).then(() => {
			tableRef.value.refresh(true)
		})
	}

	// 批量删除
	const deleteBatchDevice = (params) => {
		const ids = params.map((item) => item.id)
		Promise.all(ids.map((id) => deviceApi.delete({ id }))).then(() => {
			tableRef.value.clearRefreshSelected()
		})
	}

	// 组件卸载时清理blob URL
	onUnmounted(() => {
		imageUrlMap.value.forEach((url) => {
			URL.revokeObjectURL(url)
		})
		imageUrlMap.value.clear()
	})
</script>
