<template>
	<div class="px-6 pt-4 pb-3 flex justify-between">
		<div class="w-full">
			<div class="flex items-center mb-3 gap-5">
				<button :disabled="statusStore.workStatus !== 'idle'" class="btn-dark px-8 py-2 text-lg" @click="onStartSpray">
					开始喷涂
				</button>
				<button
					:disabled="statusStore.workStatus !== 'spraying'"
					class="btn-light px-8 py-2 text-lg"
					@click="onStopSpray">
					停止喷涂
				</button>
				<section class="flex items-center gap-3 px-4 text-base ml-auto">
					<div class="flex items-center">
						<span class="self-center text-right text-primary font-medium mr-3">选择基质</span>
						<el-select v-model="selectMatrixId" placeholder="Select" style="width: 120px" @change="onMatrixChange">
							<el-option
								v-for="item in settingStore.matrixList"
								:key="item.id"
								:label="item.name"
								:value="item.id" />
						</el-select>
					</div>
					<div class="flex items-center">
						<span class="self-center text-right text-primary font-medium mr-3">工艺</span>
						<el-select
							:disabled="craftList.length === 0"
							v-model="selectCraftId"
							placeholder="Select"
							style="width: 120px"
							@change="onCraftChange">
							<el-option v-for="item in craftList" :key="item.id" :label="item.name" :value="item.id" />
						</el-select>
					</div>
					<el-popover placement="bottom" :width="380" trigger="click">
						<template #reference>
							<div class="text-primary underline flex items-center gap-1">
								<span>{{ craftList.length === 0 ? "设置参数" : "详细参数" }}</span>
								<img src="@/assets/icon_info.svg" alt="info" />
							</div>
						</template>
						<template #default>
							<SprayParam
								ref="sprayParamRef"
								:sprayParam="selectCraft"
								save-title="保存至工艺"
								@save="updateSprayParam" />
						</template>
					</el-popover>
				</section>
			</div>

			<section class="flex flex-col items-start">
				<section class="flex">
					<Spray
						:width="210"
						:height="610"
						:left-padding="4"
						:right-padding="4"
						:top-padding="4"
						:bottom-padding="4"
						:columns="1"
						:rows="3"
						:cell-num="25"
						@select-area="area => onSelectArea(area, 0)" />
					<Spray
						:width="210"
						:height="610"
						:left-padding="4"
						:right-padding="4"
						:top-padding="4"
						:bottom-padding="4"
						:columns="1"
						:rows="3"
						:cell-num="25"
						@select-area="area => onSelectArea(area, 1)" />
					<Spray
						:width="210"
						:height="610"
						:left-padding="4"
						:right-padding="4"
						:top-padding="4"
						:bottom-padding="4"
						:columns="1"
						:rows="3"
						:cell-num="25"
						@select-area="area => onSelectArea(area, 2)" />
					<Spray
						:width="210"
						:height="610"
						:left-padding="4"
						:right-padding="4"
						:top-padding="4"
						:bottom-padding="4"
						:columns="1"
						:rows="3"
						:cell-num="25"
						@select-area="area => onSelectArea(area, 3)" />
				</section>

				<van-checkbox-group
					shape="square"
					v-model="checked"
					checked-color="#26509c"
					icon-size="28px"
					direction="horizontal"
					class="flex justify-around mt-3 w-[848px]">
					<van-checkbox name="0"></van-checkbox>
					<van-checkbox name="1"></van-checkbox>
					<van-checkbox name="2"></van-checkbox>
					<van-checkbox name="3"></van-checkbox>
				</van-checkbox-group>
			</section>
		</div>
	</div>
</template>

<script setup lang="ts">
import Spray, { type GridArea } from "@/components/Spray.vue";
import { onMounted, ref, useTemplateRef } from "vue";
import { startSpray, stopWork } from "@/services/globalCmd/globalCmd";
import { checkSprayParamValid, type PositionType, type WorkType } from "@/services/globalCmd/cmdTypes";
import { ElMessage } from "element-plus";
import { useSettingStore } from "@/stores/setting";
import type { CraftItem } from "@/services/matrix/type";
import { createCraft, getListByMatrixId, updateCraft } from "@/services/matrix/craft";
import SprayParam from "@/components/SprayParam.vue";
import { useEquipmentStatusStore } from "@/stores/equipmentStatus";

const defaultCraft: Partial<CraftItem> = {
	id: 0,
	name: "default",
	matrixId: 0,
	routeType: 1,
	space: undefined,
	nitrogenFlowVelocity: undefined,
	nitrogenAirPressure: undefined,
	matrixFlowVelocity: undefined,
	voltage: undefined,
	needPower: false,
	height: undefined,
	movementSpeed: undefined,
	position: [],
};

const settingStore = useSettingStore();
const statusStore = useEquipmentStatusStore();
const selectMatrixId = ref<number>(settingStore.matrixList.length > 0 ? settingStore.matrixList[0].id : 0);

const craftList = ref<CraftItem[]>([]);

const selectCraftId = ref<number>(1);
const selectCraft = ref<Partial<CraftItem>>(defaultCraft);

const selectedArea = ref<GridArea[]>([
	{ xStart: 8, yStart: 8, xEnd: 16, yEnd: 16 },
	{ xStart: 8, yStart: 8, xEnd: 16, yEnd: 16 },
	{ xStart: 8, yStart: 8, xEnd: 16, yEnd: 16 },
	{ xStart: 8, yStart: 8, xEnd: 16, yEnd: 16 },
]);

const checked = ref(["0"]);

onMounted(() => {
	if (settingStore.matrixList.length > 0) {
		onMatrixChange(settingStore.matrixList[0].id);
	}
});

function onSelectArea(area: GridArea, index: number) {
	selectedArea.value[index] = area;
}

function onMatrixChange(val: number) {
	selectMatrixId.value = val;
	getListByMatrixId({ matrixId: val }).then(res => {
		if (res.success) {
			craftList.value = res.data || [];
			if (res.data.length > 0) {
				selectCraftId.value = res.data[0].id;
				selectCraft.value = { ...res.data[0], needPower: res.data[0].voltage > 0 };
			} else {
				selectCraftId.value = 0;
				selectCraft.value = defaultCraft;
			}
		} else {
			ElMessage.error(res.msg);
		}
	});
}

function onCraftChange(val: number) {
	const craft = craftList.value.find(item => item.id === val);
	selectCraft.value = { ...craft, needPower: craft!.voltage > 0 };
}

function mapAreaToPosition() {
	return checked.value.map(index => {
		const idx = +index;
		const pos: PositionType = {
			x1: selectedArea.value[idx].xStart,
			y1: selectedArea.value[idx].yStart,
			x2: selectedArea.value[idx].xEnd,
			y2: selectedArea.value[idx].yEnd,
			index: idx,
		};
		return pos;
	});
}
const sprayParamRef = ref();

function onStartSpray() {
	if (checked.value.length === 0) {
		ElMessage.error("请至少选择一个玻片");
		return;
	}

	// 把参数弹窗中的数据 应用过来
	const params = { ...selectCraft.value, ...sprayParamRef.value.sprayParam };
	params.position = mapAreaToPosition();
	if (!params.needPower) {
		params.voltage = 0;
	}
	// console.log(params);

	const check = checkSprayParamValid(params);
	if (!check[0]) {
		ElMessage.error(check[1]);
		return;
	}

	startSpray({
		...(params as CraftItem),
		matrixId: selectMatrixId.value,
		matrixCraftId: selectCraft.value.id || 0,
	}).then(res => {
		if (res.success) {
		} else {
			ElMessage.error(res.msg);
		}
	});
}

function onStopSpray() {
	stopWork().then(res => {
		if (res.success) {
		} else {
			ElMessage.error(res.msg);
		}
	});
}

function updateSprayParam(p: WorkType) {
	console.log(p);
	const params = !!p.needPower ? p : { ...p, voltage: 0 };
	if ((params as CraftItem).id === 0) {
		// 创建
		const p = { ...(params as CraftItem), matrixId: selectMatrixId.value };
		createCraft(p).then(res => {
			if (res.success) {
				onMatrixChange(selectMatrixId.value);
			} else {
				ElMessage.error(res.msg);
			}
		});
	} else {
		// 更新
		updateCraft(params as CraftItem).then(res => {
			if (res.success) {
				selectCraft.value = params as CraftItem;
			} else {
				ElMessage.error(res.msg);
			}
		});
	}
}
</script>

<style lang="scss" scoped>
:deep(.el-collapse-item__header) {
	background-color: transparent;
}
:deep(.el-collapse-item__wrap) {
	background-color: transparent;
}
</style>
