<script setup lang="ts" name="Gateway">
import apis from "@a"
import message from "@@/utils/message"
import dayjs from "dayjs"

const emits = defineEmits<{
	(e: "query-meter", v: number): void
	(e: "create-meter", v: number): void
}>()
const groupIdOptions = ref<any[]>([])

const onlineStatusOptions = computed(() => {
	return [
		{ label: "在线", value: 2, type: "success" },
		{ label: "离线", value: 1, type: "danger" }
	]
})
const isAdd = ref(false)
const tableRef = ref()
const modalRef = ref()
const opts = reactive<any>({
	columns: [
		{ field: "id", name: "ID", width: 100, visible: false, isSort: false, tooltip: true },
		{ field: "groupName", name: "设备分组", width: 150, visible: true, tooltip: true },
		{ field: "sn", name: "设备编码(SN)", width: 130, isSort: true, visible: true },
		{ field: "name", name: "设备名称", width: "auto", isSort: true, visible: true, tooltip: true },
		{ field: "type", name: "设备类型", width: 80, isSort: false, visible: true },
		{ field: "cycle", name: "周期", width: 50, isSort: false, visible: true },
		{ field: "status", name: "启用状态", width: 100, isSort: true, visible: true },
		{ field: "onlineStatus", name: "在线状态", width: 100, isSort: true, visible: true },
		// { field: "timeOnline", name: "上线时间", width: 155, isSort: true, visible: true },
		{ field: "timeOffline", name: "离线时间", width: 155, isSort: true, visible: true },
		{ field: "createdAt", name: "创建时间", width: 155, isSort: true, visible: true },
		{ field: "actions", name: `操作`, width: 130 }
	],
	queryParams: {
		groupId: undefined,
		sn: undefined,
		name: undefined,
		status: undefined,
		type: 1
	},
	searchFormItems: [
		{
			field: "groupId",
			label: "分组",
			class: "w-100",
			component: "VS",
			data: () => groupIdOptions.value,
			props: {
				type: "select",
				clearable: true,
				placeholder: "请选择设备分组",
				props: {
					label: "name",
					value: "id"
				}
			}
		},
		{
			field: "sn",
			label: "SN",
			class: "w-100",
			component: "I",
			listeners: {
				keyup: (e: any) => {
					if (e.code == "Enter") {
						handleQuery()
					}
				}
			}
		},
		{
			field: "name",
			label: "名称",
			class: "w-100",
			component: "I",
			listeners: {
				keyup: (e: any) => {
					if (e.code == "Enter") {
						handleQuery()
					}
				}
			}
		},
		{
			field: "status",
			label: "状态",
			class: "w-100",
			component: "dict",
			props: {
				valueIsNumber: true,
				placeholder: "请选择设备状态",
				dictType: "sys_normal_disable"
			}
		}
	] as any,
	permission: "iot:device",
	handleFuns: {
		handleRefresh,
		handleCreate
	},
	customBtns: [],
	tableListFun: apis.iot.deviceApi.listDevice,
	getEntityFun: apis.iot.deviceApi.getDevice,
	deleteEntityFun: apis.iot.deviceApi.delDevice,
	formItems: [
		{
			show: () => !isAdd.value,
			field: "sn",
			label: "设备编码",
			class: "w-100",
			component: "I",
			required: true,
			props: {
				disabled: true
			},
			span: 24
		},
		{
			field: "groupId",
			label: "设备分组",
			class: "w-100",
			required: true,
			component: "VS",
			data: () => groupIdOptions.value,
			props: {
				type: "select",
				valueIsNumber: true,
				clearable: true,
				placeholder: "请选择分组",
				props: {
					label: "name",
					value: "id"
				}
			},
			span: 24
		},

		{
			field: "name",
			label: "设备名称",
			class: "w-100",
			component: "I",
			required: true,
			span: 24
		},
		{
			field: "cycle",
			label: "上报周期",
			class: "w-100",
			component: "I",
			type: "number",
			required: true,
			span: 24
		},
		{
			field: "description",
			label: "设备描述",
			class: "w-100",
			component: "I",
			type: "textarea",
			required: false,
			span: 24
		},
		{
			field: "status",
			label: "设备状态",
			class: "w-100",
			component: "dict",
			props: {
				type: "radio",
				valueIsNumber: true,
				placeholder: "请选择设备状态",
				dictType: "sys_normal_disable"
			},
			span: 24
		}
	] as any,
	resetForm: () => {
		form.value = emptyFormData.value
	},
	modalTitle: "网关",
	emptyFormData: {
		id: undefined,
		parentId: 0,
		groupId: undefined,
		sn: undefined,
		name: undefined,
		type: 1,
		mode: undefined,
		cycle: undefined,
		status: 2,
		description: undefined,
		protocol: undefined,
		address: undefined
	}
})
const { queryParams, emptyFormData } = toRefs(opts)
const form = ref<any>(emptyFormData.value)

/** 添加按钮操作 */
function handleCreate() {
	opts.resetForm()
	isAdd.value = true
	modalRef.value.changePrefixTitle("添加")
	modalRef.value.show()
}
/** 修改按钮操作 */
function handleUpdate(row: any) {
	isAdd.value = false
	tableRef.value.defaultHandleFuns.handleUpdate("", row)
}
/** 删除按钮操作 */
function handleDelete(rows: any[]) {
	tableRef.value.defaultHandleFuns.handleDelete("", rows)
}
/** 提交按钮 */
function submitForm() {
	if (form.value.id != undefined) {
		apis.iot.deviceApi.updateDevice(form.value).then(() => {
			message.msgSuccess("修改成功")
			queryParams.value.orgId = undefined
			handleQuery()
		})
	} else {
		apis.iot.deviceApi.addDevice(form.value).then(() => {
			message.msgSuccess("新增成功")
			queryParams.value.orgId = undefined
			handleQuery()
		})
	}
}

function handleRefresh() {
	message.confirm("确定要重新加载设备吗？", "重新加载").then(() => {
		apis.iot.deviceApi.refresh().then(() => {
			message.msgSuccess("重新加载成功")
			handleQuery()
		})
	})
}

/** 查询按钮 */
function handleQuery() {
	addDateRange(queryParams.value, queryParams.value.dateRange)
	tableRef.value?.search()
	let count = 0
	let timer: any = 0
	function handle() {
		const row = tableRef.value?.getData()[0]
		if (row) {
			clearTimeout(timer)
			emits("query-meter", row.id)
		} else if (count < 50) {
			count++
			timer = setTimeout(handle, 100)
		}
	}
	handle()
}
/** 查询重置按钮 */
function resetQuery() {
	queryParams.value.dateRange = []
	addDateRange(queryParams.value, queryParams.value.dateRange)
}

function handleCreateMeter(row: any) {
	emits("create-meter", row.id)
}
function init() {
	apis.iot.groupApi.listGroup({ pageSize: 10000, pageIndex: 1 }).then((res) => {
		groupIdOptions.value = res.data.rows
	})
}
function onRowClick(row: any) {
	emits("query-meter", row.id)
}

function query(orgId: number) {
	queryParams.value.orgId = orgId
	handleQuery()
}
onMounted(init)
defineExpose({ query })
</script>

<template>
	<div class="w-100 h-100">
		<VbDataTable
			ref="tableRef"
			style="height: 100%"
			:handle-perm="opts.permission"
			:handle-funs="opts.handleFuns"
			:search-form-items="opts.searchFormItems"
			:columns="opts.columns"
			:custom-btns="opts.customBtns"
			:remote-fun="opts.tableListFun"
			:get-entity-fun="opts.getEntityFun"
			:delete-entity-fun="opts.deleteEntityFun"
			:page-size="10"
			:page-size-array="[10, 25, 50]"
			sortField="createdAt"
			sort-order="desc"
			:modal="modalRef"
			:reset-form-fun="opts.resetForm"
			v-model:form-data="form"
			:query-params="queryParams"
			:check-multiple="true"
			:has-checkbox="true"
			:row-click="onRowClick"
			:reset-search-form-fun="resetQuery"
			:custom-search-fun="handleQuery">
			<template #status="{ row }">
				<DictTag valueIsNumber :value="row.status" type="sys_normal_disable"></DictTag>
			</template>
			<template #type="{ row }">
				<DictTag valueIsNumber :value="row.type" type="iot_device_type"></DictTag>
			</template>
			<template #mode="{ row }">
				<DictTag valueIsNumber :value="row.mode" type="iot_device_mode"></DictTag>
			</template>
			<template #onlineStatus="{ row }">
				<VbTag valueIsNumber :value="row.onlineStatus" :data="onlineStatusOptions"></VbTag>
			</template>
			<template #timeOnline="{ row }">
				<span :class="{ 'text-success': row.onlineStatus == 2 }">
					{{ row.timeOnline.Valid ? dayjs(row.timeOnline.Time).format("YYYY-MM-DD HH:mm:ss") : "" }}
				</span>
			</template>
			<template #timeOffline="{ row }">
				<span :class="{ 'text-danger': row.onlineStatus == 1 }">
					{{
						row.timeOffline.Valid ? dayjs(row.timeOffline.Time).format("YYYY-MM-DD HH:mm:ss") : ""
					}}
				</span>
			</template>
			<template #createdAt="{ row }">
				<span>{{ dayjs(row.createdAt).format("YYYY-MM-DD HH:mm:ss") }}</span>
			</template>
			<template #actions="{ row }">
				<vb-tooltip content="修改" placement="top">
					<el-button
						link
						type="primary"
						@click="handleUpdate(row)"
						v-hasPermission="'iot:device: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="'iot:device:remove'">
						<template #icon>
							<VbIcon icon-name="trash-square" icon-type="duotone" class="fs-3"></VbIcon>
						</template>
					</el-button>
				</vb-tooltip>
				<vb-tooltip content="新增表计" placement="top">
					<el-button
						link
						type="danger"
						@click="handleCreateMeter(row)"
						v-hasPermission="'iot:device:add'">
						<template #icon>
							<VbIcon icon-name="plus-square" icon-type="duotone" class="fs-3"></VbIcon>
						</template>
					</el-button>
				</vb-tooltip>
			</template>
		</VbDataTable>
		<VbModal
			v-model:modal="modalRef"
			:title="opts.modalTitle"
			:form-items="opts.formItems as any"
			:form-data="form"
			@confirm="submitForm"
			append-to-body></VbModal>
	</div>
</template>
