<template>
	<page-container>
		<template #ops>
			<a-row>
				<a-col :span="18">
					<a-input-search
						v-model:value="searchKey"
						:placeholder="`请输入设备号/工位名称`"
						allow-clear
						enter-button
						@search="loadData()"
					></a-input-search>
				</a-col>
				<a-col :span="6">
					<a-button type="primary" style="margin-left: 10px" @click="addOrEdit()">
						<template #icon>
							<icon-font type="icon-plus" />
						</template>
						添加
					</a-button>
				</a-col>
			</a-row>
		</template>
		<div style="min-height: calc(100vh - 305px)">
			<a-table
				:columns="columns"
				:data-source="stationPage?.records"
				bordered
				:pagination="pagination"
				:loading="loading"
				row-key="id"
			>
				<template #bodyCell="{ column, record }">
					<template v-if="column.dataIndex === 'key'">
						<a-typography-link
							href="javascript:;"
							:style="{ color: token.colorPrimary }"
							@click="showDetail(record as station.Station)"
						>
							{{ record.key }}
						</a-typography-link>
					</template>
					<template v-if="column.dataIndex === 'channel'">通道 #{{ record.channel }}</template>
					<template v-if="column.dataIndex === 'operation'">
						<a-button type="link" :style="{ color: token.colorPrimary }" @click="addOrEdit(record)">
							<template #icon>
								<icon-font type="icon-edit" />
							</template>
							编辑
						</a-button>
						<a-popconfirm :title="`确定需要删除设备 ${record.name}(${record.key}) 吗？`" @confirm="remove(record.id)">
							<a-button type="link" danger style="margin-left: 10px">
								<template #icon>
									<icon-font type="icon-delete" />
								</template>
								删除
							</a-button>
						</a-popconfirm>
					</template>
				</template>
			</a-table>
		</div>
	</page-container>
	<form-drawer
		ref="formDrawer"
		v-model="station"
		:form-items="items"
		:config="formConfig"
		:title="modalTitle"
		@ok="doSave"
	>
		<template #after-name>
			<a-row>
				<a-col :span="12">
					<a-form-item
						label="设备绑定"
						name="key"
						:rules="[{ required: true, message: '请选择设备' }]"
						:label-col="{ span: 8 }"
					>
						<a-select
							v-model:value="station.key"
							show-search
							placeholder="请输入设备名称/编码"
							:default-active-first-option="false"
							:show-arrow="false"
							:filter-option="false"
							not-found-content="没有找到设备"
							:field-names="{ label: 'name', value: 'key' }"
							allow-clear
							:options="sensors"
							@search="handleSearch"
						></a-select>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item
						label="设备通道"
						name="channel"
						:rules="[{ required: true, message: '请选择通道' }]"
						:label-col="{ span: 8 }"
					>
						<a-select
							v-model:value="station.channel"
							allow-clear
							placeholder="请选择设备通道"
							:options="channels"
						></a-select>
					</a-form-item>
				</a-col>
			</a-row>
		</template>
		<template #after-maxGap>
			<a-slider
				v-model:value="range"
				:tip-formatter="formatter"
				dots
				range
				:marks="marks"
				:max="station.working ? station.working * 1.1 : 100"
				:step="station.working ? Math.floor((station.working < 20 ? 20 : station.working) / 20) : 100 / 20"
			/>
		</template>
	</form-drawer>
</template>

<script setup lang="ts">
	import FormDrawer from '@/components/form-render/form-drawer.vue'

	import api from '@/api'
	import { IPage } from '@/api/api'
	import { notification, SelectProps, theme } from 'ant-design-vue/es'
	import { config, formItems } from './form'
	import { FormDataType } from '@/components/form-render/form-render-types'
	import { SliderMarks } from 'ant-design-vue/es/slider'
	const { useToken } = theme
	const { token } = useToken()
	const searchKey = ref('')

	const stationPage = ref<IPage<station.Station>>()
	const loading = ref(false)
	const loadData = async (page = 1, size = 10) => {
		loading.value = true
		api.stationApi.station.stations(
			{ page: page || stationPage.value?.current, size: size || stationPage.value?.size, key: searchKey.value },
			(data) => {
				loading.value = false
				stationPage.value = data
			},
		)
	}
	loadData()

	//表格列
	const columns = [
		{
			title: '设备编号',
			dataIndex: 'key',
		},
		{
			title: '设备通道',
			dataIndex: 'channel',
		},
		{
			title: '工位名称',
			dataIndex: 'name',
		},
		{
			title: '待机电流(安培)',
			dataIndex: 'standby',
		},
		{
			title: '工作电流(安培)',
			dataIndex: 'working',
		},
		{
			title: '最大工作间歇(秒)',
			dataIndex: 'maxGap',
		},
		{
			title: '操作',
			dataIndex: 'operation',
			width: 400,
		},
	]

	//分页信息
	const pagination = computed(() => {
		return {
			current: stationPage.value?.current,
			pageSize: stationPage.value?.size,
			total: stationPage.value?.total,
			onChange: (page: number, pageSize: number) => {
				loadData(page, pageSize)
			},
		}
	})
	const router = useRouter()
	const showDetail = (_station: station.Station) => {
		router.push({ name: 'station-detail', params: { key: _station.uid } })
	}

	const station = ref<Partial<station.Station>>({})

	const range = computed({
		get: () => {
			return [station.value.standby ?? 10, station.value.working ?? 100] as [number, number]
		},
		set: (val) => {
			station.value.standby = val[0]
			station.value.working = val[1]
		},
	})

	const marks = computed(() => {
		const standby = station.value.standby ?? 10
		const working = station.value.working ?? 100
		const a: SliderMarks = {}
		a[standby] = `${standby} A`
		a[working] = `${working} A`
		return a as SliderMarks
	})

	const formatter = (value?: number) => {
		if (value === station.value.standby) {
			return `待机电流: ${value} A`
		}
		if (value === station.value.working) {
			return `工作触发电流: ${value} A`
		}
		return `${value}`
	}
	//表单
	const formDrawer = ref<typeof FormDrawer>()

	const formConfig = computed(() => {
		return config
	})
	//表单配置
	const items = computed(() => {
		return formItems
	})

	//弹窗标题
	const modalTitle = computed(() => {
		return station.value.id ? '编辑工位' : '添加工位'
	})

	const addOrEdit = (u?: Record<string, unknown>) => {
		station.value = { ...u }
		formDrawer.value?.show()
	}
	const doSave = (_data: FormDataType) => {
		const f = station.value.id ? api.stationApi.station.update : api.stationApi.station.add
		f(_data as unknown as station.Station, (data) => {
			console.log(data)
			formDrawer.value?.close()
			notification.success({
				message: '操作成功',
				description: '工位信息保存成功,页面将自动刷新!',
				onClose: () => {
					loadData(1)
				},
			})
		})
	}
	const remove = (id: number) => {
		api.stationApi.station.deleteStation(id, () => {
			notification.success({
				message: '操作成功',
				description: '工位信息删除成功,页面将自动刷新!',
				onClose: () => {
					loadData(1)
				},
			})
		})
	}

	const sensors = ref<Array<sensor.Sensor>>([])
	const handleSearch = (val: string) => {
		api.sensorApi.sensor.sensors({ key: val }, (data) => {
			sensors.value = data.records ?? []
		})
	}
	const channels = ref<SelectProps['options']>([])
	watch(
		() => {
			return station.value.key
		},
		(val) => {
			if (val)
				api.sensorApi.sensor.channels(val, (data) => {
					channels.value = data.map((item) => {
						return {
							label: item.label,
							value: Number(item.value),
							disabled: item.disabled,
						}
					})
				})
		},
		{ immediate: true, deep: true },
	)

	watch(
		() => {
			return station.value.key
		},
		(val) => {
			if (val) handleSearch(val)
		},
		{ immediate: true },
	)
</script>
