<template>
	<ViewOrderDialogLab v-if="x_form_id == constants.OD_LAB" :client="client" :ien="ien" :dlgdef="dlgdef" :bldqrsp="bldqrsp" @submit="submit" />
	<ViewOrderDialogMedOutpt v-else-if="x_form_id == constants.OD_MEDOUTPT" :client="client" :ien="ien" :dlgdef="dlgdef" :bldqrsp="bldqrsp" @submit="submit" />
	<ViewOrderDialogGeneric v-else-if="x_form_id == constants.OD_RTC" :client="client" :ien="ien" :dfn="dfn" :location_ien="location_ien" :dlgname="dlgname" :dlgdef="dlgdef" @submit="submit" />
	<ViewOrderDialogGeneric v-else-if="x_form_id" :client="client" :ien="ien" :dfn="dfn" :location_ien="location_ien" :dlgname="dlgname" :dlgdef="dlgdef" @submit="submit" />
</template>

<script>
	import * as constants from './constants.mjs';
	import ViewOrderDialogLab from './ViewOrderDialogLab.vue';
	import ViewOrderDialogMedOutpt from './ViewOrderDialogMedOutpt.vue';
	import ViewOrderDialogGeneric from './ViewOrderDialogGeneric.vue';

	export default {
		components: {
			ViewOrderDialogLab, ViewOrderDialogMedOutpt, ViewOrderDialogGeneric
		},
		props: {
			client: Object,
			ien: String,
			form_id: String,
			dfn: String,
			location_ien: String
		},
		emits: {
			'update:form_id': Number
		},
		data() {
			return {
				constants,
				dlgname: null,
				dlgdef: null,
				prompts: null,
				inputs: null,
				bldqrsp: null,
				odslct: null,
				x_form_id: this.form_id
			};
		},
		methods: {
			async submit(payload) {
				if((this.ien) && (this.dfn) && (payload)) {
					var user_ien = (await this.client.userinfo()).result[0];
					var dgrp = await this.client.ORWDX_DGRP(this.dlgname.BaseDialogName);
					var res = await client.ORWDX_SAVE(this.dfn, 0/*user_ien*/, 0/*location_ien*/, this.dlgname.BaseDialogName, dgrp, this.dlgname.BaseDialogIEN, ''/*order_ifn*/, payload, '', '', '', 0);
					console.log(res);
				}
			}
		},
		created() {
			this.$watch(
				() => (this.client, this.ien, {}),
				async () => {
					if((this.client) && (this.ien)) {
						var userinfo = await this.client.userinfo();
						var user_ien = userinfo && userinfo.result ? userinfo.result[0] : '';
						this.dlgname = await this.client.ORWDXM_DLGNAME(this.ien);
						if(this.dlgname.BaseDialogIEN != this.ien) console.warn('IEN =', this.ien, '|', 'BaseDialogIEN =', this.dlgname.BaseDialogIEN);
						this.dlgdef = await this.client.ORWDX_DLGDEF(this.dlgname.BaseDialogName);
						if(this.bldqrsp = (await this.client.ORWDXM1_BLDQRSP(this.ien, '^^' + user_ien + '^^^^;;;^^^^', 0, 0))[0]) this.$emit('update:form_id', this.x_form_id = +this.bldqrsp.FormID);
					} else {
						this.dlgname = this.dlgdef = this.bldqrsp = null;
						this.x_form_id = +this.form_id;
					}
					if(this.x_form_id == constants.OD_RTC) this.odslct = await client.ORWDSD1_ODSLCT(0, 0);
				},
				{ immediate: true }
			);
		}
	};
</script>
