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

const props = withDefaults(defineProps<{ id: number }>(), { id: 0 })
const { id: parentId } = toRefs(props)
const protocolOptions = ref<any[]>([])
const reportProtocolOptions = ref<any[]>([])
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: "sn", name: "设备编码", width: "auto", isSort: true, visible: true },
		{ field: "name", name: "表计名称", width: "auto", isSort: true, visible: true },
		// { field: "type", name: "设备类型", width: 100, isSort: true, visible: true },
		{ field: "protocol", name: "表计协议", width: 200, isSort: true, visible: true },
		{ field: "address", name: "表计串口地址", width: 130, isSort: false, visible: true },
		// { field: "mode", name: "设备模式", width: 180, isSort: false, visible: true },
		{ field: "createdAt", name: "创建时间", width: 185, isSort: true, visible: true },
		{ field: "actions", name: `操作`, width: 150 }
	],
	queryParams: {
		parentId: parentId.value,
		sn: undefined,
		name: undefined,
		type: 2,
		dateRange: []
	},
	searchFormItems: [
		{
			field: "sn",
			label: "设备编码",
			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: "dateRange",
			label: "创建时间",
			class: "w-100",
			component: "D",
			placeholder: "请选择创建时间",
			props: {
				type: "daterange",
				valueFormat: "YYYY-MM-DD",
				rangeSeparator: "-",
				startPlaceholder: "开始日期",
				endPlaceholder: "结束日期"
			},
			listeners: {
				change: (v: any) => {
					queryParams.value.dateRange = v
				}
			}
		}
	] as any,
	permission: "",
	handleFuns: {},
	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
		},
		{
			show: false,
			field: "mode",
			label: "设备模式",
			class: "w-100",
			required: false,
			component: "Dict",
			props: {
				disabled: true,
				type: "radio",
				valueIsNumber: true,
				clearable: true,
				placeholder: "请选择设备模式",
				dictType: "iot_device_mode"
			},
			span: 24
		},
		{
			field: "name",
			label: "设备名称",
			class: "w-100",
			component: "I",
			required: true,
			span: 24
		},
		{
			field: "protocol",
			label: "表计协议",
			class: "w-100",
			required: true,
			component: "VS",
			placeholder: "请选择表计协议",
			data: () => protocolOptions.value,
			props: {
				type: "select",
				clearable: true
			},
			span: 12
		},
		{
			field: "address",
			label: "表计地址",
			class: "w-100",
			component: "I",
			type: "number",
			required: true,
			span: 12
		},
		{
			field: "dsn",
			label: "平台上报",
			class: "w-100",
			component: "slot",
			span: 24
		},
		{
			field: "bmYz",
			label: "编码因子",
			class: "w-100",
			component: "I",
			type: "textarea",
			required: false
		},
		{
			field: "description",
			label: "设备描述",
			class: "w-100",
			component: "I",
			type: "textarea",
			required: false
		}
	] as any,
	modalTitle: "表计",
	resetForm: () => {
		form.value = emptyFormData.value
	},
	emptyFormData: {
		id: undefined,
		parentId: parentId.value,
		groupId: undefined,
		sn: undefined,
		name: undefined,
		type: 2,
		mode: undefined,
		reportConfig: [
			{
				host: "",
				protocol: "",
				st: "",
				mn: "",
				user: "",
				pwd: ""
			}
		],
		protocol: undefined,
		address: undefined,
		bmYz: undefined,
		description: undefined
	}
})
const { queryParams, emptyFormData } = toRefs(opts)
const form = ref<any>(Object.assign({}, emptyFormData.value))

function handleCreate(parentId: number) {
	isAdd.value = true
	form.value.parentId = parentId
	form.value.reportConfig = [
		{
			host: "",
			protocol: "",
			st: "",
			mn: "",
			user: "",
			pwd: ""
		}
	]
	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("修改成功")
			handleQuery()
		})
	} else {
		apis.iot.deviceApi.addDevice(form.value).then(() => {
			message.msgSuccess("新增成功")
			handleQuery()
		})
	}
}
/** 查询按钮 */
function handleQuery() {
	addDateRange(queryParams.value, queryParams.value.dateRange)
	tableRef.value?.search()
}
/** 查询重置按钮 */
function resetQuery() {
	queryParams.value.dateRange = []
	addDateRange(queryParams.value, queryParams.value.dateRange)
}

function handelAddReportConfig() {
	form.value.reportConfig.push({
		host: "",
		protocol: "",
		st: "",
		mn: "",
		user: "",
		pwd: ""
	})
}

function handelRemoveReportConfig(index: number) {
	message.confirm("是否确认删除第" + (index + 1) + "条上报配置?", "删除配置").then(() => {
		form.value.reportConfig.splice(index, 1)
	})
}

function init() {
	apis.iot.deviceApi.getDeviceProtocols().then((res: any) => {
		protocolOptions.value = res.data.map((v: any) => {
			return {
				label: v,
				value: v
			}
		})
	})
	apis.iot.deviceApi.getReportProtocols().then((res: any) => {
		reportProtocolOptions.value = res.data.map((v: any) => {
			return {
				label: v,
				value: v
			}
		})
	})
}
function createMeter(id: number) {
	handleCreate(id)
}
onMounted(init)
watch(
	() => props.id,
	(val: any) => {
		parentId.value = val
		queryParams.value.parentId = val
		handleQuery()
	}
)
defineExpose({
	createMeter
})
</script>

<template>
	<div class="w-100 h-100">
		<VbDataTable
			ref="tableRef"
			style="height: 100%"
			:init-search="false"
			:show-right-toolbar="false"
			:show-search-bar="false"
			:show-toolbar="false"
			:page-size="5"
			:page-size-array="[5, 10, 25]"
			: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"
			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"
			:reset-search-form-fun="resetQuery"
			:custom-search-fun="handleQuery">
			<template #groupId="{ row }">
				{{ row.group?.Name }}
			</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 #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>
			</template>
		</VbDataTable>
		<VbModal
			v-model:modal="modalRef"
			:title="opts.modalTitle"
			:form-items="opts.formItems as any"
			:form-data="form"
			@confirm="submitForm"
			append-to-body>
			<template #dsn_form="">
				<div
					class="w-100 px-5 mb-3"
					v-for="(item, index) in form.reportConfig"
					:key="index"
					style="border: 2px solid var(--bs-primary); border-radius: 10px">
					<div class="d-flex justify-content-between">
						<span class="text-danger fw-bold">配置 {{ index + 1 }}</span>
						<span>
							<vb-tooltip
								v-if="index === form.reportConfig.length - 1"
								type="primary"
								icon="ki-duotone ki-plus"
								content="添加上报配置"
								placement="top">
								<el-button link type="primary" @click="handelAddReportConfig()">
									<template #icon="">
										<VbIcon icon-name="plus-square" icon-type="duotone" class="fs-3"></VbIcon>
									</template>
								</el-button>
							</vb-tooltip>
							<vb-tooltip
								v-if="form.reportConfig.length > 1"
								content="删除上报配置"
								placement="top">
								<el-button link type="primary" @click="handelRemoveReportConfig(index)">
									<template #icon="">
										<VbIcon icon-name="trash-square" icon-type="duotone" class="fs-3"></VbIcon>
									</template>
								</el-button>
							</vb-tooltip>
						</span>
					</div>
					<el-row :gutter="10">
						<el-col :span="12">
							<el-form-item
								label="HOST"
								:prop="`reportConfig.${index}.host`"
								:rules="{ required: true, message: '请输入HOST(IP:端口)', trigger: 'blur' }">
								<el-input
									v-model="form.reportConfig[index].host"
									@change="console.log('change', form)"
									placeholder="请输入HOST(IP:端口)" />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item
								label="协议"
								:prop="`reportConfig.${index}.protocol`"
								:rules="{ required: true, message: '请选择上报协议', trigger: 'blur' }">
								<el-select
									v-model="form.reportConfig[index].protocol"
									placeholder="请输入平台上报协议">
									<el-option
										v-for="(v, i) in reportProtocolOptions"
										:label="v.label"
										:value="v.value"
										:key="i"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item
								label="指令(ST)"
								:prop="`reportConfig.${index}.st`"
								:rules="{ required: true, message: '请输入平台指令', trigger: 'blur' }">
								<el-input v-model="form.reportConfig[index].st" placeholder="请输入平台指令" />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item
								label="编码(MN)"
								:prop="`reportConfig.${index}.mn`"
								:rules="{ required: true, message: '请输入表计编码', trigger: 'blur' }">
								<el-input v-model="form.reportConfig[index].mn" placeholder="请输入表计编码" />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="用户" :prop="`reportConfig.${index}.user`">
								<el-input v-model="form.reportConfig[index].user" placeholder="请输入平台用户" />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="密码" :prop="`reportConfig.${index}.pwd`">
								<el-input v-model="form.reportConfig[index].pwd" placeholder="请输入平台密码" />
							</el-form-item>
						</el-col>
					</el-row>
				</div>
			</template>
		</VbModal>
	</div>
</template>
