<script setup lang="ts">
import { RouterView, useRouter } from "vue-router";
import { createWebSocket, sharedWsUrl } from "./services/socket";
import { useEquipmentStatusStore } from "@/stores/equipmentStatus";
import { onMounted, ref } from "vue";
import { getList } from "./services/matrix/manage";
import { useSettingStore } from "./stores/setting";
import Dialog, { type DialogParam } from "./components/Dialog.vue";
import { pushOutTray } from "./services/globalCmd/globalCmd";
import { ElMessage } from "element-plus";

const equipmentStatusStore = useEquipmentStatusStore();
const settingStore = useSettingStore();
const router = useRouter();

const wsClient = createWebSocket(sharedWsUrl);
wsClient.dataOb.subscribe(data => {
	if (data.type === "ing") {
		equipmentStatusStore.setWorkStatus(data.data.workStatus);
	} else if (data.type === "status") {
		equipmentStatusStore.setEquipmentStatus(data["data"]);
	} else if (data.type === "warn") {
		if (data.data.code === "wash_complete") {
			dialogContent.value = {
				desc: "清洗管道已经完成",
				type: "alert",
			};
			showDialog.value = true;
		} else if (data.data.code === "prefill_complete") {
			dialogContent.value = {
				desc: "预充管道已经完成",
				type: "alert",
			};
			showDialog.value = true;
		} else if (data.data.code === "dehumidify_complete") {
			dialogContent.value = {
				desc: "湿度已达到设定值，氮气已置换完毕。",
				type: "confirm",
				okText: "去喷涂",
				_brand: "dehumidify_complete",
			};
			showDialog.value = true;
		} else if (data.data.code === "spray_complete") {
			dialogContent.value = {
				desc: "喷涂完成",
				type: "confirm",
				okText: "推出玻片",
				cancelText: "确认完成",
				_brand: "spray_complete",
			};
			showDialog.value = true;
		} else if (data.data.code === "error") {
			dialogContent.value = {
				title: "错误",
				desc: data.data.msg,
				type: "alert",
			};
			showDialog.value = true;
		}
	}
});
wsClient.connect();

onMounted(() => {
	getList({ pageNum: 1, pageSize: 9999 }).then(res => {
		if (res.success) {
			const { list } = res.data;
			settingStore.setMatrixList(list);
		}
	});
});

const dialogContent = ref<DialogParam>({ desc: "描述" });

const showDialog = ref(false);

function onOk() {
	showDialog.value = false;
	if (dialogContent.value._brand === "dehumidify_complete") {
		router.push("/spray");
	} else if (dialogContent.value._brand === "spray_complete") {
		pushOutTray({}).then(res => {
			if (res.success) {
				ElMessage.success("正在推出");
			} else {
				ElMessage.error(res.msg);
			}
		});
	}
}
</script>

<template>
	<RouterView />
	<van-overlay v-if="showDialog" :show="true">
		<div class="flex justify-center items-center h-full">
			<Dialog
				:title="dialogContent.title"
				:desc="dialogContent.desc"
				:type="dialogContent.type"
				:ok-text="dialogContent.okText"
				:cancel-text="dialogContent.cancelText"
				@on-ok="onOk"
				@on-cancel="showDialog = false"></Dialog>
		</div>
	</van-overlay>
</template>
<style lang="scss" scoped></style>
