<template>
	<table class="table" style="font-family: monospace;" v-if="appointments && appointments.length > 0">
		<thead>
			<tr><th>Time</th><th>Clinic</th><th>Patient</th><th>Note</th><th>Assignee</th></tr>
		</thead>
		<tbody>
			<tr v-for="row in appointments" :style="{ backgroundColor: strHashHSL(row.Clinic, '90%') }">
				<td>{{row.ApptDate}}</td>
				<td>{{row.Clinic}}</td>
				<td v-if="production"><router-link :to="'/patient/$' + row.HRN">{{row.Name}} ${{row.HRN}}</router-link></td>
				<td v-else><router-link :title="strtr_unscramble(row.Name)" :to="'/patient/$' + row.Name.charAt(0) + row.HRN.slice(-4) + '?name=' + row.Name">{{row.Name}} ${{row.HRN}}</router-link></td>
				<td>{{row.NOTE}} [{{row.APPT_MADE_BY}} on {{row.DATE_APPT_MADE}}]</td>
				<td><Autocomplete :value="practitioner[row.Name]" @update:value="x => set_practitioner(row.Name, x)" :items="practitioner_list" /></td>
			</tr>
		</tbody>
	</table>
</template>

<script>
	import cookie from './cookie.mjs';
	import { uniq, strtr_unscramble, strHashHSL, strfdate_vista, debounce } from './util.mjs';

	import Autocomplete from './Autocomplete.vue';

	export default {
		components: {
			Autocomplete
		},
		props: {
			client: Object,
			selection: {
				type: Array,
				default: []
			},
			date_begin: Date,
			date_end: Date
		},
		data() {
			return {
				appointments: [],
				practitioner: {},
				production: true
			};
		},
		computed: {
			params() {
				return { selection: this.selection, date_begin: this.date_begin, date_end: this.date_end };
			},
			practitioner_list() {
				return this.practitioner ? uniq(Object.values(this.practitioner)).sort() : [];
			}
		},
		watch: {
			params(value) {
				this.debounced_params(value);
			}
		},
		methods: {
			strHashHSL,
			strtr_unscramble,
			set_practitioner(patient, practitioner) {
				this.practitioner[patient] = practitioner;
				cookie.set('vista.practitioner', JSON.stringify(this.practitioner), 1);
			}
		},
		created() {
			this.debounced_params = debounce(async function(value) { this.appointments = value.selection.length > 0 ? (await this.client.SDEC_CLINLET(value.selection.join('|') + '|', strfdate_vista(value.date_begin), strfdate_vista(value.date_end))).sort((a, b) => (new Date(a.ApptDate)) - (new Date(b.ApptDate))) : []; }, 500);
		},
		async mounted() {
			var practitioner = cookie.get('vista.practitioner');
			if(practitioner) this.practitioner = JSON.parse(practitioner);
			this.production = (await this.client.serverinfo()).result.production == '1';
		}
	};
</script>
