<template>
	<table v-if="details.length > 0" class="table table-striped">
		<template v-for="group in details">
			<thead>
				<tr>
					<th>{{map_groups[group.key].name}}</th>
					<th>Practitioner</th>
					<th style="text-align: right;">Status</th>
				</tr>
			</thead>
			<tbody>
				<tr v-for="item in group.values">
					<td><div v-for="line in item.text">{{line}}</div></td>
					<td>
						<div v-if="item.PrvNam" :title="item.PrvID">{{item.PrvNam}}</div>
						<div v-if="item.Nrs">Nurse: {{item.Nrs}}</div>
						<div v-if="item.Clk">Clerk: {{item.Clk}}</div>
						<div v-if="item.ChartRev">Chart: {{item.ChartRev}}</div>
						<div v-if="item.LOC">{{item.LOC.split(':')[0]}}</div>
					</td>
					<td style="text-align: right;">
						<div v-if="item.Sts">{{name_of_status[item.Sts]}}</div>
						<div v-if="item.OrdTm">Ordered: {{strptime_vista(item.OrdTm).toLocaleDateString('en-CA')}}</div>
						<div v-if="item.StrtTm">Start: {{strptime_vista(item.StrtTm).toLocaleDateString('en-CA')}}</div>
						<div v-if="item.StopTm">Stop: {{strptime_vista(item.StopTm).toLocaleDateString('en-CA')}}</div>
					</td>
				</tr>
			</tbody>
		</template>
	</table>
</template>

<style scoped>
	th {
		text-transform: lowercase;
	}
	th::first-letter {
		text-transform: uppercase;
	}
</style>

<script>
	import { groupByArray, strftime_vista, strptime_vista } from './util.mjs';

	const name_of_status = {
		0:	'Error',
		1:	'Discontinued',
		2:	'Complete',
		3:	'Hold',
		4:	'Flagged',
		5:	'Pending',
		6:	'Active',
		7:	'Expired',
		8:	'Scheduled',
		9:	'Partial results',
		10:	'Delayed',
		11:	'Unreleased',
		12:	'DC/edit',
		13:	'Cancelled',
		14:	'Lapsed',
		15:	'Renewed',
		97:	'',
		98:	'New',
		99:	'No status'
	};

	export default {
		props: {
			client: Object,
			dfn: String,
			filter: { default: 2 },
			group: { default: 1 },
			date_begin: Date,
			date_end: Date
		},
		data() {
			return {
				orders: [],
				details: [],
				map_groups: {},
				name_of_status
			};
		},
		computed: {
			params() {
				return { dfn: this.dfn, filter: this.filter, group: this.group, date_begin: strftime_vista(this.date_begin), date_end: strftime_vista(this.date_end) };
			}
		},
		watch: {
			async params(value) {
				this.orders = await this.client.ORWORR_AGET(value.dfn, value.filter, value.group, value.date_begin, value.date_end);
			},
			async orders(value) {
				this.details = this.orders.length > 0 ? groupByArray(await this.client.ORWORR_GET4LST(0, 0, value.map(x => x.ifn)), x => x.Grp) : [];
			}
		},
		methods: {
			strptime_vista
		},
		async mounted() {
			this.map_groups = (await this.client.ORWORDG_ALLTREE()).reduce((acc, x) => (acc[x.ien] = x, acc), {});
		}
	};
</script>
